是否可以在完成错误请求并返回HTTP400错误代码时自定义从Spring返回的html页面?
答案 0 :(得分:0)
是的,你可以做到这一点。
您需要定义全局错误处理程序 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 :(得分:0)
要添加@Yogi,请回答2个替代方案:
<error-page> <error-code>400</error-code> <location>/WEB-INF/my/location/to/http/errors/400.jsp</location> </error-page>
/error
目录下的/resources
目录下提供View页面或HTTP-Error-Code-group页面(方便的约定配置方法)。