SpringBoot中干掉Whitelabel Error Page返回自定义内容的实现

 更新时间:2021年01月05日 11:35:05   作者:MylesYang  
这篇文章主要介绍了SpringBoot中干掉Whitelabel Error Page返回自定义内容的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

 1. 引言

SpringBoot中对于错误请求的页面是长这样的,

Whitelabel Error Page

然而我们在访问在一些网站时,如果请求错误,一般都会有友好美观的提示,比如知乎这个,这比起一堆错误信息要友好的多了。

BHu

我们可以根据项目业务来自定义错误请求(RequestMapping中没有映射到的请求)的处理,比如返回自定义错误页面或者Json字符串。

2. 分析

我们看看SpringBoot中对于错误请求是如何处理的。SpringBoot项目中搜索Whitelabel定位到类WhitelabelErrorViewConfiguration,可以看到它是ErrorMvcAutoConfiguration的一个静态内部类,而且正是这个类处理的错误请求的,代码中的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...
}

仔细研究这个代码,我们不难发现,我们至少有两种方法可以替换掉默认的实现自定义错误页面。

入手点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控制了这个类是否装配,我们可以在配置中将其设为false

server:
 error:
  whitelabel:
   enabled: false
  path: /error

该配置类为ErrorProperties,默认的错误请求为/error,将 whitelabel 禁用后在 controller 中定义请求 /error返回自定义内容。

@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

具体报错原因未作分析,怀疑是我项目设置有问题,笔者使用的SpringBoot版本是2.3.6.RELEASE,大家可以尝试一些行不行。既然第一个方法尝试接着尝试失败,那就试试第二个吧。

3.2 尝试2

@Bean(name = "error")
@ConditionalOnMissingBean(name = "error")

这个操作更简单,我们只要向IoC 容器中注入一个名为errorBean即可,返回类型为View:

@Configuration
public class MyConfig {
  @Bean("error")
	public View error() {
		ModelAndView view = new ModelAndView(new MappingJackson2JsonView());
		return view.getView();
	}
}

其中new MappingJackson2JsonView()返回的Json字符串的 View ,当然你也可以根据业务需求灵活使用,如果想获取HttpServletRequest可以这样获取,但使用时需要注意判空,因为Bean实例化注入是可能获取不到HttpServletRequest而造成NPE,项目启动失败。

public static HttpServletRequest getRequest() {
  return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
     .map(r -> ((ServletRequestAttributes) r).getRequest())
     .orElse(null);
}

结果当然是没问题的,会返回以下信息:

result

4. 总结

解决问题:

搜索引擎找解决方法深入源码尝试自己解决

到此这篇关于SpringBoot中干掉Whitelabel Error Page返回自定义内容的文章就介绍到这了,更多相关SpringBoot返回自定义内容内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot统一返回格式的方法详解

    SpringBoot统一返回格式的方法详解

    今天小编主要是和大家分享一个让代码变得更简洁的小技巧:统一返回格式,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-08-08
  • 详解Spring Boot Profiles 配置和使用

    详解Spring Boot Profiles 配置和使用

    本篇文章主要介绍了详解Spring Boot Profiles 配置和使用,具有一定的参考价值,有兴趣的可以了解一下
    2017-06-06
  • Java 按行读取文件按行写入文件并以空格分割字符串的方法

    Java 按行读取文件按行写入文件并以空格分割字符串的方法

    今天小编就为大家分享一篇Java 按行读取文件按行写入文件并以空格分割字符串的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • spring boot使用thymeleaf模板的方法详解

    spring boot使用thymeleaf模板的方法详解

    thymeleaf 是新一代的模板引擎,在spring4.0中推荐使用thymeleaf来做前端模版引擎。下面这篇文章主要给大家介绍了关于spring boot使用thymeleaf模板的方法,文中通过示例代码介绍的非常详细,需要的朋友们下面来一起看看吧。
    2017-07-07
  • 深入解析Java编程中面向字节流的一些应用

    深入解析Java编程中面向字节流的一些应用

    这篇文章主要介绍了Java编程中面向字节流的一些应用,是Java入门学习中的基础知识,需要的朋友可以参考下
    2015-10-10
  • Java多线程编程中的并发安全问题及解决方法

    Java多线程编程中的并发安全问题及解决方法

    保障多线程并发安全,解决线程同步与锁竞争问题,提高应用性能与可靠性。多线程编程需要考虑线程安全性,使用同步机制保证共享变量的一致性,避免线程竞争导致的数据不一致与死锁等问题。常用的同步机制包括synchronized、ReentrantLock、volatile等
    2023-04-04
  • 详解Springboot下载Excel的三种方式

    详解Springboot下载Excel的三种方式

    本文给大家分享Springboot下载Excel三种方式,主要分为浏览器下载和代码本地下载实现的方式,针对每种实现方式给大家介绍的非常详细,需要的朋友参考下吧
    2021-07-07
  • SpringCloud使用集中配置组件Config规避信息泄露

    SpringCloud使用集中配置组件Config规避信息泄露

    项目应用中,数据库连接信息、Access-key、Secret-key等由于其及其敏感和特殊性,一旦泄露出去就很可能会使得应用遭到黑客攻击,例如数据库账号密码泄露可能导致“拖库”,甚至数据丢失。此等事件偶有发生,那么,在分布式微服务项目中,怎么避免这种情况呢
    2022-07-07
  • 使用Java读取Excel文件数据的方法详解

    使用Java读取Excel文件数据的方法详解

    通过编程方式读取Excel数据能实现数据导入、批量处理、数据比对和更新等任务的自动化,本文为大家介绍了三种Java读取Excel文件数据的方法,需要的可以参考下
    2024-01-01
  • Spring实现IoC的多种方式小结

    Spring实现IoC的多种方式小结

    本篇文章主要介绍了Spring实现IoC的多种方式小结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-02-02

最新评论