[쉽게 배우는 JSP 웹 프로그래밍] 11장 정리, 연습문제

JSP에서의 예외 처리 방법에 대해 다루고 있습니다. page 디렉티브 태그를 이용한 예외 처리, web.xml 파일을 이용한 예외 처리, 그리고 try-catch-finally를 이용한 예외 처리 방법에 대해 설명하고 있습니다. 각 방법에 대한 코드 예시와 설명이 포함되어 있습니다. 이를 통해 예외 처리의 개념과 이를 적용하는 방법을 이해할 수 있습니다.
Feb 28, 2024
[쉽게 배우는 JSP 웹 프로그래밍] 11장 정리, 연습문제

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

exception.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</title> </head> <body> <form action="exception_process.jsp" method="post"> <p> 숫자1: <input type="text" name="num1"> <p> 숫자2: <input type="text" name="num2"> <p> <input type="submit" value="나누기"> </form> </body> </html>

exception_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</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.println(num1 + " / " + num2 + " = " + c); %> </body> </html>

exception_error.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page isErrorPage="true" %> <html> <head> <title>Exception</title> </head> <body> <p>오류가 발생했습니다. <P> 예외 : <%=exception%> <p> toString() : <%=exception.toString() %> <p> getClass().getName() : <%=exception.getClass().getName() %> <p> getMessage() : <%=exception.getMessage() %> </body> </html>
 

핵심 키워드

  • page 디렉티브 태그에 errorPage와 isErrorPage 속성을 사용해서 오류 페이지를 호출할 수 있다.
    • errorPage 속성은 오류 페이지를 호출하는 page 디렉티브 태그의 속성이다.
      • JSP 페이지가 실행되는 도중에 오류가 발생하면 웹 서버의 기본 오류 페이지를 대신하여 errorPage 속성에 설정한 페이지가 오류 페이지로 호출된다.
    • isErrorPage 속성은 현재 JSP 페이지를 오류 페이지로 호출하는 page 디렉티브 태그의 속성이다.
      • 오류 페이지에선 getMessage(), toString(), printStackTrace() 같은 exception 내장 객체를 사용할 수 있다.
 

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

web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app> <security-role> <role-name>admin</role-name> </security-role> <security-constraint> <web-resource-collection> <web-resource-name>JSPBook</web-resource-name> <url-pattern>/ch10/practice/practice04.jsp</url-pattern> <http-method>GET</http-method> </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>/ch10/practice/practice04_login.jsp</form-login-page> <form-error-page>/ch10/practice/practice04_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> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/ch11/exceptionType_error.jsp</location> </error-page> </web-app>

errorCode.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</title> </head> <body> <form action="errorCode_process.jsp" method="post"> <p> 숫자1: <input type="text" name="num1"> <p> 숫자2: <input type="text" name="num2"> <p> <input type="submit" value="나누기"> </form> </body> </html>

errorCode_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</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.println(num1 + " / " + num2 + " = " + c); %> </body> </html>

errorCode_error.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</title> </head> <body> errorCode 505 오류가 발생하였습니다. </body> </html>

exceptionType_error.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</title> </head> <body> exception type 오류가 발생하였습니다. </body> </html>
 

핵심 키워드

  • web.xml 파일을 이용한 예외 처리는 web.xml 파일을 통해 오류 상태와 오류 페이지를 보여주는 방법으로, <error-page>태그 내에 처리할 오류 코드나 오류 유형 및 오류 페이지를 호출한다.
    • 오류 코드는 웹 서버가 제공하는 기본 오류 페이지에 나타나는 404, 500과 같이 사용자의 요청이 올바르지 않을 때 출력되는 코드로 응답 상태 코드라고도 한다.
    • 예외 유형에 따른 오류 페이지 호출 방법은 JSP 페이지가 발생시키는 오류가 web.xml 파일에 설정된 예외 유형과 일치하는 경우 예외 유형과 오류 페이지를 보여준다.
 

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

tryCatch_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</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 (ArithmeticException e) { RequestDispatcher dispatcher = request.getRequestDispatcher("tryCatch_error.jsp"); dispatcher.forward(request, response); } %> </body> </html>

tryCatch_error.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</title> </head> <body> <p>잘못된 데이터가 입력되었습니다. <p><%="숫자1 : "+request.getParameter("num1") %> <p><%="숫자2 : "+request.getParameter("num2") %> </body> </html>
 

핵심 키워드

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

연습문제

practice01.jsp

01 예외 처리는 프로그램이 처리되는 동안 특정한 문제가 발생했을 때 처리를 중단하고 다른 처리를 하는 것으로 오류 처리라고도 한다. 02 errorPage 속성은 오류 페이지를 호출하는 속성이다. isErrorPage 속성은 현재 JSp 페이지를 오류 페이지로 호출하는 속성이다. 03 web.xml 파일을 이용한 예외 처리는 web.xml 파일을 통해 오류 상태와 오류 페이지를 보여주는 방법이다. <error-page> 태그 내에 <error-code> 태그나 <exception-type> 태그를 이용해 오류 코드나 예외 유형으로 에러 페이지를 호출한 후 <location> 태그로 오류 페이지의 URI를 작성할 수 있다.

