1. Create a filter to monitor the request and response.
public class ErrorHandlerFilter implements Filter {
public void init(FilterConfig arg0) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
ErrorAwareResponseWrapper wrapper = new ErrorAwareResponseWrapper((HttpServletResponse) servletResponse);
filterChain.doFilter(servletRequest, wrapper);
}
public void destroy() {
}
2. A ResponseWrapper to check the error codes if applicable,
public class ErrorAwareResponseWrapper extends HttpServletResponseWrapper{
public ErrorAwareResponseWrapper(HttpServletResponse httpServletResponse) {
super(httpServletResponse);
}
@Override
public void sendError(int errorCode, String msg) throws IOException {
// TODO Auto-generated method stub
if (errorCode == HttpServletResponse.SC_NOT_FOUND){
//throw new PageNotFoundException();
this.sendRedirect("error_404.jsp");
}else if (errorCode == HttpServletResponse.SC_INTERNAL_SERVER_ERROR){
System.out.println("INTERNAL SERVER ERROR OCCURED WITH ERROR AWAREREQUEST WRAPPER"); //I never catch this error actually, struggling ....
// some actions to do here
.......
//
this.sendRedirect("error_500.jsp");
}
super.sendError(errorCode, msg);
}
3. Config Web.xml
<filter>
<filter-name>errorHandlerFilter</filter-name>
<filter-class>com.tantalus.filters.ErrorHandlerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>errorHandlerFilter</filter-name>
<url-pattern>/*</url-pattern>
<!-- These are needed by Tomcat 5 for forwards -->
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Comments
Post a Comment