JSP(11. 예외처리)

min seung moon·2021년 4월 15일
0

JSP

목록 보기
11/13

1. 예외 처리의 개요

01. 예외 처리

  • 프로그램이 처리되는 동안 특정한 문제가 발생했을 때 처리를 중단하고 다른 처리를 하는 것으로 오류 처리라고도 함
  • 웹 사이트를 이용하다가 주소를 잘못 입력하면 오류 페이지를 보게 됨
    • 웹 서버가 제공하는 오류페이지로 해당 페이지에 발생한 오류, 디렉터리 구조, 톰캣 버전 등의 정보가 나타나 있기 때문에 웹 보안이 취약하여 쉽게 해킹 당할 수 있음
  • 웹 애플리케이션 실행 도중에 발생할 수 있는 오류에 대비한 예외 처리 코드를 작성하여 비정상적인 종료를 막을 수 있음

02. 예외 처리 방법의 종류

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

01. errorPage 속성으로 오류 페이지 호출하기

  • errorPage 속성
    • 오류 페이지를 호출하는 page 디렉티브 태그의 속성
  • JSP 페이지가 실행되는 도중에 오류가 발생하면 웹 서버의 기본 오류 페이지를 대신하여 errorPage 속성에 설정한 페이지가 오류 페이지로 호출

예제 1.

  • page 디렉티브 태그에 errorPage 속성을 이용하여 오류 페이지 호출하기

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page errorPage="errorPage_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	name 파라미터 : <%=request.getParameter("name").toUpperCase() %>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	오류가 발생했습니다.
</body>
</html>

02. isErrorPage 속성으로 오류 페이지 만들기

  • isErrorPage 속성
    • 현재 JSP 페이지를 오류 페이지로 호출하는 page 디렉티브 태그의 속성
    • 이때 오류 페이지에서 exception 내장 객체를 사용할 수 있음

예제 2.

  • page 디렉티브 태그에 isErrorPage 속성을 이용하여 오류 페이지 만들기

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page errorPage="isErrorPage_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	name 파라미터 : <%=request.getParameter("name").toUpperCase() %>	
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<p>오류가 발생하였습니다.</p>
	<p>
		예외 유형 :
		<%=exception.getClass().getName()%></p>
	<p>
		오류 메시지 :
		<%=exception.getMessage()%></p>
	<p>
		toString :
		<%=exception.toString()%></p>
	<p>
		printStackTrace :
		<%=exception.printStackTrace()%></p>
</body>
</html>

예제 3.

  • page 디렉티브 태그에 errorPage와 isErrorPage 속성을 이용하여 예외 처리하기


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<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>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page errorPage="exception_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String num1 = request.getParameter("num1");
		String num2 = request.getParameter("num2");
		int a = Integer.parseInt(num1);
		int b = Integer.parseInt(num2);
		int c= a/b;
		out.print(num1 + "/" + num2 + " = " + c);
	%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<p>오류가 발생하였습니다</p>
	<p> 예외 : <%=exception %></p>
	<p> toString() : <%=exception.toString() %></p>
	<p> getClass().getName() : <%=exception.getClass().getName() %></p>
	<p> getMessage() : <%=exception.getMessage() %>
	
	
</body>
</html>

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

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

  • web.xml 파일을 통해 오류 상태와 오류페이지를 보여주는 방법
  • <error-page>...요소 내에 처리할 오류 코드나 오류 유형 및 오류 페이지를 호출
  • web.xml 파일은 웹 애플리케이션의 /WEB-INF/폴더에 있어야 함

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

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

03. web.xml 파일에 오류 코드와 오류 페이지를 설정하는 형식



예제 04.

  • web.xml 파일에 오류 코드로 오류 페이지 호출하기



