繁体   English   中英

自定义错误请求HTTP400页面Spring MVC

[英]Customize bad request HTTP400 page Spring MVC

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

是的,您可以实现这一目标。

您需要定义全局错误处理程序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

要添加到@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错误类别的组提供View页面。 看一下文档 简而言之,您可以在/resources目录下的/error目录下提供“查看”页面或“ HTTP错误代码”组页面(方便的配置约定)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM