[SpringBoot] Static resource rule configuration

My springboot version is

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>

1. XML configuration method

1.1. /** and /* difference

  • ? Matches any single character
  • * Match 0 or any number of characters
  • ** Match 0 or more directories

1.2.spring.mvc.static-path-pattern

The meaning of spring.mvc.static-path-pattern is what path we should use to access static resources 默认配置为 /*. In other words 只有静态资源满足什么样的匹配条件, Spring Boot will only process static resource requests. Take the official configuration as an example:

#这表示只有静态资源的访问路径为/statics/**时,才会当作静态资源处理请求
spring.mvc.static-path-pattern=/resources/**,
  • Assuming that the default port is http://localhost:8080/resources/jquery.jsused, SpringBoot will process the request only when the request address is similar . The processing method is to find the local file according to the file name after the pattern is matched.

So where should I look for local files?

  • Then you need to rely on spring.resources.static-locationsit.

1.3.spring.resources.static-locations

spring.resources.static-locations is used to tell Spring Boot 在去哪里找静态资源文件that multiple configurations can be configured, separated by commas, 配置的先后顺序and files are searched in turn

默认的官方配置如下

spring.resources.static-locations=classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources
  • Continuing to take the above request address as an example, http://localhost:8080/resources/jquery.jsit will check 依次查找whether there is a “jquery.js”file in the above four paths . If it is found, it will return this file, otherwise it will return 404an error.

How to access the Windows local path

# 反斜线,windows目录分隔符,前一个\是转义字符,后一个\是目录分隔符。
spring.resources.static-locations=file:\\D:\\dist\\
# 或spring.resources.static-locations=file:///D:/dist/

Equivalent to Spring's XML configuration

<mvc:resources mapping="/image/**" location="file:D:/temp/image/">
    <mvc:cache-control max-age="3600" cache-public="true"/>
</mvc:resources>

2. Code configuration method

We can also @Configuration配置类ways to achieve WebMvcConfigurer接口, 重写addResourceHandlers方法from the definition of static resource mapping directory, but会覆盖默认的静态资源配置

Spring5 is deprecated WebMvcConfigurerAdapter类and used insteadWebMvcConfigurer接口

  • addResourceHandler: Specify the access path exposed by the mapping
  • addResourceLocations: Specify the directory where the file is placed

Springboot 1.x configuration-inherit WebMvcConfigurerAdapter class

@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    
    
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
            
    	/**
         * 资源映射路径
         * addResourceHandler:访问映射路径
         * addResourceLocations:资源绝对路径
         */
        registry.addResourceHandler("/image/**")
        		.addResourceLocations("file:D:/temp/image/")
          		.setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
    }
}

Springboot 2.x configuration-implement WebMvcConfigurer interface

@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    
    
    /**
      * 资源映射路径
      * addResourceHandler:访问映射路径
      * addResourceLocations:资源绝对路径
      */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
      
        registry.addResourceHandler("/image/**")
        		.addResourceLocations("file:D:/temp/image/")
          		.setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
    }
}

Equivalent to Spring's XML configuration

<mvc:resources mapping="/image/**" location="file:D:/temp/image/">
    <mvc:cache-control max-age="3600" cache-public="true"/>
</mvc:resources>

How to access files under classPath

 registry.addResourceHandler("/image/**").addResourceLocations("classpath:/temp-rainy/");

Three. WebJars way

  • WebJars is to package the front-end resources (css, js, image, html, etc.) into a jar, and then use a JVM-based package manager (such as Maven, Gradle, etc.) to manage the front-end dependencies.

  • Official website address : https://www.webjars.org/

Open the website and you can see that there are many front-end js components introduced by maven below
Insert picture description here

  • In SpringBoot, static resources can also be accessed through WebJars. By default it will be /webjars/**mapped toclasspath:/META-INF/resources/webjars/

    **/webjars/****: Means all the files in the /webjars/ directory and all the files in the jar package in the directory.

    • By default, we need to access the resources in WebJars, and we need to put the jar package classpath:/META-INF/resources/webjars/目录in it.

SpringBoot support WebJar of
view WebMWebMVCAutoConfiguration源码is as follows:
Insert picture description here
which 绿色方框代码explain how to WebJars SpringBoot be supported:所有 /webjars/**的请求都去 classpath:/META-INF/resources/webjars/ 找资源

Page usage

  • In the pom.xmlintroduction jquery in WebJars, the default will be placed in classpath:/META-INF/resources/webjars/the directory
 <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>jquery</artifactId>
      <version>2.1.1</version>
  </dependency>
  • Introduce jquery in the front-end webjars.html page
<script src="/webjars/jquery/2.1.1/jquery.js"></script>
  • Visit the specified page
    Insert picture description here

Unified management of WebJar version number

pom.xml add dependencies as follows

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator</artifactId>
            <version>0.40</version>
        </dependency>

At this point, (带版本号和不带版本号)all the requests used can get the resources correctly!
Insert picture description here
Annotation webjars-locatordependency discovery is no longer possibleInsert picture description here

Four. SpringBoot static resource mapping rules

The related configuration of static resources and WebJar in SpringBoot is WebMvcAutoConfiguration类in.

  • Through source code analysis: all /webjars/**的请求go classpath:/META-INF/resources/webjars/look for resources.
    Insert picture description here

Pass 源码分析: SpringBoot is ResourceProperties类to set parameters related to static resources, such as cache time settings.

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
    
    }

Insert picture description here
Access /**to any resources of the current project will first go to these static resource directories to find:

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

Pass 源码分析: 欢迎页index.htmlthrough search 所有静态资源目录下的index.html页面, according 目录优先级to return

Insert picture description here

Five. How does Spring access static resources such as Webapp

When we created the JavaWeb project before, we directly put static resources, such as html files, pictures, etc., in the src/main/webappdirectory, and these static resources can be directly accessed in the browser. So how to deal with these resource files for springboot?

The default scanning path of springboot for static resources is:

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

By default, springBoot does not have a webapp directory. You need to create it yourself and place it in a unified directory with java and resource, as follows:
Insert picture description here

Mainly configure two paths
Insert picture description here

Pom.xml configures the packaging path and compiles the corresponding resources to the target directory

        <resources>
            <!--打包webapp目录下的所有内容到classpath:META-INF/resources-->
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
            <!--打包resources目录下的所有内容到classpath:/-->
            <resource>
                <directory>src/main/resources/</directory>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
        </resources>

Compiled directory structure
Insert picture description here

Request: http://localhost:8080/img2/4.jpg
Insert picture description here
Request: http://localhost:8080/img2/5.jpg
Insert picture description here
Request: http://localhost:8080/img2/6.jpg
Insert picture description here

Insert picture description here


As can be seen from source 静态资源文件夹to 默认配置:
Insert picture description here

spring.resources.static-locations is
used to tell Spring Boot where to find static resource files. This is a list configuration. The file search will depend on the order of configuration. Similar to the location tag in springmvc, the default official configuration is as follows:

  • spring.resources.static-locations=
    classpath:/META-INF/resources
    classpath:/resources,
    classpath:/public,
    classpath:/static,

Six. SpringBoot integration shiro static resource file is intercepted solution

Directory Structure
Insert picture description here

6.1. The default spring.mvc.static-path-pattern configuration

The spring.mvc.static-path-pattern is not in the springBoot configuration. That is, the static resource matching condition,, 默认配置为 /*any static resource request will go to the following directory to find

classpath:/META-INF/resources
classpath:/resources
classpath:/public
classpath:/static
  1. shirFilter new configuration-access to static resources /css, /js, /image request path release
@Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
    
    
        System.out.println("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");

        //拦截器.
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        //自定义拦截器
        Map<String, Filter> customisedFilter = new HashMap<>();
        customisedFilter.put("url", getUrlPathMatchingFilter());
        //配置映射关系
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/index", "anon");
        //springboot默认把所有的静态资源都映射到static目录了
        //也就是说本来的http://localhost:8888/static/css/main.css 需要改成
        //http://localhost:8888/css/main.css才可以访问
        filterChainDefinitionMap.put("/image/**", "anon");//img
        filterChainDefinitionMap.put("/css/**", "anon");//css
        filterChainDefinitionMap.put("/js/**", "anon");//js
        filterChainDefinitionMap.put("/config/**", "anon");
        filterChainDefinitionMap.put("/404", "anon");
        filterChainDefinitionMap.put("/500", "anon");
        filterChainDefinitionMap.put("/doLogout", "logout");
        filterChainDefinitionMap.put("/**", "url");
        shiroFilterFactoryBean.setFilters(customisedFilter);
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }
  1. Direct browser request is accessible
    Insert picture description here

  2. href=/css/style.css specified in jsp
    Insert picture description here

6.2. Spring.mvc.static-path-pattern is configured

  1. Global configuration file application.properties new configuration
# 这表示只有静态资源的访问路径为/statics/**时,才会当作静态资源处理请求
spring.mvc.static-path-pattern=/statics/**
  1. shirFilter new configuration- /staticsrelease the request path
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
    
    
        System.out.println("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");

        //拦截器.
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        //自定义拦截器
        Map<String, Filter> customisedFilter = new HashMap<>();
        customisedFilter.put("url", getUrlPathMatchingFilter());
        //配置映射关系
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/index", "anon");
        //#核心配置文件配置=>静态资源位置 spring.mvc.static-path-pattern=/statics/**
        //访问时 http://localhost:8080/statics/css/style.css
        filterChainDefinitionMap.put("/statics/**", "anon");
        filterChainDefinitionMap.put("/config/**", "anon");
        filterChainDefinitionMap.put("/404", "anon");
        filterChainDefinitionMap.put("/500", "anon");
        filterChainDefinitionMap.put("/doLogout", "logout");
        filterChainDefinitionMap.put("/**", "url");
        shiroFilterFactoryBean.setFilters(customisedFilter);
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }
  1. Browser requestInsert picture description here
  2. href= specified in jsp/statics/css/style.cssInsert picture description here

Analysis of Spring Boot static resource access principle

Guess you like

Origin blog.csdn.net/qq877728715/article/details/110422199