Servlet 中使用 RequestDispatcher 来集中处理异常

[b]Servlet 中使用 RequestDispatcher 来集中处理异常[/b]

利用Servlet 的 RequestDispatcher 方法,可以将不同的异常封装在请求中,发给一个 Servlet 来统一处理,可以有效的避免代码重复,提高管理效率。

举例如下:

测试环境:JDK1.6.0_21 Tomcat6.0.29

第一步:创建一个产生异常的Servlet(DemoServlet)

package cn.test;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try{
int a=100;
int b=0;
int c=a/b;

}catch(ArithmeticException ae){
request.setAttribute("servletException",ae);
request.setAttribute("servletExceptionUrl", request.getRequestURI());
RequestDispatcher rd = request.getRequestDispatcher("ExceptionHandlerServlet");
rd.forward(request, response);
}
}
}


第二步:建立一个处理异常的Servlet(ExceptionHandlerServlet)

package cn.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ExceptionHandlerServlet extends HttpServlet {

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=GB2312");
PrintWriter out = response.getWriter();

out.println("系统错误");
out.println("");
String uri = (String) request.getAttribute("servletExceptionUrl");
Object msg = request.getAttribute("servletException");
out.println("

错误位置:" + uri + "

");
out.println("

错误信息:[" + msg + "]

");
out.println("");
out.close();
}
}


web.xml的配置信息:

 

DemoServlet
DemoServlet
cn.test.DemoServlet


DemoServlet
/Demo



ExceptionHandlerServlet
ExceptionHandlerServlet
cn.test.ExceptionHandlerServlet


ExceptionHandlerServlet
/ExceptionHandlerServlet



网页显示如下信息:

[img]http://dl.iteye.com/upload/picture/pic/72864/aa604aa9-e858-341f-a639-7f7042282888.jpg[/img]

我们可以对这个Servlet进行统一的包装,使他成为一个中央错误页。还有一个好处就是报错是自定义的页面而不是Tomcat默认的页面,没有容器的相关信息。

你可能感兴趣的:(Java相关,Servlet,Java,Tomcat,配置管理,Web)