본문 바로가기

SPRING

404 NOT_FOUND 처리하기

스프링 MVC의 모든 요청은 DispatcherServlet을 통해 처리되므로 404 에러도 같이 처리할 수 있도록 해야한다.

 

 

1. web.xml 설정 추가

 

<!-- 서블릿과 관련된 설정 -->
<servlet>
	<servlet-name>appServlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
	</init-param>
	<!-- 여기서부터 추가 -->
	<init-param>
		<param-name>throwExceptionIfNoHandlerFound</param-name>
		<param-value>true</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

 

 

2. Controller

 

@ControllerAdvice

해당 객체가 스프링의 컨트롤러에서 발생하는 예외를 처리하는 존재임을 명시

 

@ExceptionHandler

해당 메서드가 ()에 들어가는 예외 타입을 처리한다는 것을 의미

즉, NoHandlerFoundException 예외가 발생하면 custom404 페이지를 띄우겠다는 것을 의미

 

@ResponseStatus

Exception이 발생했을 때, 어노테이션에 정의된 API Response Status Code로 반환

 

package org.zerock.exception;

import org.springframework.http.HttpStatus;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import lombok.extern.log4j.Log4j;

@ControllerAdvice
@Log4j
public class CommonExcetionAdvice {

	@ExceptionHandler(NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public String handle404(NoHandlerFoundException ex) {
		return "custom404";
	}
	
}

 

 

3. custom404.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>해당 URL은 존재하지 않습니다.</h1>	
</body>
</htm

'SPRING' 카테고리의 다른 글

로그인 / 로그아웃 / 세션  (0) 2020.10.12
비밀번호 변경하기  (0) 2020.10.12
파일 업로드 처리 : MultipartResolver  (0) 2020.10.11
Model 객체 / @ModelAttribute  (0) 2020.10.11
@RequestParam 어노테이션  (0) 2020.10.11