예외 처리
오류 처리
: 프로그램이 처리되는 동안 특정한 문제가 발생했을 때 처리를 중단하고 다른 처리를 하는 것
오류 페이지에 발생 오류, 디렉터리 구조, 톰캣 버전 등의 정보가 나타나 있기에 웹 보안에 취약함
ex)
- 예외 처리 방법의 종류
예외 처리 방법 | 설명 |
page 디렉티브 태그 이용 | errorPage, isErrorPage 속성 이용 |
web.xml 파일 이용 | <error-code>, <exception-type> 요소 이용 |
try/catch/finally를 이용 | 자바 언어의 예외 처리 구문 이용 |
page 디렉티브 태그 이용
- errorPage 속성으로 오류 페이지 호출
<%@ page errorPage = "오류 페이지 URL" %>
errorPage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page errorPage="errorPage_error.jsp" %>
<!-- JSP 페이지가 실행되는 도중 오류 발생 시 오류 페이지 호출.
page 디렉티브 태그. errorPage 속성 작성 -->
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
<!--
요청 URI : /ch11/errorPage.jsp?name=apple
요청 파라미터(HTTP 파라미터, QueryString) : name=apple
요청방식 : GET
-->
<p>name 파라미터 : <%=request.getParameter("name").toUpperCase()%> </p>
</body>
</html>
errorPage_error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
<h3>오류가 발생했습니다.</h3>
</body>
</html>
=> 미리 오류 발생 시 web.xml로 페이지 설정을 해 놨을 경우에도 errorPage가 우선 처리됨
- isErrorPage 속성 추가 이용
<%@ page isErrorPage = "true" %>
메소드 | 형식 | 설명 |
getMessage() | String | 오류 이벤트와 함께 들어오는 메시지 출력 |
toString() | String | toString()을 호출하여 간단한 오류 메시지 확인 |
printStackTrace() | String | 오류 메시지의 발생 근원지를 찾아 단계별로 오류 출력 |
errorPage_error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page isErrorPage="true" %>
<!-- isErrorPage 속성 : 현재 JSP 페이지를 오류 페이지로 호출하는
page 디렉티브 태그의 속성. 이때 오류 페이지에서 exception 내장 객체를
사용할 수 있음 -->
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
<h3>오류가 발생했습니다.</h3>
<!-- P.361 -->
<!-- exception : JSP에서 제공해주는 오류 처리용 기본 내장 객체 -->
<!-- <exception-type>java.lang.NullPointerException</exception-type> -->
<!-- 오류 이벤트의 toString()을 호출하여 간단한 오류 메시지 확인 -->
<p>예외 유형 : <%=exception.toString()%></p> <!-- isErrorPage을 사용해야 쓸 수 있음 -->
<!-- 오류 메시지의 발생 근원지를 찾아 단계별로 오류를 출력 -->
<%-- <p>단계별 오류 출력 : <%=exception.printStackTrace()%></p> --%>
<!-- 오류 발생 시 해당 예외 객체 타입을 가져와 출력 -->
<p>예외 유형 : <%=exception.getClass().getName()%></p>
<!-- getMessage() 오류 이벤트와 함께 들어오는 메시지를 출력 -->
<p>오류 메시지 : <%=exception.getMessage()%></p>
</body>
</html>
- => 로그인 시 오류 내용 확인할 수 있게 수정
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page isErrorPage="true" %>
<!-- isErrorPage 속성 : 현재 JSP 페이지를 오류 페이지로 호출하는
page 디렉티브 태그의 속성. 이때 오류 페이지에서 exception 내장 객체를
사용할 수 있음 -->
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
<h3>오류가 발생했습니다.</h3>
<%if(request.isUserInRole("manager")) {%>
<!-- P.361 -->
<!-- exception : JSP에서 제공해주는 오류 처리용 기본 내장 객체 -->
<!-- <exception-type>java.lang.NullPointerException</exception-type> -->
<!-- 오류 이벤트의 toString()을 호출하여 간단한 오류 메시지 확인 -->
<p>예외 유형 : <%=exception.toString()%></p> <!-- isErrorPage을 사용해야 쓸 수 있음 -->
<!-- 오류 메시지의 발생 근원지를 찾아 단계별로 오류를 출력 -->
<%-- <p>단계별 오류 출력 : <%=exception.printStackTrace()%></p> --%>
<!-- 오류 발생 시 해당 예외 객체 타입을 가져와 출력 -->
<p>예외 유형 : <%=exception.getClass().getName()%></p>
<!-- getMessage() 오류 이벤트와 함께 들어오는 메시지를 출력 -->
<p>오류 메시지 : <%=exception.getMessage()%></p>
<%}%>
</body>
</html>
web.xml 파일 이용
요소 | 설명 |
<error-code> | 오류 코드를 설정 |
<exception-type> | 자바 예외 유형의 정규화된 클래스 이름 설정 |
<location> | 오류 페이지의 URL 설정 |
web-app의 안, 가장 하단에 추가하기
web.xml
<!-- 오류가 나면 오류 타입에 맞춰 오류 처리 jsp로 매핑 -->
<!-- 404 : page not found. URL에 해당되는 jsp가 없음 -->
<!--
[주요 오류 코드 종류]
200 : 요청이 정상적으로 처리됨
307 : 임시로 페이지가 리다이렉트 됨
400 : 클라이언트의 요청이 잘못된 구문으로 구성됨
401 : 접근이 허용되지 않음
404 : 지정된 URL을 처리하기 위한 자원이 존재하지 않음
405 : 요청된 메소드가 허용되지 않음
500 : 서버 내부 오류(JSP에서 예외 발생)
503 : 서버 과부하나 보수 중인 경우. 서버가 일시적으로 서비시를 제공할 수 없음
-->
<error-page>
<!-- 오류 코드 설정
오류 코드 : 웹 서버가 제공하는 기본 오류 페이지에 나타나는 404, 500과 같이
사용자의 요청이 올바르지 않을 때 출력되는 코드. 응답 상태 코드.
JSP페이지에서 발생하는 오류가 web.xml 파일에 설정된 오류 코드와 일치하는
경우 오류 코드와 오류 페이지를 보여줌
-->
<error-code>404</error-code>
<location>/error/error404.jsp</location>
</error-page>
<error-page>
<!-- 프로그래밍 오류 ex ) 10/0과 같이 잘못된 코드 -->
<error-code>500</error-code>
<location>/error/error500.jsp</location>
</error-page>
error404.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>404오류</title>
</head>
<body>
<img src="/images/404.jpg" />
</body>
</html>
error500.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>500오류</title>
</head>
<body>
<img src="/images/500.jpg" />
</body>
</html>
- error-code 이용
errorCode.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
<!-- 폼페이지
요청URI : errorCode_process.jsp?num1=10&num2=5
요청파라미터 : num1=10&num2=5
요청방식 : post
-->
<form action="errorCode_process.jsp" method="post">
<p>숫자1 : <input type="number" name="num1" placeholder="숫자1" required></p>
<p>숫자2 : <input type="number" name="num2" placeholder="숫자2" required></p>
<p><input type="submit" value="나누기" /></p>
</form>
</body>
</html>
errorCode_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<!-- 폼페이지
요청URI : errorCode_process.jsp?num1=10&num2=5
요청파라미터 : num1=10&num2=5
요청방식 : post
-->
<%
String num1 = request.getParameter("num1"); //10
String num2 = request.getParameter("num2"); //5
// 문자 타입을 숫자 타입으로 형변환
int a = Integer.parseInt(num1);
int b = Integer.parseInt(num2);
/*page 디렉티브의 errorPage속성이 없으므로 web.xml의
error500.jsp에서 오류를 처리함
<error-page>
<error-code>500</error-code>
<location>/error/error500.jsp</location>
</error-page>
*/
int c = a / b; // by zero 오류 발생
out.print(num1 + " / " + num2 + " = " + c);
%>
</body>
</html>
- exception-type의 NullPointerException 이용
web.xml
하단에 추가
<error-page>
<!-- excetion 타입 -->
<exception-type>java.lang.NullPointerException</exception-type>
<!-- 오류페이지 설정 -->
<location>/error/errorNullPointer.jsp</location> <!-- jsp가 있어야 함!! -->
</error-page>
=> nullPointerException이 발생할 경우 위의 errorNullPointer.jsp로 이동됨
try/catch/finally를 이용
tryCatch.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
<!-- 폼페이지
요청URI : tryCatch_process.jsp
요청파라미터 : {num1=10&num2=5}
요청방식 : post
-->
<form action="tryCatch_process.jsp" method="post">
<p>숫자1 : <input type="number" name="num1" placeholder="숫자1" required></p>
<p>숫자2 : <input type="number" name="num2" placeholder="숫자2" required></p>
<p><input type="submit" value="나누기" /></p>
</form>
</body>
</html>
tryCatch_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<!-- 폼페이지
요청URI : tryCatch_process.jsp
요청파라미터 : {num1=10&num2=5}
요청방식 : post
-->
<%
try{
String num1 = request.getParameter("num1"); //10
String num2 = request.getParameter("num2"); //5
// 문자 타입을 숫자 타입으로 형변환
int a = Integer.parseInt(num1);
int b = Integer.parseInt(num2);
/*page 디렉티브의 errorPage속성이 없으므로 web.xml의
error500.jsp에서 오류를 처리함
<error-page>
<error-code>500</error-code>
<location>/error/error500.jsp</location>
</error-page>
*/
int c = a / b; // by zero 오류 발생
out.print(num1 + " / " + num2 + " = " + c);
} catch(ArithmeticException e) {
out.print("<img src='/images/error.jpg' />");
}
%>
</body>
</html>
=> try-catch > errorPage > web.xml 순으로 우선 순위가 있음
+forward와 Redirct 차이
tryCatch_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page errorPage="errorPage_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<!-- 폼페이지
요청URI : tryCatch_process.jsp
요청파라미터 : {num1=10&num2=5}
요청방식 : post
-->
<%
try{
String num1 = request.getParameter("num1"); //10
String num2 = request.getParameter("num2"); //5
// 문자 타입을 숫자 타입으로 형변환
int a = Integer.parseInt(num1);
int b = Integer.parseInt(num2);
/*page 디렉티브의 errorPage속성이 없으므로 web.xml의
error500.jsp에서 오류를 처리함
<error-page>
<error-code>500</error-code>
<location>/error/error500.jsp</location>
</error-page>
*/
int c = a / b; // by zero 오류 발생
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("/ch11/tryCatch_error.jsp");
dispatcher.forward(request, response); // forward로 인해 request 객체가 tryCatch_error로 따라감
}
%>
</body>
</html>
tryCatch_error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
<!--
요청URI : tryCatch_process.jsp
요청파라미터 : request객체 안에 {num=10&num2=5}
요청방식 : post
-->
<p>잘못된 데이터가 입력되었습니다.</p>
<p>숫자1 : <%=request.getParameter("num1")%></p>
<p>숫자2 : <%=request.getParameter("num2")%></p>
</body>
</html>
'스프링' 카테고리의 다른 글
[스프링] 19장 필터, 쇼핑몰 시스템7 (0) | 2024.04.17 |
---|---|
[스프링] 18장 쇼핑몰 시스템6 (1) | 2024.04.16 |
[스프링] 16.5장 과제 (0) | 2024.04.15 |
[스프링] 16장 시큐리티, 쇼핑몰 시스템5(시큐리티 작업) (0) | 2024.04.15 |
[스프링] 15장 쇼핑몰 시스템4 (0) | 2024.04.12 |