SpringBoot中干掉Whitelabel Error Page返回自定義內(nèi)容的實(shí)現(xiàn)
1. 引言
SpringBoot中對于錯誤請求的頁面是長這樣的,
然而我們在訪問在一些網(wǎng)站時,如果請求錯誤,一般都會有友好美觀的提示,比如知乎這個,這比起一堆錯誤信息要友好的多了。
我們可以根據(jù)項(xiàng)目業(yè)務(wù)來自定義錯誤請求(RequestMapping中沒有映射到的請求)的處理,比如返回自定義錯誤頁面或者Json字符串。
2. 分析
我們看看SpringBoot中對于錯誤請求是如何處理的。SpringBoot項(xiàng)目中搜索Whitelabel
定位到類WhitelabelErrorViewConfiguration
,可以看到它是ErrorMvcAutoConfiguration
的一個靜態(tài)內(nèi)部類,而且正是這個類處理的錯誤請求的,代碼中的defaultErrorView
正是我們看到的默認(rèn)錯誤頁面。
@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... }
仔細(xì)研究這個代碼,我們不難發(fā)現(xiàn),我們至少有兩種方法可以替換掉默認(rèn)的實(shí)現(xiàn)自定義錯誤頁面。
入手點(diǎn)1:
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
入手點(diǎn)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
,默認(rèn)的錯誤請求為/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"); } }
運(yùn)行!一頓操作猛如虎,仔細(xì)一看原地杵,想法不錯,但瘋狂報(bào)錯:
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
具體報(bào)錯原因未作分析,懷疑是我項(xiàng)目設(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 ,當(dāng)然你也可以根據(jù)業(yè)務(wù)需求靈活使用,如果想獲取HttpServletRequest
可以這樣獲取,但使用時需要注意判空,因?yàn)锽ean實(shí)例化注入是可能獲取不到HttpServletRequest
而造成NPE
,項(xiàng)目啟動失敗。
public static HttpServletRequest getRequest() { return Optional.ofNullable(RequestContextHolder.getRequestAttributes()) .map(r -> ((ServletRequestAttributes) r).getRequest()) .orElse(null); }
結(jié)果當(dāng)然是沒問題的,會返回以下信息:
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項(xiàng)目網(wǎng)頁加載出現(xiàn)Whitelabel?Error?Page的解決
- SpringBoot項(xiàng)目報(bào)錯:"Error?starting?ApplicationContext...."解決辦法
- springboot?ErrorPageFilter的實(shí)際應(yīng)用詳解
- SpringBoot自定義/error路徑失效的解決
- SpringBoot異常: nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletContext解決方案
- Springboot初始化啟動報(bào)錯Error?creating?bean?with?name?'dataSource'?defined?in?class?path?resource
相關(guān)文章
SpringMVC中的@RequestMapping注解解析
這篇文章主要介紹了SpringMVC中的@RequestMapping注解解析,SpringMVC使用@RequestMapping注解為控制器指定可以處理哪些?URL?請求,在控制器的類定義及方法定義處都可標(biāo)注@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è)置默認(rèn)值問題
這篇文章主要介紹了@Value注入List,Map及設(shè)置默認(rèn)值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05通過Java實(shí)現(xiàn)在Word中創(chuàng)建可填充表單
這篇文章主要為大家詳細(xì)介紹了如何通過Java代碼,以編程方式在Word中創(chuàng)建可填充表單,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-03-03Spring框架通過工廠創(chuàng)建Bean的三種方式實(shí)現(xiàn)
這篇文章主要介紹了Spring框架通過工廠創(chuàng)建Bean的三種方式實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03