📕🐘 도로락 - 코끼리를 냉장고에 넣는 방법
Servlet&Jsp | 2018. 8. 1. 19:52

[서블릿/JSP] Exception 타입에 따른 오류 처리 JSP 맵핑하기

이전글

Exception 타입에 따른 오류 처리 JSP 맵핑하기

WEB-INF/web.xml 설정에서 <error-page> 태그를 이용하여 서버에서 Exception이 발생하였을 때 Exception 의 클래스 타입에 따라 원하는 처리 페이지를 지정해줄 수 있습니다.

다음과 같이 web.xml<error-page> 태그를 넣고 <exception-type>에는 처리를 원하는 Exception<location> 태그에는 사용자에게 보여줄 처리 페이지 경로를 넣습니다.

<?xml version="1.0" encoding/UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         id="WebApp_ID" version="3.1">

    <error-page>
        <exception-type>java.lang.NullPointerException</exception-type>
        <location>/internalEx.jsp</location>
    </error-page>

</web-app>

웹 어플리케이션 경로 /internalEx.jsp 페이지입니다. 별다를 것 없는 단순 JSP 페이지입니다. 앞의 설정대로라면 웹 어플리케이션 내에서 NullPointerException이 발생하는 경우 따로 try-catch문으로 예외 처리를 해주지 않는 이상 internalEx.jsp 페이지의 결과를 리턴합니다.

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

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
죄송합니다.
내부 오류가 발생하였습니다.
</body>
</html>

nullEx.jsp 페이지입니다. 이페이지를 요청하면 강제로 NullPointerException이 발생하게 되고 설정에 따라 internalEx.jsp 페이지의 결과를 볼 수 있을 것입니다.

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

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
<%
    String nullStr = null;
    System.out.println(nullStr.toString());
%>
</body>
</html>

nullEx.jsp를 요청하게 되면 web.xml 에러 처리 설정에 따라 internalEx.jsp의 처리 결과가 리턴됩니다.

도로락

도로락

Writer

IT, 프로그래밍, 컴퓨터 활용 정보 등을 위한 블로그