romworld

JSP 21 - 예외 처리(Exception) 본문

WEB/JSP

JSP 21 - 예외 처리(Exception)

inderrom 2023. 1. 13. 10:34
  • 404  : Page Not Found
  • 500 : 개발자 오류 (문법, 구문 오류)

 

 

- 주요 오류 코드


1. 디렉티브 태그를 이용한 예외 처리

 -   errorPage(오류를 처리하는 jsp 페이지) 

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

 

 

- isErrorPage : 현재 본 jsp 페이지는 오류처리 페이지이다. 기본이 false

- exception 객체를 사용하기 위해서는 page디렉티브의 isErrorPage="true"

<%@ page isErrorPage="true" %>

 



 

<errorPage.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page errorPage="errorPage_error.jsp" %>
<!-- 1) page 디렉티브 태그를 이용한 예외 처리
	  errorPage(오류를 처리하는 jsp 페이지) / isErrorPage 속성을 이용	
 -->
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
<!--  예외 처리(Exception) 
	- 프로그램이 처리되는 동안 특정한 문제가 발생했을 때
	  처리를 중단하고 다른 처리를 하는 것
	  ex) 0으로 나눔, null.toString(), page not found,
	  	Nullpoint exception, array out of bounds
-->
	<!--  errorPage.jsp?name=apple => APPLE -->
	<!-- errorPage.jsp -->
	name 파라미터 : <%=request.getParameter("name").toUpperCase()%>
</body>
</html>

<errorPage.error.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isErrorPage="true" %>
<!-- isErrorPage : 현재 본 jsp 페이지는 오류처리 페이지이다. 기본이 false -->
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<p>오류가 발생했습니다</p>
	<!-- p. 361 -->
	<!-- exception : JSP에서 제공해주는 오류 처리용 기본 내장 객체 -->
	<p>예외 유형 : <%=exception.toString() %></p>
	<p>예외 유형 : <%=exception.getClass().getName() %></p>
	<p>오류 메시지 : <%=exception.getMessage() %></p>
	<p></p>
</body>
</html>

errorPage에서 실행시면


<exception.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<!-- 폼페이지 
		요청URI : exception_process.jsp?num=12&num2=6
		요청파라미터(HTTP파라미터, QueryString) : num12&num2=6
	-->
	<form action="exception_process.jsp" method="post">
	<!-- 폼데이터 -->
		<p>숫자1 : <input type="text" name="num1" /></p>
		<p>숫자2 : <input type="text" name="num2" /></p>
		<p><input type="submit" value="나누기" /></p>
	</form>
</body>
</html>

 

<exception_process.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page errorPage="exception_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<!-- 요청URI : exception_process.jsp?num=12&num2=6 
		request객체에 num=12&num2=6 들어있음
	-->
	<%
		String num1 = request.getParameter("num1");  //"12" 
		String num2 = request.getParameter("num2"); //"6"
		// 문자를 숫자로 형변환
		int a = Integer.parseInt(num1);  //12
		int b = Integer.parseInt(num2);  //6
		int c = a / b; // 12 /6 = 2
		out.print(num1 + "/" + num2 + "=" + c);
	%>
</body>
</html>

 

 

 

 

오류가 발생될 때 throws를 던지는 jsp

<excepton_error.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isErrorPage="true" %>
<!-- isErrorPage : 현재 본 jsp 페이지는 오류처리 페이지이다. 기본이 false -->
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<p>오류가 발생했습니다</p>
	<!-- exception : JSP에서 제공해주는 오류 처리용 기본 내장 객체 -->
	<!--  exception 객체를 사용하기 위해서는 page디렉티브의 isErrorPage="true" -->
	<p>예외 : <%=exception%></p>
	<p>예외 유형 : <%=exception.toString() %></p>
	<p>예외 유형 : <%=exception.getClass().getName() %></p>
	<p>오류 메시지 : <%=exception.getMessage() %></p>
	<p></p>
</body>
</html>

 


2. web.xml 파일을 이용한 예외 처리

 

<web.xml>

  <!--  오류가 나면 오류 타입(404,500)에 맞춰 오류 처리 jsp로 매핑 -->
  <!--  404 : page not found. URL에 해당되는 jsp가 없음 -->
  <error-page>
  	<error-code>404</error-code>
  	<location>/error/error404.jsp</location>
  </error-page>
  <!-- 500 : 프로그래밍 오류 -->
  <error-page>
  	<error-code>500</error-code>
  	<location>/error/error500.jsp</location>
  </error-page>

 

 

<error404.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>404오류</title>
</head>
<body>
	<img alt="404오류" src="/images/404_not_found.png"/>
</body>
</html>

 

<error500.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>500오류</title>
</head>
<body>
	<img alt="500 오류" src="/images/error-500.jpg"/>
</body>
</html>

 


주요 예외 유형

 

 	 <error-page>
  		<exception-type>java.lang.NullPointerException</exception-type>
  		<location>/error/errorNullPointer.jsp</location>
  	</error-page>

 


3. try -cath를 이용한 예외 처리

  • try 구문 : 예외가 발생할 수도 있는 코드를 작성
  • catch 구문 : 오류가 발생할 수도 있는 예외 사항을 예측하여
  • 오류를 처리하는 코드를 작성
  • finally : try 구문이 실행된 후 실행할 코드를 작성(생략 가능)

 

 

<tyrCatch.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<!-- 폼페이지 
		요청URI : tryCatch_process.jsp?num=12&num2=6
		요청파라미터(HTTP파라미터, QueryString) : num12&num2=6
	-->
	<form action="tryCatch_process.jsp" method="post">
	<!-- 폼데이터 -->
		<p>숫자1 : <input type="text" name="num1" /></p>
		<p>숫자2 : <input type="text" name="num2" /></p>
		<p><input type="submit" value="나누기" /></p>
	</form>
</body>
</html>

 

<tryCatch_process.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- <%@ page errorPage="exception_error.jsp" %> --%>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<!-- 3) try-catch-finally를 이용한 예외 처리  
		- 자바의 예외 처리 구문으로
		- try 구문 : 예외가 발생할 수도 있는 코드를 작성
		- catch 구문 : 오류가 발생할 수도 있는 예외 사항을 예측하여
				오류를 처리하는 코드를 작성
		- finally : try 구문이 실행된 후 실행할 코드를 작성(생략 가능)
	-->
		
	<!-- 요청URI : tryCatch_process.jsp?num=12&num2=6 
		request객체에 num=12&num2=6 들어있음
	-->
	<%
	try{	// 먼저 실행됨. 만약 예외 발생 시 실행을 중단하고, 예외와 일치하는 catch 블록의 내용을 실행
		String num1 = request.getParameter("num1");  //"12" 
		String num2 = request.getParameter("num2"); //"0"
//		String num3 = request.getParameter("num3").toString(); 
		// 문자를 숫자로 형변환
		int a = Integer.parseInt(num1);  //12
		int b = Integer.parseInt(num2);  //0
		int c = a / b; // 12 /0 = 오류발생
		out.print(num1 + "/" + num2 + "=" + c);
	}catch(ArithmeticException e){
		// 오류가 발생하면 tryCatch_error.jsp로 포워딩.
		/*
			1) forwarding : jsp 해석 -> 컴파일 -> html 리턴받음. 데이터를 전달할 수 있음.
			2) redirect :  URL을 재요청. 데이터를 전달하기 어려움.
		*/
		// request객체와  response객체를 전달함
		// tryCatch_error.jsp에서도 요청파라미터인 ?num1=12&num2=0을 사용할 수 있음
		RequestDispatcher dispatcher =
				request.getRequestDispatcher("tryCatch_error.jsp");
		dispatcher.forward(request, response);
	}
	%>
</body>
</html>

 

<tryCatch_error.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
<!--  tryCatch_process.jsp 
	dispatcher.forward(reqest,response);
	전달받은 requst객체를 사용할 수 있음
-->
	<p>잘못된 데이터가 입력되었습니다.</p>
	<p>숫자1 : <%=request.getParameter("num1")%> </p>
	<p>숫자2 : <%=request.getParameter("num2")%></p>
</body>
</html>

 


예외 처리 우선순위

  • 1. page 디렉티브
  • 2. web.xml
  • 3. try-catch

이 순서대로 예외 처리가 된다. try-cath문에서 작성을 해도 

page 디렉티브나 web.xml에서 매핑을 한다면 

우선순위대로 적용이 된다.

Comments