본문 바로가기

청년취업아카데미/DayLog

[ JSP ] Day 10 - ② Error 처리하는 방법

# Error 처리

JSP 에러 발생시  처리하는 방법에는 두가지, 처리하는 장소에는 세 가지가 있다.

  • 처리하는 방법
    • ErrorPage 작성하기, out.println()으로 웹 전송
      • Servlet에서 에러처리
      • JSP페이지에서 처리
      • Javascript에서 처리

 

1. Error Page 작성하기

JSP 페이지로 작성

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" isErrorPage="true"%>

<%
	response.setStatus(200);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div align=center>
		<h1>공지</h1>
		<p>
			더 나은 페이지를 위해 준비중입니다. <br>
			메세지: <%=exception.getMessage()%> <br>
			클래스: <%=exception.getClass() %>
		</p>
	</div>
</body>
</html>

에러페이지 작성 순서

  1. Page 지시어에 isErrorPage = "true" 추가
  2. 스크립트릿에 response.setStatus() 메소드를 이용하여 상태코드 지정
  3. 에러페이지 화면 작성

 

2. Servlet에서 처리하기

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Cal2")
public class Cal2 extends HttpServlet {
	public static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException {
		System.out.println("Cal2 Start!");
		response.setContentType("text/html;charset-utf-8");
		PrintWriter out = response.getWriter();
		out.println("<html><body><h2>연산결과</h2></body></html>");
		try {
			int num1 = Integer.parseInt(request.getParameter("num1"));
			int num2 = Integer.parseInt(request.getParameter("num2"));
			out.printf("%d + %d = %d", num1,num2,(num1+num2));
			out.printf("%d - %d = %d", num1,num2,(num1-num2));
			out.printf("%d * %d = %d", num1,num2,(num1*num2));
			out.printf("%d / %d = %d", num1,num2,(num1/num2));
		}catch (Exception e) {
			System.out.println("Cal2 Exception --> "+e.getMessage());
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);
		}
		out.println("</body></html>");
		out.close();
	}

Servlet 클래스의 try-catch구분에서 error.jsp 페이지로 이동. Servlet 클래스를 인식해주기 위해서 @WebServlet("/ClassName") 해줘야함. 아래의 링크에서 서블릿 클래스 개념과 작성을 살펴볼 수 있다.

2019/07/24 - [Employment Academy] - [ JSP ] Day 10 - ④ 서블릿(Servlet)

 

[ JSP ] Day 10 - ④ 서블릿(Servlet)

...더보기 # Read Before Servlet은 톰캣 위에서 동작하는 Java 프로그램입니다. Java언어를 기반으로 동적인 contents를 생성하는 기술입니다. Servlet은 Java를 잘 모르면 상당히 어려운 부분으로, 예전에는 JSP..

dadmi97.tistory.com

 

3. JSP 페이지에서 스크립트릿 안에서 예외 부분에서 처리

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		try {
			int num1 = Integer.parseInt(request.getParameter("num1"));
			int num2 = Integer.parseInt(request.getParameter("num2"));
			out.println(num1 + " + " + num2 + " = " + (num1 + num2) + "<p>");
			out.println(num1 + " - " + num2 + " = " + (num1 - num2) + "<p>");
			out.println(num1 + " * " + num2 + " = " + (num1 * num2) + "<p>");
			out.println(num1 + " / " + num2 + " = " + (num1 / num2) + "<p>");
		} catch (ArithmeticException e) {
			out.println("헐! 0으로 나누다니;;");
		} catch (NumberFormatException e) {
			out.println("그게 숫자니?");
		} catch (Exception e) {
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);
		}
	%>
</body>
</html>

error 페이지 이동하는 것은 (1)catch문에서 에러 페이지로 이동 혹은 페이지 지시어에서 (2)errorPage="errorPage,jsp" 삽입

 

4. Javascript에서 처리

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<% try {
			int num1 = Integer.parseInt(request.getParameter("num1"));
			int num2 = Integer.parseInt(request.getParameter("num2"));
			out.println(num1 + " + " + num2 + " = " + (num1 + num2) + "<p>");
			out.println(num1 + " - " + num2 + " = " + (num1 - num2) + "<p>");
			out.println(num1 + " * " + num2 + " = " + (num1 * num2) + "<p>");
			out.println(num1 + " / " + num2 + " = " + (num1 / num2) + "<p>");
		} catch (ArithmeticException e) { %>
        
	<script type="text/javascript">
		alert("0으로 못나눠"); history.go(-1);'
	</script>
	<% } catch (NumberFormatException e) { %>
	<script type="text/javascript">
		alert("그게 숫자니"); history.go(-1);'
	</script>
	<% } catch (Exception e) { %>
	<script type="text/javascript">
		alert("하여튼 에러야"); location.href="num2.html";
	</script>
	<% } %>
</body>
</html>

alert 함수와 뒤로가기: history.go(-1)

페이지 이동: location.href