FireDrago
[JSP] web.xml 파일을 이용한 예외처리 본문
jsp에서 예외처리를 하는 방법은 총 3가지가 있다.
| 1. <% page errorPage ="에러나면 이동할 파일"%> <% page isErrorPage ="true" %> : exception 변수 사용가능 |
| 2. try catch 문 |
| 3. web.xml 파일 |
이 중 1, 2는 서버에서 자바파일이 실행되고 난 다음의 예외처리를 담당한다.
3. web.xml 파일은 서버가 최초로 시행될때 읽는 문서로서 초기 설정파일 이므로 자바코드가 실행되기전에 예외처리한다

web.xml 파일 내부에 오류코드와 오류페이지를 설정하고, 일치하는 오류코드가 발생한 경우 오류 페이지를 보여준다.
1. web.xml 파일 설정
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 예외 처리 설정 -->
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location> <!-- 예외 발생 시 이동할 JSP 페이지 경로 -->
</error-page>
<!-- URL 패턴 지정 -->
<servlet>
<servlet-name>exceptionServlet</servlet-name>
<servlet-class>com.example.ExceptionServlet</servlet-class> <!-- 예외 처리를 담당할 서블릿 클래스 -->
</servlet>
<servlet-mapping>
<servlet-name>exceptionServlet</servlet-name>
<url-pattern>/exception</url-pattern> <!-- 예외 처리할 URL 패턴 -->
</servlet-mapping>
<!-- 기타 설정 -->
...
</web-app>
2. 입력폼 (form.jsp) 작성
<!-- form.jsp -->
<html>
<head>
<title>Input Form</title>
</head>
<body>
<form action="exception" method="post"> <!-- 데이터 처리를 위한 URL을 지정 -->
<input type="text" name="data" placeholder="Enter data"> <!-- 데이터 입력 필드 -->
<input type="submit" value="Submit"> <!-- 데이터 전송 버튼 -->
</form>
</body>
</html>
3. 처리폼 (exception.jsp) 작성
<!-- exception.jsp -->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<head>
<title>Exception Handling</title>
</head>
<body>
<%-- 데이터 처리 로직 --%>
<% String data = request.getParameter("data"); %>
<%-- 예외 발생 시 처리 --%>
<% try {
// 데이터 처리 로직
} catch (Exception e) {
// 예외 처리 로직
// 예외 발생 시 처리할 내용 작성'프로그래밍 > 템플릿 엔진(thymeleaf, jsp)' 카테고리의 다른 글
| [JSP] Cookie (0) | 2023.06.20 |
|---|---|
| [JSP] Filter로 로그기록 만들기 (0) | 2023.06.19 |
| [JSP] MultipartRequest 사용하여 파일 입력받기 (0) | 2023.06.18 |
| [JSP] 초간단 CRUD 구현(2) (0) | 2023.06.18 |
| [JSP] 초간단 CRUD 구현 (0) | 2023.06.18 |
