복붙노트

[SPRING] Spring 컨트롤러로 에러 404를 처리한다.

SPRING

Spring 컨트롤러로 에러 404를 처리한다.

제 웹 애플 리케이션에서 던진 예외를 처리하기 위해 @ExceptionHandler를 사용합니다. 제 경우에는 클라이언트에게 에러 응답을위한 HTTP 상태의 JSON 응답을 반환합니다.

그러나 @ExceptionHandler에 의해 처리되는 것과 비슷한 JSON 응답을 반환하기 위해 404 오류를 처리하는 방법을 파악하려고합니다.

최신 정보:

내 존재하지 않는 URL에 액세스하면

해결법

  1. ==============================

    1.가장 간단한 방법은 다음을 사용하는 것입니다.

    가장 간단한 방법은 다음을 사용하는 것입니다.

    @ExceptionHandler(Throwable.class)
      public String handleAnyException(Throwable ex, HttpServletRequest request) {
        return ClassUtils.getShortName(ex.getClass());
      }
    

    URL이 DispatcherServlet의 범위 내에있는 경우 오타 또는 기타 다른 이유로 인해 404가이 메서드에 의해 catch되지만, 입력 한 URL이 DispatcherServlet의 URL 매핑을 벗어나는 경우 다음 중 하나를 사용해야합니다.

    <error-page>
       <exception-type>404</exception-type>
       <location>/404error.html</location>
    </error-page>
    

    또는

  2. ==============================

    2.나는 봄 4.0과 자바 설정을 사용한다. 내 작업 코드는 다음과 같습니다.

    나는 봄 4.0과 자바 설정을 사용한다. 내 작업 코드는 다음과 같습니다.

    @ControllerAdvice
    public class MyExceptionController {
        @ExceptionHandler(NoHandlerFoundException.class)
        public ModelAndView handleError404(HttpServletRequest request, Exception e)   {
                ModelAndView mav = new ModelAndView("/404");
                mav.addObject("exception", e);  
                //mav.addObject("errorcode", "404");
                return mav;
        }
    }
    

    JSP에서 :

        <div class="http-error-container">
            <h1>HTTP Status 404 - Page Not Found</h1>
            <p class="message-text">The page you requested is not available. You might try returning to the <a href="<c:url value="/"/>">home page</a>.</p>
        </div>
    

    Init param config의 경우 :

    public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
        @Override
        public void customizeRegistration(ServletRegistration.Dynamic registration) {
            registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
        }
    }
    

    또는 xml을 통해 :

    <servlet>
        <servlet-name>rest-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>throwExceptionIfNoHandlerFound</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>
    

    Spring MVC 스프링 보안과 에러 처리

  3. ==============================

    3.@> 3.0을 사용하면 @ResponseStatus

    @> 3.0을 사용하면 @ResponseStatus

      @ResponseStatus(value = HttpStatus.NOT_FOUND)
      public class ResourceNotFoundException extends RuntimeException {
        ...
    }
    
        @Controller
        public class MyController {
        @RequestMapping.....
        public void handleCall() {
            if (isFound()) {
            // do some stuff
            }
            else {
                  throw new ResourceNotFoundException(); 
            }
        }
    }
    
  4. ==============================

    4.

    public final class ResourceNotFoundException extends RuntimeException {
    
    }
    
    
    @ControllerAdvice
    public class AppExceptionHandler {
        @ExceptionHandler(ResourceNotFoundException.class)
        @ResponseStatus(HttpStatus.NOT_FOUND)
        public String handleNotFound() {
            return "404";
        }
    }
    

    Exception, ExceptionHandler를 정의하여 비즈니스 코드 컨트롤러에서 예외를 throw하십시오.

  5. ==============================

    5.서블릿 표준 방법을 사용하여 404 오류를 처리 할 수 ​​있습니다. web.xml에 다음 코드를 추가하십시오.

    서블릿 표준 방법을 사용하여 404 오류를 처리 할 수 ​​있습니다. web.xml에 다음 코드를 추가하십시오.

    <error-page>
       <exception-type>404</exception-type>
       <location>/404error.html</location>
    </error-page>
    
  6. from https://stackoverflow.com/questions/13356549/handle-error-404-with-spring-controller by cc-by-sa and MIT license