• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot首页设置解析(推荐)

python 搞代码 4年前 (2022-01-09) 35次浏览 已收录 0个评论

首先来解释一下SpringBoot首页设置的三种方式

1.SpringBoot默认首页设置

编写一个最简单的html文件 index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
</head>
<body>
<h1>首页</h1>
</body>
</html>

将index.html文件置于SpringBoot的任一静态资源目录下

http://localhost:8080/访问,成功显示

源码分析

首先找对应的自动配置类WebMvcAutoConfiguration中的对应代码

@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
 WelcomePageHandlerMapping welcomePageHandlerMapping = 
 	new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext),
 		 applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
 welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
 welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
 return welcomePageHandlerMapping;
}

可以看到 SpringBoot注册了WelcomePageHandlerMappingBean来处理项目的默认首页,构造器中的this.getWelcomePage()为首页资源。

private Resource getWelcomePage() {
 String[] var1 = this.resourceProperties.getStaticLocations();
 int var2 = var1.length;

 for(int var3 = 0; var3 < var2; +<i>本文来源gaodai$ma#com搞$$代**码)网@</i>+var3) {
  String location = var1[var3];
  Resource indexHtml = this.getIndexHtml(location);
  if (indexHtml != null) {
  return indexHtml;
  }
 }

 ServletContext servletContext = this.getServletContext();
 if (servletContext != null) {
  return this.getIndexHtml((Resource)(new ServletContextResource(servletContext, "/")));
 } else {
  return null;
 }
}

分析这段代码,首先获取了this.resourceProperties的StaticLocations字段,顾名思义就是静态路径,那就先跟踪StaticLocations

可以看出StaticLocations是WebPropertis中内部静态类Resources的属性,从构造器中可以看出它的值为

 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

显而易见,这其实就是SpringBoot的静态资源目录

/META-INF

/resources/

/resources/

/static/

/public/

回到之前的代码,获取了StaticLocations后,通过循环遍历,很明显可以看到一个新的方法this.getIndexHtml(location)

private Resource getIndexHtml(String location) {
 return this.getIndexHtml(this.resourceLoader.getResource(location));
}

使用this.resourceLoader返回一个与location对应的Resource执行另一个getIndexHtml()函数

private Resource getIndexHtml(Resource location) {
 try {
  Resource resource = location.createRelative("index.html");
  if (resource.exists() && resource.getURL() != null) {
  return resource;
  }
 } catch (Exception var3) {
 }

 return null;
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot首页设置解析(推荐)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址