SpringBoot定制异常页面
先看后台代码:
1由于是实验所以先把拦截器注释掉,当然不想注释,再加上这些异常请求也行,我这里先把这些注释掉:
public void addInterceptors(InterceptorRegistry registry) { //addPathPatterns("/**").excludePathPatterns("/","/index.html","/user/login");添加所有拦截除了excludePathPatterns;里面 // registry.addInterceptor(new LoginHandlerIntercepter()).addPathPatterns("/**").excludePathPatterns("/", // "/index.html","/user/login"); }
2.定制异常类:
public class UserNotExitsException extends RuntimeException{ public UserNotExitsException(){ //super指向当前父类这样就可以引用父类的成员;2.子类中的成员变量或者方法与父类的同名3.调用父类的一个构造函数应放在代码的第一句 super("用户不存在"); } }
要集成RuntimeException方便运行时抛出异常。
3.写controller:
@ControllerAdvice public class MyExceptionHandler { //将自定义的异常引入进来 @ExceptionHandler(UserNotExitsException.class) public String handleException(Exception e, HttpServletRequest request){ Map<String,Object>map=new HashMap<>(); //定义状态码。注意不要写错。 request.setAttribute("javax.servlet.error.status_code",500); //定义code与mseeage用于页面展示。 map.put("code","user.notexit"); map.put("message","用户出错了"); request.setAttribute("ext",map); return "forward:/error"; } }
@ControllerAdvice是controller的增强版是一个compent适用于所有使用的@RequestMapping方法主要用于处理异常通常与@ExceptionHandler一块用。转发到/error进行自适应响应效果处理。
4.编写错误属性:
@Component public class MyErrorAttributes extends DefaultErrorAttributes{ public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String,Object>map= super.getErrorAttributes(webRequest, includeStackTrace); map.put("compay","xixiha"); //引入我们的异常处理器所带的数据.0代表从请求域中获取1session中 Map<String,Object> ext= (Map<String, Object>) webRequest.getAttribute("ext",0); //获取的数据放入到map中用于页面取值 map.put("ext",ext); return map; } }
用@component将这个类交给spring剩下的就是sprigboot内部的处理了(即给容器中加入我们自己定义的ErrorAttributes)。
看前台展示页面:
在templates文件夹下放错误页面(
有模板引擎的情况下;error/状态码;** 【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的 error文件夹下】,发生此状态码的错误就会来到 对应的页面;
我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html);
)
最终效果: