【问题标题】:How to override Jetty's 404 error with Spring MVC?如何使用 Spring MVC 覆盖 Jetty 的 404 错误?
【发布时间】:2016-10-13 13:00:33
【问题描述】:

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

HTTP 错误 404

访问 /swagger-ui.ht 时出现问题。原因:

Not Found

所以要覆盖我创建的码头的 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,所以这不应该覆盖我的控制器建议。

什么是正确的方法?

【问题讨论】:

    标签: java spring jsp spring-mvc jetty


    【解决方案1】:

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

    dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    

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

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

    【讨论】:

      【解决方案2】:

      也许可以尝试使用注释

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

      【讨论】:

        【解决方案3】:

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

        类似这样的:

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

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

        【讨论】:

        • 您告诉我为我据称试图访问的某些资源创建自定义异常,但我说的是 something.com/asdasfr11 情况,其中没有控制器和码头错误页面抛出。当 url 不正确时,我需要创建一个自定义错误页面。
        猜你喜欢
        • 2016-03-21
        • 2012-08-03
        • 1970-01-01
        • 2011-09-13
        • 2023-03-19
        • 2011-10-04
        • 2013-08-14
        • 1970-01-01
        • 2010-11-10
        相关资源
        最近更新 更多