今天上课讲到一个web应用时,随口提起异常、错误集中处理显示,自然地想到了web.xml配置文件中的<error-page>项,进而在一个servlet中应用了一下。如下:
web.xml加入如下配置
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/error.jsp</location>
</error-page>
servlet中加入异常抛出代码
String title=request.getParameter("title");
if(title==null || title.trim().equals(""))
throw new ServletException("请输入数据");
启动运行,页面一片空白!?怎么回事,难道没有进入error.jsp?仔细查了查看到控制台报的异常中有一处是EncodingFilter的代码位置,难道和过滤器有关?!于是屏蔽了过滤器再启动服务运行,一切OK了!果真和过滤器有关,翻开servlet-2.4手册查到一段说明:
The error page mechanism described does not intervene when errors occur
when invoked using the RequestDispatcher or filter.doFilter method. In this
way, a filter or servlet using the RequestDispatcher has the opportunity to handle
errors generated.
回头再认真看了看抛出的异常位置,是在过滤器的doFilter()方法调用处,恍然大悟,doFilter()调用被try-catch了,过滤器自己catch(ServletException)进行了处理,所以不会再转到error.jsp页面。最后想了个解决方法:
try {
filterChain.doFilter(request, response);
}catch (ServletException sx) {
filterConfig.getServletContext().log(sx.getMessage());
request.setAttribute("errMsg",sx.getMessage());
RequestDispatcher rd=request.getRequestDispatcher("/error.jsp");
try {
rd.forward(request, response);
} catch (Exception ex) {
filterConfig.getServletContext().log(ex.getMessage());
}
} catch (IOException iox) {
filterConfig.getServletContext().log(iox.getMessage());
}
web.xml加入如下配置
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/error.jsp</location>
</error-page>
servlet中加入异常抛出代码
String title=request.getParameter("title");
if(title==null || title.trim().equals(""))
throw new ServletException("请输入数据");
启动运行,页面一片空白!?怎么回事,难道没有进入error.jsp?仔细查了查看到控制台报的异常中有一处是EncodingFilter的代码位置,难道和过滤器有关?!于是屏蔽了过滤器再启动服务运行,一切OK了!果真和过滤器有关,翻开servlet-2.4手册查到一段说明:
The error page mechanism described does not intervene when errors occur
when invoked using the RequestDispatcher or filter.doFilter method. In this
way, a filter or servlet using the RequestDispatcher has the opportunity to handle
errors generated.
回头再认真看了看抛出的异常位置,是在过滤器的doFilter()方法调用处,恍然大悟,doFilter()调用被try-catch了,过滤器自己catch(ServletException)进行了处理,所以不会再转到error.jsp页面。最后想了个解决方法:
try {
filterChain.doFilter(request, response);
}catch (ServletException sx) {
filterConfig.getServletContext().log(sx.getMessage());
request.setAttribute("errMsg",sx.getMessage());
RequestDispatcher rd=request.getRequestDispatcher("/error.jsp");
try {
rd.forward(request, response);
} catch (Exception ex) {
filterConfig.getServletContext().log(ex.getMessage());
}
} catch (IOException iox) {
filterConfig.getServletContext().log(iox.getMessage());
}