笔记——Spring Boot访问静态资源

前言

        记录学习历程,在学习笔记中有描述不正确的地方,欢迎小伙伴们评论指正。

 Spring Boot访问Web中的静态资源,默认情况下指定了一些固定的目录结构。静态资源放在指定目录结构中的某一个,服务启动后可以用浏览器直接访问。

源码:org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
        在WebMvcAutoConfiguration.java中的添加静态资源映射addResourceHandlers方法中可以找到静态资源的自动化配置信息。

		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
            //添加静态资源映射webjars
			addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
            //添加静态资源映射
			addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
                //在映射中所要放开的资源 this.resourceProperties.getStaticLocations() 和 SERVLET_LOCATION
				registration.addResourceLocations(this.resourceProperties.getStaticLocations());
				if (this.servletContext != null) {
					ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
					registration.addResourceLocations(resource);
				}
			});
		}

ResourceHandlerRegistry类的作用

        通过Spring MVC存储资源处理程序的注册,以服务静态资源,如图像、css文件和其他资源,包括设置缓存头,以便在web浏览器中有效加载。资源可以在web应用程序根目录下的位置之外提供,比如类路径等。
        要创建一个资源处理程序,使用addResourceHandler(String…)提供URL路径模式,应该调用该处理程序来服务静态资源(例如。“/资源/ * *”)。然后在返回的ResourceHandlerRegistration上使用其他方法来添加一个或多个提供静态内容的位置(例如{"/","classpath:/META-INF/public-web-resources/"}),或者为所服务的资源指定一个缓存周期。

this.resourceProperties.getStaticLocations()

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

private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

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

        进入resourceProperties.getStaticLocations()中可以看到,添加静态资源映射中所要放开的资源有:

        1、classpath:/META-INF/resources/
        2、classpath:/resources/
        3、classpath:/static/
        4、classpath:/public/
        5、SERVLET_LOCATION指定的根目录:/

依次创建同名的HTML文件放入以上目录结构中,测试执行的优先级顺序。

故,执行优先级顺序为:META-INF/resources > resources > static > public

当静态资源放入以上文件夹中可以直接访问到,但当静态资源放入根目录【根目录指:src/main/webapp/,需要创建webapp目录】后直接访问就会报404错误。为什么?

因为创建的webapp目录中的文件没有在项目代码编译的时候在resources路径下生成文件。所以需要在pom.xml中增加以下配置。

<build>
    <resources>
        <resource>
            <directory>src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <includes>
                <include>**/**</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/**</include>
            </includes>
        </resource>
    </resources>
</build>

修改静态资源映射

private String staticPathPattern = "/**";

public String getStaticPathPattern() {
	return this.staticPathPattern;
}

在上面的源码中可以找到 this.mvcProperties.getStaticPathPattern() 进入后为上述源码,默认为 /** 。修改资源映射可以通过配置 spring.mvc.static-path-pattern: /** 来完成。再次访问时,需要在页面前面加入增加的前缀来进行访问。

spring:
  application:
    name: learn-statics
  mvc:
    static-path-pattern: /stic/**

WebJars

         WebJars是前端资源库打成的Jar包文件。在基于jvm的web应用程序中显式且轻松地管理客户端依赖关系。引入WebJars依赖后,SpringBoot默认将引入的前端资源放入META-INF/resources/webjars下,前端引用时需要在 /webjars/.... 使用前端资源。

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.6.0</version>
</dependency>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>/</title>
  <script src="/webjars/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <h1>我是/</h1>
</body>
</html>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值