【问题标题】:How to use a filter to handle exception that are throws in the servlet如何使用过滤器来处理 servlet 中抛出的异常
【发布时间】:2018-12-27 07:40:37
【问题描述】:

我的目的是创建一个过滤器来处理 servlet 中抛出的异常。

假设我有这个过滤器:

public class FiltroAccess implements Filter{

    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        //handle exception

    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }
}

在我的servlet 中,我抛出了Exception

我该怎么做才能在我的过滤器中处理异常?

谁能帮帮我?

【问题讨论】:

    标签: java servlets filter servlet-filters


    【解决方案1】:

    只需将过滤器链调用包含在 try/catch 块中:

    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        try {
            arg2.doFilter(arg0, arg1);
        }
        catch (Exception e) {
            // Handle exception here
        }
    }
    

    唯一的问题是 ServletResponse 已经提交(发送到客户端),您将无法更改标头。

    【讨论】:

    • 它不起作用,因为过滤器没有进入catch块。抛出异常时我需要调用过滤器,但我不知道该怎么做?
    • 抛出异常时调用过滤器是废话。必须声明过滤器以过滤 servlet。一旦是,它将在 servlet 之前的过滤器链中被调用,如果 servlet 抛出,异常将被过滤器的 catch 块捕获。
    猜你喜欢
    • 2015-12-12
    • 2021-05-19
    • 2013-09-07
    • 2015-07-07
    • 2021-11-12
    • 2017-06-29
    • 2016-04-08
    相关资源
    最近更新 更多