JSP

[JSP] 예외 페이지

반응형

[JSP] 예외 페이지



예외 페이지의 필요성

JAVA에서 예외처리 (try-catch)를 사용하듯이, JSP나 Servlet에서도 예외가 발생할 수 있다.

예외적 상황이 발생했을 경우, 톰캣에서 제공되는 기본적인 예외 페이지가 보여지면 사용자 입장에서 불쾌감이나 거부감이 들 수 있다. 따라서 약간 딱딱한 에러 페이지보다 친근한 느낌이 느껴지는 페이지로 유도할 수 있는 장점이 있다.




예외 페이지 처리는 page 지시자를 이용한다.


<%@ page errorPage="errorPage.jsp" %>



에러가 발생하면, errorPage.jsp로 넘어간다는 뜻이다.

errorPage.jsp에서는 page지시자와 Status 값을 지정해준다.

1
2
3
4
<%@ page isErrorPage="true" %>
<% response.setStatus(200); %>
 
<%= exception.getMessage() %>
cs


isErrorPage의 기본값은 false이기 때문에 true로 설정해준다.

에러 내용은 exception의 메시지를 통해 불러올 수 있다.

Status를 200으로 설정한 이유는?

현재 error가 발생한 페이지는 info.jsp다. errorPage.jsp는 에러가 발생한 페이지가 아니라 에러를 알려주는 곳이기 때문에, 에러를 뜻하는 Status 500이 설정되지 않도록 200으로 지정해주는 것이다.






info.jsp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page errorPage="errorPage.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 i = 40/0;
    %>
    
</body>
</html>
cs

integer를 0으로 나누는 에러를 만들어놓은 모습을 볼 수 있다.

에러가 발생하기 때문에, page 지시자로 설정한 errorPage.jsp로 넘어갈 것이다.




errorPage.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ 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>
cs





이 밖에도 web.xml 파일을 이용한 예외 처리도 가능하다.

1
2
3
4
5
6
7
8
<error-page>
    <error-code>404</error-code>
    <location>/error404.jsp</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/error500.jsp</location>
</error-page>
cs


error404.jsp와 error500.jsp만 만들어 놓으면, web.xml로 예외 처리를 지정해두는 방법 또한 존재한다.


반응형

'JSP' 카테고리의 다른 글

[JSP] 자바 빈(Bean)  (0) 2018.05.11
[JSP] 세션  (0) 2018.05.09
[JSP] 쿠키  (0) 2018.05.09
[JSP] 액션 태그  (0) 2018.05.09
[JSP] JSP 기본 정리  (0) 2018.05.09