spring boot ---静态资源

在 spring  mvc  中,对于静态资源也需要手动的配置,但是在spring boot  中是不需要手动配置的,提供了自动化配置,可以简化静态资源的过滤配置

spring  boot 中 对于 spring  mvc 的自动化配置都在WebMvcAutoConfiguration 类中,在webMvcAutoConfiguration 类中有一个静态内部类WebMvcConfigurationAdapter ,在该类中有一个方法, addResourceHandlers,在该方法中有一句

this.resourceProperties.getStaticLocations() ,获取的是
public String[] getStaticLocations() {
		return this.staticLocations;
	}

而该返回的数据是

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

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

可以看到在spring  mvc 中设置了路径

但是在    getResourceLocations  该方法中,获取了

	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;
		}

中的  SERVLET_LOCATIONS  静态变量

	private static final String[] SERVLET_LOCATIONS = { "/" };

表示 spring boot  会过滤掉所有的 静态资源

在使用 idea 创建  spring boot 项目的时候,会默认创建出  static 目录,可用于存放静态资源

在使用的时候,也可以自定义存放的路径

spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations= classpath:/static/

也可以使用 Bean 来创建  文件存放的路径,, 在使用bean 的时候,需要实现   WebMvcConfigurer类

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/*").addResourceLocations("classpath:/static/");
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值