如何用 Spring MVC 覆盖 Jetty 的 404 错误?

How to override Jetty's 404 error with Spring MVC?

当我到达不存在的页面时,我得到:

HTTP ERROR 404

Problem accessing /swagger-ui.ht. Reason:

Not Found

为了覆盖我创建的 jetty 的 404 错误页面:

WEB-INF/jsp/404.jsp

<html>
<head>
    <title>Error Page</title>
</head>
<body>
    <p>An error occured, please contact webmaster.</p>
</body>

WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

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

</web-app>

据我所知,我需要在 WebMvcConfigurerAdapter 中创建一些 Bean,但找不到合适的。问题是,我已经有了@RestControllerAdvice,所以这不应该覆盖我的控制器建议。

正确的方法是什么?

也许尝试使用注释

class MyController {
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ModelAndView handleNotFound() {
        return new ModelAndView("redirect:/error.htm");
    }
}

既然您正在使用 Spring MVC 处理 Web 应用程序,我会做的是创建一个客户 Exception 处理程序,每次您请求不存在的资源时都会调用该处理程序

像这样:

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {
    return "errorPage.html";
}

这样您就可以为每个 @Controller 配置不同的页面(如果需要)。你有更大的灵活性。

所以有一个解决方案: 您需要将 DispatcherServlet 设置为在没有请求处理程序时抛出异常:

dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

然后,当您尝试到达某个端点并且控制器中没有它的处理程序时,spring 将抛出 NoHandlerFoundException。您可以在@ControllerAdvice 中处理:

@ExceptionHandler({NoHandlerFoundException.class})
public ResponseEntity<> handle(NoHandlerFoundException e, Locale locale) {
    ....
}