如何在 Spring MVC 中通过返回自定义错误页面来全局处理 404 异常?

How to globally handle 404 exception by returning a customized error page in Spring MVC?

我需要 return HTTP 404 的自定义错误页面,但代码不起作用。我已经阅读了 stackflow 1,2, 3 and different online + articles 但我的情况与那些完全不同,或者至少我无法弄清楚问题所在。

HTTP Status 404 -

type Status report

message

description The requested resource is not available.

例如,建议使用web.xml中的动作名称来处理异常,它可能会起作用,但我认为这不是一个好的方法。

我使用了以下组合:

1)

@Controller   //for class
@ResponseStatus(value = HttpStatus.NOT_FOUND) //for method

2)
 @Controller   //for class
 @ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
 @ExceptionHandler(ResourceNotFoundException.class) //for method

3)

@ControllerAdvice //for class
@ResponseStatus(value = HttpStatus.NOT_FOUND) //for method

3)

@ControllerAdvice //for class
@ResponseStatus(HttpStatus.NOT_FOUND) //for method

4)
 @ControllerAdvice   //for class
 @ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
 @ExceptionHandler(ResourceNotFoundException.class) //for method

代码

@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public String handleBadRequest(Exception exception) {
          return "error404";
    }
}

您可以在 class 级别使用@ResponseStatus 注释。至少对我有用。

@Controller
@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class GlobalExceptionHandler {
  ....  
}

DispatcherServlet 默认情况下不会抛出异常,如果它没有找到处理请求的处理程序。所以你需要如下显式激活它:

在web.xml中:

<servlet>
    <servlet-name>mvc-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>
    <load-on-startup>1</load-on-startup>
</servlet>

如果您使用的是基于注解的配置:

dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

在控制器建议中class:

@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleExceptiond(NoHandlerFoundException ex) {
    return "errorPage";
}

您可以在 web.xml 中添加以下内容以在 404 上显示错误页面。它将显示 404.jsp WEB-INF 文件夹内 views 文件夹中的页面。

 <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/404.jsp</location>
 </error-page>