예제
T04_ErrorHandler
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status.code");
String servletName = (String) req.getAttribute("javax.servlet.error.servlet_name");
if(servletName == null) {
servletName = "알 수 없음";
}
String requestUri = (String) req.getAttribute("javax.servlet.error.request_uri");
if(requestUri == null) {
requestUri = "알 수 없는 URL";
}
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
String title = "예외(에러) 정보";
pw.println("<!DOCTYPE html>\n"
+ "<html>\n"
+ "<head><title>" + title + "</title></head>\n"
+ "<body>\n");
if(throwable == null&& statusCode == null) {
pw.println("<h2>에러 정보 없음</h2>");
pw.println("홈페이지로 돌아가기 : "
+ "<a href=\"http://localhost:9090/P16_ServletTest/index.html"
+ "\">홈페이지</a>");
}else if(statusCode != null) {
pw.println("Status code : " + statusCode);
}else {
pw.println("<h2>에러(예외) 정보</h2>");
pw.println("Servlet Name : " + servletName + "<br><br>");
pw.println("Exception Type : " + throwable.getClass().getName() + "<br><br>");
pw.println("요청 URL : " + requestUri + "<br><br>");
pw.println("예외 메시지 : " + throwable.getMessage());
}
pw.println("</body>");
pw.println("</html>");
}
web.xml
url패턴 매핑
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>kr.or.ddit.basic.T04_ErrorHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
에러코드 매핑
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
에러타입 매핑
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/ErrorHandler</location>
</error-page>