【问题标题】:Customize bad request HTTP400 page Spring MVC自定义错误请求 HTTP400 页面 Spring MVC
【发布时间】:2018-01-04 16:38:40
【问题描述】:

当错误请求完成并返回HTTP400错误代码时,是否可以自定义从Spring返回的html页面?

【问题讨论】:

    标签: java spring error-handling bad-request


    【解决方案1】:

    是的,你可以做到这一点。

    您需要定义全局错误处理程序 ControllerAdvice 注释。

    示例代码如下:

    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        public static final String DEFAULT_ERROR_VIEW = "error";
    
        @ExceptionHandler(value = Exception.class)
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
    
            // If the exception is annotated with @ResponseStatus rethrow it and let
            // the framework handle it.
            if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
                throw e;
    
            // setup and send the user to a default error-view.
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e);
            mav.addObject("url", req.getRequestURL());
            mav.setViewName(DEFAULT_ERROR_VIEW);
            return mav;
        }
    }
    

    进一步阅读:

    1. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html
    2. https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

    【讨论】:

      【解决方案2】:

      要添加到@Yogi 回答另外 2 个备选方案:

      1. 如果您使用的是 web.xml,则有一个非常方便的选项可以为每个 HTTP 错误代码提供专用的查看页面
      <error-page>
         <error-code>400</error-code>
         <location>/WEB-INF/my/location/to/http/errors/400.jsp</location>
      </error-page>
      
      1. Spring Boot 还提供了一种非常方便的方式来执行相同的操作,另外还提供了为 http 错误类别组提供查看页面的附加选项。 Take a look at the documentation。简而言之,您可以在/resources 目录下的/error 目录下提供查看页面或HTTP-Error-Code-group 页面(方便的约定优于配置的方法)。

      【讨论】:

        猜你喜欢
        • 2014-01-30
        • 1970-01-01
        • 1970-01-01
        • 2014-06-27
        • 1970-01-01
        • 2017-01-06
        • 2013-08-17
        • 1970-01-01
        • 2014-11-09
        相关资源
        最近更新 更多