practice04.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page errorPage="practice04_isErrorPage.jsp" %> <html> <head> <title>Exception</title> </head> <body> <% int a = 1; int b = 0; int c = a / b; %> </body> </html>

practice04_isErrorPage.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page isErrorPage="true"%> <html> <head> <title>Exception</title> </head> <body> <h3>오류 발생</h3> <p>ERROR: <%=request.getAttribute("javax.servlet.error.exception")%>: 오류발생!! <p>URI: <%=request.getAttribute("javax.servlet.error.request_uri")%> <p>Status Code: <%=request.getAttribute("javax.servlet.error.status_code")%> </body> </html>

practice05.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</title> </head> <body> <form action="practice05_process.jsp" method="post"> <p> 아이디: <input type="text" name="id"> <p> 비밀번호: <input type="text" name="passwd"> <p> <input type="submit" value="전송"> </form> </body> </html>

practice05_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</title> </head> <body> <% String id = request.getParameter("id"); String passwd = request.getParameter("passwd"); if (id.equals("") || passwd.equals("")) { throw new ServletException(); } else { out.println("아이디: " + request.getParameter("id")); } %> </body> </html>

practice05_error.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Exception</title> </head> <body> <p> 오류 발생 : 요청 파라미터 값이 없습니다. <%@include file="practice05.jsp"%> </body> </html>

practice06.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page errorPage="practice04_isErrorPage.jsp" %> <html> <head> <title>Exception</title> </head> <body> <% try { int a = 1; int b = 0; int c = a / b; } catch (ArithmeticException e) { out.println("오류 발생: "+e.getMessage()); } %> </body> </html>

practice07

exceptionNoBookId.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <link rel="stylesheet" href="./resources/css/bootstrap.min.css"> <title>상품ID 오류</title> </head> <body> <jsp:include page="menu.jsp" /> <div class="jumbotron"> <div class="container"> <h2 class="alert alert-danger">해당 도서가 존재하지 않습니다.</h2> </div> </div> <div class="container"> <p><%=request.getRequestURL()%>?<%=request.getQueryString()%> <p> <a href="products.jsp" class="btn btn-secondary"> 도서 목록 &raquo;</a> </div> </body> </html>

product.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="dto.Book"%> <%@ page import="dao.BookRepository"%> <%@ page errorPage="exceptionNoBookId.jsp" %> <html> <head> <link rel="stylesheet" href="./resources/css/bootstrap.min.css" /> <title>도서 정보</title> </head> <body> <jsp:include page="menu.jsp" /> <div class="jumbotron"> <div class="container"> <h1 class="display-3">도서 정보</h1> </div> </div> <% String id = request.getParameter("id"); BookRepository dao = BookRepository.getInstance(); Book book = dao.getBookById(id); %> <div class="container"> <div class="row"> <div class="col-md-5"> <img src="/upload/<%=book.getFilename()%>" style="width: 100%"> </div> <div class="col-md-6"> <h3><%=book.getName()%></h3> <p><%=book.getDescription()%> <p> <b>도서 코드 : </b><span class="badge badge-danger"> <%=book.getBookId()%></span> <p> <b>출판사</b> : <%=book.getPublisher()%> <p> <b>저자</b> : <%=book.getAuthor()%> <p> <b>재고 수</b> : <%=book.getUnitsInStock()%> <p> <b>총 페이지 수</b> : <%=book.getTotalPages()%> <p> <b>출판일</b> : <%=book.getReleaseDate()%> <h4><%=book.getUnitPrice()%>원 </h4> <p> <a href="#" class="btn btn-info"> 도서 주문 &raquo;</a> <a href="./books.jsp" class="btn btn-secondary">도서 목록 &raquo;</a> </div> </div> <hr> </div> <jsp:include page="footer.jsp" /> </body> </html>

web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app> <security-role> <role-name>guest</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>/addBook.jsp</url-pattern> </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>/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>

exceptionNoPage.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <link rel="stylesheet" href="./resources/css/bootstrap.min.css"> <title>페이지 오류</title> </head> <body> <jsp:include page="menu.jsp" /> <div class="jumbotron"> <div class="container"> <h2 class="alert alert-danger">요청하신 페이지를 찾을 수 없습니다.</h2> </div> </div> <div class="container"> <p><%=request.getRequestURL()%></p> <p> <a href="products.jsp" class="btn btn-secondary"> 도서 목록 &raquo;</a> </div> </body> </html>
 

결론

해당 코드를 작성하면서 예외 처리의 개념, page 디렉티브 태그를 이용한 예외 처리 방법, web.xml 파일을 이용한 예외 처리 방법, try-catch-finally를 이용한 예외 처리 방법을 익힐 수 있었다.
Share article

More articles

See more posts
RSSPowered by inblog