.jsp 연습하기 - 예외처리

오늘·2021년 5월 12일
0

웹 페이지 연습

목록 보기
12/35

예외처리

  • 프로그램이 처리되는 동안 특정한 문제가 발생했을 때, 처리를 중단하고 다른 처리를 하는 것으로 '오류처리'라고 하기도 함
  • 보통 웹 사이트를 이용하다가 주소를 잘못 입력하면 오류 페이지를 보게된다.
    -> 또한 웹 서버가 제공하는 오류 페이지는 해당 페이지에 발생한 오류, 디렉터리구조 등의 정보가 나타나있기 때문에 보안에 취약하여 쉽게 해킹당할 우려도 있다.

그래서 예외처리를 한다.

  • 웹 애플리 케이션 실행 도중에 발생할 수 있는 오류에 대비한 예외처리 코드를 작성해 비정상적인 종료를 막을 수 있는 것이다.

  • 예외 처리 방법 중 우선순위는

  1. try-catch-finally
  2. page 디렉티브 errorPage, isErrorPage
  3. web.xml
예외 처리 방법의 종류
예외 처리 방법 설명
page디렉티브 태그를 이용한 예외 처리 errorPage 와 isErrorPage 속성을 이용한다.
web.xml 파일을 이용한 예외 처리 error-code 또는 exception-type 요소를 이용한다.
try-catch-finally를 이용한 예외처리 자바 언어의 예외 처리 구문을 이용한다.

errorPage 속성을 이용 01

  1. error_page.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!-- 현재 파일을 수행하다가 에러가 나면 아래 jsp 파일로 이동해라 -->
<%@ page errorPage="1_errorPage_error.jsp" %>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<p> Exception-page 디렉티브 태그에 errorPage 속성을 이용해 오류 페이지 호출하기 </p>
	name 파라미터 : <%= request.getParameter("name").toUpperCase() %>
</body>
</html>
  1. 에러 받는 1_errorPage_error.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<p> 오류 발생 시 넘어오는 페이지 <br>
	errorPage속성을 이용해 호출했습니다.</p>
	<!-- exception 내장객체를 사용하려면, 현재 페이지가 에러페이지 임을 명시해야한다 -->
	<p> 예외 유형은 <%= exception.toString() %>
	<P> 예외가 발생한 클래스 이름은 <%= exception.getClass().getName() %>
	<p> 오류 메시지는 <%= exception.getMessage() %>
</body>
</html>

내부에서 실행시키면 나오지 않고, 크롬에서 실행시 아래와 같이 결과가 원하는 대로 나온다.


errorPage 속성을 이용 02

  1. 숫자를 입력받을 파일 생성
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<p> Exception-Page 태그에 errorPage 속성을 이용, 오류 페이지 호출하기 </p>
	<form action="2_exception_process.jsp" method="post">
		<p> 숫자 1 : <input type="text" name="num1">
		<p> 숫자 2 : <input type="text" name="num2">
		<p> <input type="submit" value="send">
	</form>
</body>
</html>
  1. 입력값을 받는 process.jsp 파일 생성
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page errorPage="2_errorPage_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
	<%
		String num1 = request.getParameter("num1");
		String num2 = request.getParameter("num2");
		
		int result = Integer.parseInt(num1) / Integer.parseInt(num2);
		out.print(num1 + " / " + num2 + " = " + result);
	%>
</body>
</html>
  1. 근데 만약에 사용자가 숫자가 아닌 문자나 특수기호 같은걸 입력했어. 그런 예외처리를 받아줄 error_page생성
  • 2번 값을 받아주는 파일에서 혹시 오류가 발생하면 아래 파일로 이동해서 받아라.. 하는 <%@ page errorPage="2_errorPage_error.jsp" %> 이런 코드를 작성해 주었기 때문에 해당 파일 명으로 작성해주면된다.
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<p> 오류가 발생했습니다. 숫자를 입력했는지 확인해주세요</p>
	<!-- exception 내장객체를 사용하려면, 현재 페이지가 에러페이지 임을 명시해야한다 -->
	<p> 예외 유형 : <%= exception.toString() %>
	<p> 오류 메시지 : <%= exception.getMessage() %>
</body>
</html>
  1. 첫번째 실행화면

  2. 숫자 입력시 다음 페이지로 잘 넘어가는 모습

  3. 숫자가 아닌 다른 것을 입력했을 시

오류 코드로 오류 페이지 호출하기

  • 웹 서버가 제공하는 기본 오류 페이지에 나타나는 404, 500과 같이 사용자의 요청이 올바르지 않을 때 출력되는 코드로 응답 상태 코드 라고도 한다.
  • jsp 페이지에서 발생하는 오류가 web.xml 파일에 설정된 오류 코드와 일치하는 경우 오류 코드와 오류 페이지를 보여준다.
-> web.xml 파일에 오류 코드와 오류 페이지를 설정하는 형식

<error-page>
	<error-code> 오류 코드 </error-code>
    	<location> 오류 페이지의 URI </location>
</error-page>

주요 오류 코드 종류

