日期:2014-05-20  浏览次数:20836 次

我想在filter中统一处理异常。不知道是不是这样写??
Java code
 

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ExceptionFilter implements Filter {

    protected FilterConfig filterConfig = null;

    private static final String PAGE_TO_FORWARD = "errorNew.jsp";

    // ---------------------- Public Methods
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = request.getSession();
        Exception e=null;
        long millsecds=0;
        
        millsecds=System.currentTimeMillis();
        
        try {
            chain.doFilter(req, res);
        }catch(NullPointerException ee){            
            e=ee;
            session.setAttribute("msg", "空指针异常!异常编号是:"+millsecds);
        } catch (Exception ee) {
            e=ee;
            session.setAttribute("msg", "异常!异常编号是:"+millsecds);            
        }
        //把异常信息保存到
        saveExceptionToDataBase(e,millsecds);
        session.setAttribute("e", e);
        redirect(PAGE_TO_FORWARD, request, response);

    }

    public void init(FilterConfig filterConfig) {

    }

    public void destroy() {
    }

    // --------------------- Private Methods
    private void redirect(String page, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect(request.getContextPath() + "/" + page);
    }
    private void saveExceptionToDataBase(Exception e,long millsecds){
        //把异常保存到db中
    }
}



------解决方案--------------------
应该是没什么问题。你测试一下,看看是否能达到你想要的结果。
------解决方案--------------------
Filter可以统一处理异常么?他好像是在 servlet和jsp的前面执行的吧?

如果能在后面执行,哪应该可以。

如果不能再后面执行,哪应该不可以。
------解决方案--------------------
filter不是这么什么的前面执行,而是在filter中进行后面方法的调用,整个执行流程是包含在filter中的,所以可以进行异常处理的
------解决方案--------------------
理解错了

顺序应该是这样的,明白了。

Filter -> servlet throw exception and forword to error page.

Filter -> error page

这样可以。