时间:2022-10-25 09:32:45 | 栏目:JAVA代码 | 点击:次
SpringBoot实现MVC 404、500等错误时跳转自定义页面
package com.study.demo.config; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.ErrorPageRegistrar; import org.springframework.boot.web.server.ErrorPageRegistry; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; /** * 错误页面的配置 */ @Component public class ErrorPageConfig implements ErrorPageRegistrar { @Override public void registerErrorPages(ErrorPageRegistry registry) { ErrorPage error400Page = new ErrorPage(HttpStatus.BAD_REQUEST, "/errorPageController/error_400"); ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/errorPageController/error_401"); ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/errorPageController/error_404"); ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/errorPageController/error_500"); registry.addErrorPages(error400Page,error401Page,error404Page,error500Page); } }
package com.study.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/errorPageController") public class ErrorPageController { @RequestMapping("/error_{errorCode}") public String error(@PathVariable int errorCode){ String responseMsg; switch (errorCode) { case 400: responseMsg = "/400.html"; break; case 401: responseMsg = "/401.html"; break; case 404: responseMsg = "/404.html"; break; case 500: responseMsg = "/500.html"; break; default: responseMsg = "/404.html"; break; } return responseMsg; } }
请求出现错误时,跳转到自定义的页面中,比如404,假如没对错误进行处理,那么系统默认的页面与项目的页面会有很大的不搭。
解决:在默认的静态路径下,新建error文件,里面放入错误页面,页面命名为错误状态码,如:404.html,也可以命名为4xx.html,但如果两个文件同时存在,那么会优先展示404.html
注:静态路径为
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{ "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" }; // 注:还有一个默认的根路径 "/"
出现4xx或5xx错误时,ErrorPageCustomizer生效,就会来到/error请求,就会被BasicErrorController处理。
//在DefaultErrorViewResolver中有一段代码 // 处理4xx和5xx的请求 static { Map<Series, String> views = new EnumMap(Series.class); views.put(Series.CLIENT_ERROR, "4xx"); views.put(Series.SERVER_ERROR, "5xx"); SERIES_VIEWS = Collections.unmodifiableMap(views); } // 解析,并会跳转到error/错误状态码; 页面中 private ModelAndView resolve(String viewName, Map<String, Object> model) { String errorViewName = "error/" + viewName; TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext); // 对是否有模板引擎做出相应的视图处理 return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model); }