简体   繁体   English

如何使用过滤器处理Servlet中引发的异常

[英]How to use a filter to handle exception that are throws in the servlet

My purpose is create a Filter to handle the exception that are throwed in the servlet. 我的目的是创建一个过滤器来处理servlet中引发的异常。

Suppose I have this filter: 假设我有这个过滤器:

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

    }
}

and in my servlet I throws the Exception 然后在我的servlet抛出Exception

How can I must do to handle in my filter the Exeception ? 我该如何处理过滤器中的Exeception?

Anyone can help me? 有人可以帮助我吗?

Just enclose the filter chain call in a try/catch block: 只需将过滤器链调用包含在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
    }
}

The only problem is that is the ServletResponse has already be committed (sent to the client) you will not be able to change the headers. 唯一的问题是,ServletResponse已经提交(发送给客户端),您将无法更改标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM