首先创建一个配置类
@Component
public class ErrorConfig implements ErrorPageRegistrar{
//配置错误状态与对应访问路径
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
ErrorPage error405Page = new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/405");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500");
registry.addErrorPages(error404Page,error405Page,error500Page);
}
}
然后写一个controller跳转error页面
@Controller
public class MyExceptionHandler {
//处理404 405 500请求错误
@RequestMapping({"/404","/405","/500"})
public String error404Page(HttpServletResponse response,HttpServletRequest request) {
int status = response.getStatus();
String msg="";
if (status==404) {
msg="Not Found! 未找到,服务器找不到请求的网页";
}
if (status==405) {
msg="METHOD_NOT_ALLOWED! 方法禁用,禁用请求中指定的方法";
}
if (status==500) {
msg="Internal Server Error! 服务器内部错误,服务器遇到错误,无法完成请求";
}
request.setAttribute("status", status);
request.setAttribute("message", msg);
return "/error/error";
}
}
我这样写的好处是把所有error都在一个error处理,但是问题就是写死了,有更好的建议可以评论,谢谢!
还有bug就是不能处理其他的错误请求,其他错误请求还是会到原来的页面上。