SpringBoot中干掉Whitelabel Error Page返回自定義內(nèi)容的實現(xiàn)
1. 引言
SpringBoot中對于錯誤請求的頁面是長這樣的,

然而我們在訪問在一些網(wǎng)站時,如果請求錯誤,一般都會有友好美觀的提示,比如知乎這個,這比起一堆錯誤信息要友好的多了。

我們可以根據(jù)項目業(yè)務(wù)來自定義錯誤請求(RequestMapping中沒有映射到的請求)的處理,比如返回自定義錯誤頁面或者Json字符串。
2. 分析
我們看看SpringBoot中對于錯誤請求是如何處理的。SpringBoot項目中搜索Whitelabel定位到類WhitelabelErrorViewConfiguration,可以看到它是ErrorMvcAutoConfiguration的一個靜態(tài)內(nèi)部類,而且正是這個類處理的錯誤請求的,代碼中的defaultErrorView正是我們看到的默認錯誤頁面。
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
@Conditional(ErrorMvcAutoConfiguration.ErrorTemplateMissingCondition.class)
protected static class WhitelabelErrorViewConfiguration {
private final ErrorMvcAutoConfiguration.StaticView defaultErrorView = new ErrorMvcAutoConfiguration.StaticView();
@Bean(name = "error")
@ConditionalOnMissingBean(name = "error")
public View defaultErrorView() {
return this.defaultErrorView;
}
// and so on...
}
仔細研究這個代碼,我們不難發(fā)現(xiàn),我們至少有兩種方法可以替換掉默認的實現(xiàn)自定義錯誤頁面。
入手點1:
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
入手點2:
@Bean(name = "error") @ConditionalOnMissingBean(name = "error")
3. 嘗試
3.1 嘗試 1
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
我們看到server.error.whitelabel.enabled控制了這個類是否裝配,我們可以在配置中將其設(shè)為false
server: error: whitelabel: enabled: false path: /error
該配置類為ErrorProperties,默認的錯誤請求為/error,將 whitelabel 禁用后在 controller 中定義請求 /error返回自定義內(nèi)容。
@Controller
public class ErrorController {
@RequestMapping("/error")
@ResponseBody
public R error(HttpServletRequest request) {
Integer status = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (Objects.nonNull(status)) {
HttpStatus httpStatus = HttpStatus.valueOf(status);
return RUtils.fail(httpStatus);
}
return RUtils.fail("Error");
}
}
運行!一頓操作猛如虎,仔細一看原地杵,想法不錯,但瘋狂報錯:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL [jar:file:/D:/Environment/Maven/repository/io/springfox/springfox-spring-web/2.9.2/springfox-spring-web-2.9.2.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/D:/Environment/Maven/repository/io/springfox/springfox-spring-web/2.9.2/springfox-spring-web-2.9.2.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [xxx/xxx/xxx/config/WebMvcConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'basicErrorController' method
org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
to { /error}: There is already 'errorController' bean method
具體報錯原因未作分析,懷疑是我項目設(shè)置有問題,筆者使用的SpringBoot版本是2.3.6.RELEASE,大家可以嘗試一些行不行。既然第一個方法嘗試接著嘗試失敗,那就試試第二個吧。
3.2 嘗試2
@Bean(name = "error") @ConditionalOnMissingBean(name = "error")
這個操作更簡單,我們只要向IoC 容器中注入一個名為error的Bean即可,返回類型為View:
@Configuration
public class MyConfig {
@Bean("error")
public View error() {
ModelAndView view = new ModelAndView(new MappingJackson2JsonView());
return view.getView();
}
}
其中new MappingJackson2JsonView()返回的Json字符串的 View ,當然你也可以根據(jù)業(yè)務(wù)需求靈活使用,如果想獲取HttpServletRequest可以這樣獲取,但使用時需要注意判空,因為Bean實例化注入是可能獲取不到HttpServletRequest而造成NPE,項目啟動失敗。
public static HttpServletRequest getRequest() {
return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
.map(r -> ((ServletRequestAttributes) r).getRequest())
.orElse(null);
}
結(jié)果當然是沒問題的,會返回以下信息:

4. 總結(jié)
解決問題:
搜索引擎找解決方法深入源碼嘗試自己解決
到此這篇關(guān)于SpringBoot中干掉Whitelabel Error Page返回自定義內(nèi)容的文章就介紹到這了,更多相關(guān)SpringBoot返回自定義內(nèi)容內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot啟動異常Exception in thread “main“ java.lang.UnsupportedClassVersionError
- SpringBoot項目網(wǎng)頁加載出現(xiàn)Whitelabel?Error?Page的解決
- SpringBoot項目報錯:"Error?starting?ApplicationContext...."解決辦法
- springboot?ErrorPageFilter的實際應(yīng)用詳解
- SpringBoot自定義/error路徑失效的解決
- SpringBoot異常: nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletContext解決方案
- Springboot初始化啟動報錯Error?creating?bean?with?name?'dataSource'?defined?in?class?path?resource
相關(guān)文章
SpringMVC中的@RequestMapping注解解析
這篇文章主要介紹了SpringMVC中的@RequestMapping注解解析,SpringMVC使用@RequestMapping注解為控制器指定可以處理哪些?URL?請求,在控制器的類定義及方法定義處都可標注@RequestMapping,需要的朋友可以參考下2023-12-12
詳解mybatis.generator配上最新的mysql 8.0.11的一些坑
這篇文章主要介紹了詳解mybatis.generator配上最新的mysql 8.0.11的一些坑,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
關(guān)于@Value注入List,Map及設(shè)置默認值問題
這篇文章主要介紹了@Value注入List,Map及設(shè)置默認值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
通過Java實現(xiàn)在Word中創(chuàng)建可填充表單
這篇文章主要為大家詳細介紹了如何通過Java代碼,以編程方式在Word中創(chuàng)建可填充表單,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2023-03-03
Spring框架通過工廠創(chuàng)建Bean的三種方式實現(xiàn)
這篇文章主要介紹了Spring框架通過工廠創(chuàng)建Bean的三種方式實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03

