当错误的请求完成并返回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;
}
}
进一步阅读:
关于java - 自定义错误请求HTTP400页面Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099718/