springboot-05-web静态资源导入

静态资源导入

SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置类里面,先进入这个类中,可以看到有很多方法,有一个方法:addResourceHandlers() 添加资源处理

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
	super.addResourceHandlers(registry);
	if (!this.resourceProperties.isAddMappings()) {
    
    
		logger.debug("Default resource handling disabled");
		return;
	}
	ServletContext servletContext = getServletContext();
	//静态资源导入方式一
	addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
	//静态资源导入方式一
	addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
    
    
		registration.addResourceLocations(this.resourceProperties.getStaticLocations());
		if (servletContext != null) {
    
    
			registration.addResourceLocations(new ServletContextResource(servletContext, SERVLET_LOCATION));
		}
	});
}

方式一

读一下源码,当路径是/webjars/**,会从classpath:/META-INF/resources/webjars/找资源

什么是webjars 呢?

  • WebJars是以Jar形式为Web项目提供资源文件,然后借助Maven这些依赖库的管理,保证这Web资源版本唯一性
  • Webjars多应用于基于Spring Boot创建微服务项目,需要打包所有资源为可执行的jar

网站:https://www.webjars.org

拿jQuery为例,要使用jQuery,只需导入对应的pom依赖

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

在这里插入图片描述
运行:只要是静态资源,SpringBoot就会去对应的路径寻找资源,我们这里访问:http://localhost:8080/webjars/jquery/3.4.1/jquery.js

在这里插入图片描述

方式二

一直点下去,可以看到请求路径
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
可以看到请求路径为/**。再看映射的路径。
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
当请求是/**时,会去下面这四个目录找静态资源

"classpath:/META-INF/resources/":就是上述的webjars
"classpath:/resources/":reources目录下的resources目录,自己新建
"classpath:/static/":resources目录下的static目录,项目自带
"classpath:/public/":resources目录下的public目录,自己新建

测试:在public目录下新建一个1.js
运行, 访问http://localhost:8080/1.js 即可看到1.js的内容。

猜你喜欢

转载自blog.csdn.net/qq_42665745/article/details/114600841