<?xml version="1.0" encoding="UTF-8"?>
<web-app>
	<security-role>
		<role-name>guest</role-name>
	</security-role>
	<security-constraint>
		<web-resource-collection>
			<web-resource-name>JSPBook</web-resource-name>
			<url-pattern>/Book/addBook.jsp</url-pattern>
			<http-method>GET</http-method>
		</web-resource-collection>
		<auth-constraint>
			<description></description>
			<role-name>guest</role-name>
		</auth-constraint>
	</security-constraint>
	<login-config>
		<auth-method>FORM</auth-method>
		<form-login-config>
			<form-login-page>/Book/login.jsp</form-login-page>
			<form-error-page>/Book/login_failed.jsp</form-error-page>
		</form-login-config>
	</login-config>
	
	<error-page>
		<error-code>500</error-code>
		<location>/ch11/errorCode_error.jsp</location>
	</error-page>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="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>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String num1 = request.getParameter("num1");
		String num2 = request.getParameter("num2");
		int a = Integer.parseInt(num1);
		int b = Integer.parseInt(num2);
		int c = a / b;
		out.print(num1 + "/" + num2 + " = " + c);
	%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	errorCode 505 오류가 발생하였습니다
</body>
</html>

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

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

05. web.xml 파일에 예외 유형과 오류 페이지를 설정하는 형식



예제 5.

  • web.xml 파일에 예외 유형으로 오류 페이지 호출하기



<?xml version="1.0" encoding="UTF-8"?>
<web-app>
	<security-role>
		<role-name>guest</role-name>
	</security-role>
	<security-constraint>
		<web-resource-collection>
			<web-resource-name>JSPBook</web-resource-name>
			<url-pattern>/Book/addBook.jsp</url-pattern>
			<http-method>GET</http-method>
		</web-resource-collection>
		<auth-constraint>
			<description></description>
			<role-name>guest</role-name>
		</auth-constraint>
	</security-constraint>
	<login-config>
		<auth-method>FORM</auth-method>
		<form-login-config>
			<form-login-page>/Book/login.jsp</form-login-page>
			<form-error-page>/Book/login_failed.jsp</form-error-page>
		</form-login-config>
	</login-config>
	
	<error-page>
		<exception-type>java.lang.Exception</exception-type>
		<location>/ch11/exceptionType_error.jsp</location>
	</error-page>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="exceptionType_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>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String num1 = request.getParameter("num1");
		String num2 = request.getParameter("num2");
		int a = Integer.parseInt(num1);
		int b = Integer.parseInt(num2);
		int c = a / b;
		out.print(num1 + "/" + num2 + " = " + c);
	%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	exception type 오류가 발생하였습니다
</body>
</html>

4. try-catch-finally를 이용한 예외 처리

01. try-catch-finally

  • 자바의 예외 처리 구문으로 스크립틀릿 태그에 작성
  • try 구문에는 예외가 발생할 수 있는 코드를 작성하고, catch 구문에는 오류가 발생할 수 있는 예외 사항을 예측하여 처리하는 코드를 작성
  • finally 구문에는 try 구문이 실행된 실행할 코드를 작성하는데 이는 생략 가능

예제 06.

  • try-catch-finally를 이용하여 예외처리하기


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<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>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<p>잘못된 데이터가 입력되었습니다</p>
	<P><%=" 숫자1 : "+request.getParameter("num1") %></P>
	<P><%=" 숫자2 : "+request.getParameter("num2") %></P>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		try {
			String num1 = request.getParameter("num1");
			String num2 = request.getParameter("num2");
			int a = Integer.parseInt(num1);
			int b = Integer.parseInt(num2);
			int c = a / b;
		} catch (NumberFormatException e) {
			RequestDispatcher dispatcher = request.getRequestDispatcher("tryCatch_error.jsp");
			dispatcher.forward(request, response);
		}
		
	%>
</body>
</html>

5. 웹 쇼핑몰 예외 처리 페이지 만들기


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>상품 아이디 오류</title>
<style>
	.banner .container {
		height : 100%;
		display: flex;
		align-items : center;
	}
	.banner .container .banner_error {
		background-color: #fc8686;
		color : #d12c2c;
		height: 7vw;
		width : 100%;
		font-size : 5vw;
		overflow: hidden;
		line-height: 1.5;
	}
	p {
		margin : 30px 0;
	}
