FireDrago
[JSP] 예외처리 본문
jsp 페이지에서도 자바처럼 예외 처리를 할 수 있다.
코드를 살펴보자
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
errorPage="addException.jsp"%>
<%
int num = Integer.parseInt(request.getParameter("num"));
int sum = 0;
for (int i=1; i<= num; i++) {
sum += i;
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>합계 구하기</h2>
<h1>1부터 <%=num %>까지의 합은 <%=sum %>입니다.</h1>
</body>
</html>
코드 맨 위쪽에 디렉티그 태그를 살펴보면
errorPage="addException.jsp
예외가 발생한 경우 호출할 jsp 파일을 지정할 수 있다. addException.jsp 를 살펴보자
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
================ toString() 내용 ==============<br>
<h1><%=exception.toString() %></h1>
================ getMessage( ) 내용 ===========<br>
<h1><%=exception.getMessage() %></h1>
============== printStackTrace() 내용 =========<br>
<h1><% exception.printStackTrace(); %></h1>
<h3>
숫자만 입력 가능합니다. 다시 시도하세요.
<a href='add.html'>다시 하기</a>
</h3>
</body>
</html>
예외처리시 호출되는 코드는 디렉티브 태그에서
isErrorPage="true"
자신이 예외를 담당하는 jsp라고 표시해준다.
이렇게 되면 코드 내부에서 exception 객체를 사용할 수 있게된다.
자바의 Exception 객체처럼 exception.toString( ) , exception.getMessage( ), exception.printStackTrace( )
메서드를 사용할 수 있다.
그럼 예외의 종류 마다 다르게 처리하고 싶을때는 어떻게 할까?
web.xml 에서 맵핑을 해주면 된다.
<error-page>
<error-code>404</error-code>
<location>/err/error_404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/err/error_505.jsp</location>
</error-page>
web.xml 에서 error-code를 지정하고, 에러코드에 따라 적절한 jsp 파일을 맵핑하는 것으로 예외의 종류별
예외처리가 가능해진다.
'프로그래밍 > 템플릿 엔진(thymeleaf, jsp)' 카테고리의 다른 글
| [Thymeleaf] 타임리프 기본기능 정리 (0) | 2024.02.05 |
|---|---|
| [JSP] 문자열 처리 함수 사용하기 (0) | 2023.07.17 |
| [JSP] Cookie (0) | 2023.06.20 |
| [JSP] Filter로 로그기록 만들기 (0) | 2023.06.19 |
| [JSP] web.xml 파일을 이용한 예외처리 (0) | 2023.06.19 |
