SpringBoot06:Web开发静态资源处理

目录

使用SpringBoot的步骤:

一、静态资源处理

1、静态资源映射规则

2、什么是webjars呢?

3、第二种静态资源映射规则

4、自定义静态资源路径

二、首页处理

SpringBoot最大的特点就是自动装配。

使用SpringBoot的步骤:

  1. 创建一个SpringBoot应用,选择我们需要的模块,SpringBoot就会默认将我们需要的模块自动配置好;
  2. 手动在配置文件中配置部分配置项目就可以运行起来了;
  3. 专注编写业务代码,不需要考虑以前那些一大堆的配置了。

要熟悉掌握开发,之前学习的自动配置的原理一定要搞明白!
比如SpringBoot到底帮我们配置了什么?我们能不能修改?我们能修改哪个位置?我们能不能扩展?

  • 向容器中自动配置组件:***Autoconfiguration
  • 自动配置类,封装配置文件的内容:***Properties
  • 熟悉自动装配原理!

一、静态资源处理

1、静态资源映射规则

首先,搭建一个普通的SpringBoot项目,回顾一下HelloWorld程序!
写请求非常简单,那要引入前端资源,项目中有许多的静态资源,比如css,js等文件,这个SprigBoot怎么处理呢?

如果项目是一个web应用,main下会有一个webapp,以前都是将多有的页面放在这个下面,但是现在的pom打包方式为jar的方式,这种方式SpringBoot能不能来给我们写页面呢!当然是可以的,但是SpringBoot对于静态资源放置的位置是有规定的。

静态资源映射的规则

在SpringBoot中,SpringMVC的配置都在WebMvcAutoConfiguration这个配置类里面,内含很多配置方法;

例如:addResourceHandlers添加资源处理

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
	if (!this.resourceProperties.isAddMappings()) {
		logger.debug("Default resource handling disabled");
		return;
	}
	Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
	CacheControl cacheControl=this.resourceProperties.getCache().
                                   getCachecontrol().toHttpCacheControl();
	if (!registry.hasMappingForPattern("/webjars/**")) {
		customizeResourceHandlerRegistration(
                 registry.addResourceHandler("/webjars/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/")
				.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
	}
	String staticPathPattern = this.mvcProperties.getStaticPathPattern();
	if (!registry.hasMappingForPattern(staticPathPattern)) {
	    customizeResourceHandlerRegistration(
                registry.addResourceHandler(staticPathPattern)
                .addResourceLocations(
                getResourceLocations(this.resourceProperties.getStaticLocations()))				 
                .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
		}
	}
}

读源码可知:比如所有的/webjars/**,都需要去classpath:/META-INF/resources/webjars/找对应的资源。

2、什么是webjars呢?

Webjars本质就是以jar包的方式引入静态资源,以前要导入一个静态资源文件,直接导入即可。
使用SpringBoot需要使用Webjars的依赖:要使用jQuery,只要引入jQuery对应版本的pom以来即可以!

 <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>jquery</artifactId>
      <version>3.4.1</version>
 </dependency>

导入完毕,查看webjars目录结构,并访问Jquery.js文件!

 访问:只要是静态资源,SpringBoot就回去对应的路径寻找资源,

访问路径:http://localhost:8080/webjars/jquery/3.4.1/jquery.js

3、第二种静态资源映射规则

项目中要使用的静态资源该如何导入呢?
我们去找staticPathPattern发现第二种映射规则:/**,访问当前的项目任意资源,它会去找resourceProperties这个类,分析:

public String[] getStaticLocations() {
	return this.staticLocations;
}

/**
 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
 * /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

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

ResourceProperties可以设置和静态资源有关的参数;这里指向了它会去寻找资源的文件夹,即上面数组的内容。
所以得出结论,以下四个目录存放的静态资源可以被识别到:

"classpath:/META-INF/resources/",
"classpath:/resources/", 
"classpath:/static/", 
"classpath:/public/"

我们可以在resource根目录下新建对应的文件夹,都可以存放静态文件夹;
比如访问:http://localhost:8080/1.js,它就会去这些文件夹中寻找对应的静态资源文件;

4、自定义静态资源路径

也可以通过配置文件来指定静态资源文件存放的位置,在application.properties中配置;

spring.resources.static-locations=classpath:/coding/,classpath:/wan/

一旦自己定义了静态文件夹得路径,原来得自动配置就都会消失了!

二、首页处理

首页映射的处理:
1、在加载系统首页的时候,欢迎页处理映射:welcomePageHandlerMapping方法会使用获取静态资源位置:getResourceLocations方法获取静态资源默认位置,静态资源位置首选我们自己配置的,若未配置那么选择系统默认的静态资源位置;
2、可以获取静态资源位置的文件夹可能有多个,会对多个静态资源的位置进行遍历,找第一个文件的index.html首页进行显示;

//欢迎页处理映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
	FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
	WelcomePageHandlerMapping welcomePageHandlerMapping = 
                    new WelcomePageHandlerMapping(
                    new TemplateAvailabilityProviders(applicationContext),                 
                    applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(
                    getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    return welcomePageHandlerMapping;
}
//获取欢迎页首页
private Optional<Resource> getWelcomePage() {
	String[] locations =                 
                getResourceLocations(this.resourceProperties.getStaticLocations());
	return  Arrays.stream(locations)
                  .map(this::getIndexHtml)
                  .filter(this::isReadable).findFirst();
}

//获取静态资源位置
static String[] getResourceLocations(String[] staticLocations) {
	String[] locations = new String[staticLocations.length + 
                                    SERVLET_LOCATIONS.length];
	System.arraycopy(staticLocations, 0, locations, 0, staticLocations.length);
	System.arraycopy(SERVLET_LOCATIONS, 0, locations, staticLocations.length, 
                     SERVLET_LOCATIONS.length);
	return locations;
}

//获取首页
private Resource getIndexHtml(String location) {
	return this.resourceLoader.getResource(location + "index.html");
}

欢迎页静态资源文件夹下的所有index.html页面;被/**映射;
比如访问:http://localhost:8080/就会找静态资源文件夹下的index.html;

猜你喜欢

转载自blog.csdn.net/weixin_44740328/article/details/131544748