Web/JSP
예외페이지
surhommejk
2017. 12. 7. 15:01
예외처리를 하는 방법은 page 지시자를 사용하는 방법과 web.xml을 사용하는 방법이 있다
1) page 지시자 활용한 예외처리
error.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page errorPage="errorprint.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
int a = 40 / 0;
%>
</body>
</html>
errorprint.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page isErrorPage="true"%>
<% response.setStatus(200);%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
에러발생
<br />
<%=exception.getMessage()%>
<%
// = 에서는 ;를 생략한다
%>
</body>
</html>
2) web.xml 지시자 활용한 예외처리
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>javabeanTest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>500</error-code>
<location>/errorTest500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/errorTest404.jsp</location>
</error-page>
</web-app>
※ page 지시자를 활용하든 web.xml을 활용하든 에러처리 페이지에서 <% response.setStatus(200); %>을 해주는 것이 중요하다.이유는 브라우저가 에러처리 페이지 역시 에러 페이지로 인식 할 수도 있기 때문이다. 따라서 200(정상)으로 setStatus해주어서 정상으로 인식하게 만들어야 밑에서 getException.Massage()가 나오든 그냥 html이 나오든 하는 것이다.