200 요청이 정상적으로 처리 됩니다
307 임시로 페이지가 리다이렉트 됩니다.
400 클라이언트의 요청이 잘못된 구문으로 구성됩니다.
401 지정된 URL을 처리하기 위한 자원이 존재하지 않습니다 (페이지가 없습니다)
405 요청된 메소드가 허용되지 않습니다.
500 서버내부의 에러입니다. (JSP에서 예외가 발생하는 경우)
자바코드 에러(비즈니스 로직 프로그램 오류)
503 서버가 일시적으로 서비스를 제공할 수 없습니다.
(서버 과부하나 보수 중인 경우)

사용해보기

  1. web.xml에 코드 추가해주기
    500번 오류코드가 발생시 아래 페이지로 이동하게끔 하는 코드이다.
	<error-page>
		<error-code>500</error-code>
		<location>/Ch11/3_errorCode_error.jsp</location>
	</error-page>
</web-app>

1-1. 여러개를 지정하고 싶다면 이런식으로 <error-page> </error-page> 로 감싸서 오류코드/호출할 파일 을 하나하나 작성해주면 된다.

	<error-page>
		<error-code>500</error-code>
		<location>/Ch11/3_errorCode_error.jsp</location>
	</error-page>

	<error-page>
		<error-code>404</error-code>
		<location>/Ch11/3_errorCode_error404.jsp</location>
	</error-page>
</web-app>
  1. 사용자에게 숫자 값을 받는 input 파일 만들기
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<p> web.xml 파일에 오류코드로 오류 페이지 호출하기 </p>
	<form action="3_errorCode_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>
  1. input에서 보낸 값을 받는 process.jsp 파일 만들기
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<%
		String num1 = request.getParameter("num1");
		String num2 = request.getParameter("num2");
		
		int result = Integer.parseInt(num1) / Integer.parseInt(num2);
		out.print(num1 + "/" + num2 + "=" + result);
	%>
</body>
</html>
  1. 근데 사용자가 숫자가 아닌 값을 입력할 수 있으니까.
    위 xml 파일에서 500 에러를 받는 3_errorCode_error.jsp 파일 생성
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<p> error code 500 번에 호출된 사용자 정의 페이지 </p>
</body>
</html>
  1. input 파일을 실행시키면 아래와 같은 첫 화면이 실행된다.


  2. 숫자 입력시 에러없이 처리되지만


  3. 숫자 아닌 값을 입력시
  4. 이 페이지가 호출된다

예외 유형으로 오류 페이지 호출하기

예외 유형에 따른 오류 페이지 호출 방법은 JSP 페이지가 발생시키는 오류가 web.xml 파일에 설정된 예외 유형과 일치하는 경우 예외 유형과 오류 페이지를 보여준다.

모양 ↓

<error-page>
	<exception-type> 예외 유형 </exception-type>
    	<location> 오류 페이지의 URI </location>
</error-page>

작성해보기

web.xml 파일 하단부분에 작성.
위는 예외 유형으로 설정한 것이고, 아래는 에러코드로 설정한 모습이다.

	<error-page>
		<exeception-type>java.lang.Exception</exeception-type>
		<location>/Ch11/3_errorCode_error.jsp</location>
	</error-page>
	<error-page>
		<error-code>404</error-code>
		<location>/Ch11/3_errorCode_error404.jsp</location>
	</error-page>

실행은 똑같다. Exception이 발생시 연결해준 jsp 페이지로 넘어간다.


try-catch-finally

  • 자바의 예외 처리 구문으로 <% %> 태그에 작성한다.
  • 사용하는 방법 역시 동일하다. try 구문에는 예외가 발생할 수 있는 코드를 작성하고, catch 구문에는 오류가 발생할수 있는 예외 사항을 예측하여 오류를 처리하는 코드를 작성, finally 구문에는 try 구문이 실행된 후 실행할 코드를 작성하는데 이는 생략이 가능하다.

작성해보기

  1. 사용자가 값을 입력하는 jsp
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html >
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<p> try-catch로 예외 처리하기 </p>
	<form action="4_tryCatch_process.jsp" method="post">
		<p> 숫자 1 : <input type="text" name="num1">
		<p> 숫자 2 : <input type="text" name="num2">
		<input type="submit" value="send">
	</form>
</body>
</html>
  1. 입력된 값을 받는 4_tryCatch_process.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<p> try-catch로 예외 받기 </p>
	<%
		try {
			String num1 = request.getParameter("num1");
			String num2 = request.getParameter("num2");
			
			int result = Integer.parseInt(num1) / Integer.parseInt(num2);
			out.print(result);
		} catch(NumberFormatException e){
			// 오류 처리하는 jsp로 넘어갈 때 자료를 가지고 넘어간다.
			RequestDispatcher dispatcher = request.getRequestDispatcher("4_tryCatch_error.jsp");
			dispatcher.forward(request, response);
					
			// 넘어갈 때 값을 버리고 넘어간다
			//response.sendRedirect("4_errorCode_error.jsp");
		}
	%>
</body>
</html>
  1. (2)에서 오류코드 발생시 넘어가는 try-Catch_error.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<p> 잘못된 데이터가 입력되었습니다 </p>
	<p> <%= "숫자 1 : " + request.getParameter("num1") %> </p>
	<p> <%= "숫자 2 : " + request.getParameter("num2") %> </p>
</body>
</html>

숫자 입력시 처리 결과
숫자 아닌값 입력시 처리결과
만약 2번 process jsp에서 값을 버리고 넘어가게끔 작성한다면
숫자 1 : null
숫자 2 : null
로 출력된다.


0개의 댓글

관련 채용 정보