SpringBoot 静态资源处理

SpringBoot Web开发

  • 要解决的问题
    • 静态资源导入问题
    • 首页
    • jsp,模板引擎
    • 增删改查
    • 拦截器
    • 国际化

SpringBoot 静态资源问题

1 SpringBoot 如何处理静态资源问题 ,那些目录下的静态能够被访问

//静态资源处理方法
@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
		//是否在yaml 自定义了映射关系
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			//缓存的处理
			Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
			CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
			// 如果有访问/webjars 则映射到classpath:/META-INF/resources/webjars/
			if (!registry.hasMappingForPattern("/webjars/**")) {
				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
			// staticPathPattern=“/**” 访问/** 则映射到{ "classpath:/META-INF/resources/",
			"classpath:/resources/", "classpath:/static/", "classpath:/public/" };上面的位置
			
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
		}

小结

SpringBoot 访问静态资源的处理方式有三种

1 在yaml自定义静态资源映射处理

2 使用webjars /webjars/**

3 使用默认的静态资源映射处理

问/** 则映射到{ "classpath:/META-INF/resources/",
			"classpath:/resources/", "classpath:/static/", "classpath:/public/" };

测试

1 yaml 中自定静态资源映射处理

  • 1 创建一个SpringBoot项目
  • 2 修改配置文件 application.yaml
spring:
  resources:
    static-locations: ["classpath:/hello/"]


3 resource文件下添加文件 hello.html

在这里插入图片描述

4 访问http://localhost:8080/hello.html

在这里插入图片描述
访问http://localhost:8080/hi.html 结果

在这里插入图片描述

自定义静态资源映射路径后,默认的静态资源路径就会失效

2 默认静态资源映射路径

1 去掉上面的配置文件,配置的静态资源路径

2 访问访问http://localhost:8080/hi.html 结果

在这里插入图片描述

3 webjars

webjars 一种个webjars格式的web库

1官网https://www.webjars.org/

在这里插入图片描述

2 导入依赖

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

3 找到webjars

在这里插入图片描述
4访问里面的jquery.js文件

http://localhost:8080/webjars/jquery/3.5.1/jquery.js

结果

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值