</style>
</head>
<body>
	<jsp:include page="header.jsp"/>
	
	<div class="main">
		<div class="banner">
			<div class="container">
				<h2 class="banner_error">해당 상품이 존재하지 않습니다.</h2>
			</div>
		</div>

		<div class="content">
			<div class="container">
				<p><%=request.getRequestURI() %><%=request.getQueryString() %></p>
				<p><a href="products.jsp" class="btn">상품 목록&raquo;</a>
			</div>
		</div>
	</div>
	
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="dto.Product"%>
<%@ page import="dao.ProductRepository"%>
<%@ page errorPage="exceptionNoProductId.jsp" %>
<jsp:useBean id="productDAO" class="dao.ProductRepository"
	scope="session" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>상품 상세 정보</title>
<style>
.content .row {
	padding: 30px 0;
	display : flex;
}
.content .row div {
	padding : 10px;
}

.content h3, .content p, .content h4 {
	margin: 25px 0;
}

.content h3 {
	margin-bottom: 5px;
}

.content .description {
	margin-top: 5px;
}

.content .badge {
	background-color: #f00;
	color: #fff;
	border-radius: 5px;
}
</style>
</head>
<body>
	<jsp:include page="header.jsp" />
	<div class="main">
		<div class="banner">
			<div class="container">
				<h1>상품 정보</h1>
			</div>
		</div>

		<%
			String id = request.getParameter("id");
			ProductRepository dao = ProductRepository.getInstance();
			Product product = dao.getProductById(id);
		%>
		<div class="content">
			<div class="container">
				<div class="row">
					<div>
						<img alt="상품 사진" style="width:100%"
							src="c:/upload/<%=product.getFilename()%>">
					</div>
					<div>
						<h3><%=product.getPname()%></h3>
						<p class="description"><%=product.getDescription()%></p>
						<p>
							<b>상품 코드 : </b><span class="badge"><%=product.getProductId()%></span>
						<p>
							<b>제조사</b> :
							<%=product.getManufacturer()%></p>
						<p>
							<b>분류</b> :
							<%=product.getCategory()%></p>
						<p>
							<b>재고 수</b> :
							<%=product.getUnitInStock()%>
						</p>
						<h4><%=product.getUnitPrice()%>원
						</h4>
						<p>
							<a href="#" class="btn btn-secondary">상품 주문 &raquo;</a> <a
								href="./products.jsp" class="btn">상품 목록 &raquo;</a>
						</p>
					</div>
				</div>
				<hr>
			</div>
		</div>
	</div>
	<jsp:include page="footer.jsp" />
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
	<security-role>
		<description></description>
		<role-name>admin</role-name>
	</security-role>
	<security-constraint>
		<display-name>WebMarket Security</display-name>
		<web-resource-collection>
			<web-resource-name>WebMarket</web-resource-name>
			<description></description>
			<url-pattern>/addProduct.jsp</url-pattern>
		</web-resource-collection>
		<auth-constraint>
			<description></description>
			<role-name>admin</role-name>
		</auth-constraint>
	</security-constraint>
	<login-config>
		<auth-method>FORM</auth-method>
		<form-login-config>
			<form-login-page>/login.jsp</form-login-page>
			<form-error-page>/login_failed.jsp</form-error-page>
		</form-login-config>
	</login-config>
	<error-page>
		<error-code>404</error-code>
		<location>/exceptionNoPage.jsp</location>
	</error-page>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>페이지 오류</title>
<style>
	.banner .container {
		height : 100%;
		display: flex;
		align-items : center;
	}
	.banner .container .banner_error {
		background-color: #fc8686;
		color : #d12c2c;
		height: 7vw;
		width : 100%;
		font-size : 5vw;
		overflow: hidden;
		line-height: 1.5;
	}
	p {
		margin : 30px 0;
	}
</style>
</head>
<body>
	<jsp:include page="header.jsp" />
	
	<div class="main">
		<div class="banner">
			<div class="container">
				<h2 class="banner_error">요청하신 페이지를 찾을 수 없습니다.</h2>
			</div>
		</div>

		<div class="content">
			<div class="container">
				<p><%=request.getRequestURI() %></p>
				<p><a href="products.jsp" class="btn">상품 목록&raquo;</a>
			</div>
		</div>
	</div>
</body>
</html>
profile
아직까지는 코린이!

0개의 댓글