[springboot web series] static resource configuration and reading

Time:2021-7-25

[springboot web series] static resource configuration and reading

[web series] static resource configuration and reading

In addition to our common JSON strings, spring web projects can also directly return static resources (of course, it is not very common in the case of front-end and back-end separation). In some simple web projects, the front-end and back-end may be wrapped by one person, and the front-end pages and JS / CSS files are also directly placed in spring projects, Do you know where to put these static resource files

<!– more –>

1. Default configuration

1. Configuration

Static resource path, springboot default slave attributespring.resources.static-locationsGet in

The default value can be fromorg.springframework.boot.autoconfigure.web.ResourceProperties#CLASSPATH_RESOURCE_LOCATIONSobtain

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;

Note the above default values. There are four by default, and the priority is from high to low

  • /META-INF/resources/
  • /resources/
  • /static/
  • /public/

2. Example demonstration

There are four default static resource paths, so we need to access the static resources in the four paths in turn to see if they are accessed normally; The second is to determine whether the priority is consistent with the above

First, create a springboot web project. The process of creating the project is not much to say. The POM mainly ensures the following dependencies (the version used in this article is:2.2.1.RELEASE)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

In the resource folderresourcesNext, create four directories and add HTML files to test whether the corresponding resource files can be accessed (mainly focusing on the red files in the figure below)

[springboot web series] static resource configuration and reading

a. META-INF/resources

Static file m.html

<html>
<title>META-INF/resource/m.html</title>
<body>
Jar package, m.html in meta-inf / resources directory
</body>
</html>

Complete the corresponding rest interface

@GetMapping(path = "m")
public String m() {
    return "m.html";
}

[springboot web series] static resource configuration and reading

b. resources

Static file R.html

<html>
<title>resources/r.html</title>
<body>
Jar package, R.html in the resources directory
</body>
</html>

Corresponding rest interface

@GetMapping(path = "r")
public String r() {
    return "r.html";
}

[springboot web series] static resource configuration and reading

c. static

Static file s.html

<html>
<title>static/s.html</title>
<body>
In the jar package, s.html is in the static directory
</body>
</html>

Corresponding rest interface

@GetMapping(path = "s")
public String s() {
    return "s.html";
}

[springboot web series] static resource configuration and reading

d. public

Static file p.html

<html>
<title>public/p.html</title>
<body>
In the jar package, p.html in the public directory
</body>
</html>

Corresponding rest interface

@GetMapping(path = "p")
public String p() {
    return "p.html";
}

[springboot web series] static resource configuration and reading

e. Priority test

For the priority test case, the main idea is to put static resources with the same file name under the four different folders above, and then determine the corresponding priority according to the specific return during access. The relevant code can be obtained from the source code at the end of the article, which will not be repeated here

2. Custom resource path

Generally speaking, it is enough for our static resources to be placed under the four default folders above, but there will always be special cases. What should we do if the resource files are placed in other directories?

1. Modify the configuration file

The first method is relatively simple and practical. Modify the abovespring.resources.static-locationsConfigure and add a custom resource directory on, as shown inapplication.ymlIn, specify the configuration

spring:
  resources:
    static-locations: classpath:/out/,classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

It is specified above that you can scan/outThe static resource file in the directory, and its priority is the highest (in the above configuration order, the priority is from left to right)

Example demonstration

In the resource directory, create a new file/out/index.html

[springboot web series] static resource configuration and reading

Please note that the other four resource directories also existindex.htmlThis file (according to the priority description above, the returned should be/out/index.html

@GetMapping(path = "index")
public String index() {
    return "index.html";
}

[springboot web series] static resource configuration and reading

2. Webmvcconfigurer add resource mapping

In addition to the above configuration specification, another common usage pose is to use the configuration classWebMvcConfigurerTo manually add the resource mapping relationship. For simplicity, let’s directly implement the startup classWebMvcConfigureInterface

@SpringBootApplication
public class Application implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //Please note the following mapping: map the resources under the resource path / TS to the access path whose root directory is / ts
        //For example, ts.html under ts, the corresponding access path is / TS / ts
        registry.addResourceHandler("/ts/**").addResourceLocations("classpath:/ts/");
    }


    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

According to the above configuration, it means that the resource ts.html in the / TS directory is mapped to / TS / TS, and the direct access to / TS will report 404 (this logic may be a bit convoluted, so you need to think carefully)

@GetMapping(path = "ts")
public String ts() {
    return "ts.html";
}

@GetMapping(path = "ts/ts")
public String ts2() {
    return "ts.html";
}

[springboot web series] static resource configuration and reading

3. Jar package resource access

The static resource access described above is mainly the resource access in the current package. If our static resources are provided by a third-party jar package (such as the famous swagger UI), is there any difference in the use posture?

1. Classpath and classpath*

Used beforeSpringMVC3+/4When I was young,classpath:/META-INF/resources/Indicates that only the in the current package will be scanned/META-INF/resources/Path, andclasspath*:/META-INF/resources/The current + third-party jar package will be scanned/META-INF/resources/route

So inSpringBoot2.2.1-RELEASEDoes this need to be done in the release( The answer is no, let’s see the following examples)

2. Examples

Create a new project that only provides basic HTML static resources. The basic structure of the project is as follows (the specific HTML content will not be pasted. Wall crack suggests that interested partners directly look at the source code for more elegant reading effect)

[springboot web series] static resource configuration and reading

Then, add dependencies in the common projects above

<dependency>
    <groupId>com.git.hui.boot</groupId>
    <artifactId>204-web-static-resources-ui</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

Add the access endpoint of the corresponding resource

@GetMapping(path = "ui")
public String ui() {
    return "ui.html";
}

@GetMapping(path = "out")
public String out() {
    return "out.html";
}

//The meta-inf / resources priority of the third-party jar package is also higher than the / static priority of the current package

@GetMapping(path = "s2")
public String s2() {
    return "s2.html";
}

Please note that we have not modified the previous one at this timespring.resources.static-locationsConfigured

[springboot web series] static resource configuration and reading

The above access results show that there is no difference between accessing the static resources in the third-party jar package and the static resource configuration of the current package

  • Under the same resource path, the resource priority of the current package is higher than the static resources in the jar package
  • In the default configuration, it is stored in the third-party jar packageMETA-INF/resourcesThe static resources in the current package have higher priority than those in the current package/resources, /static, /public

4. Other

0. Project

  • Project: https://github.com/liuyueyi/spring-boot-demo
  • Source code: https://github.com/liuyueyi/spring-boot-demo/spring-boot/204-web-static-resources
  • https://github.com/liuyueyi/spring-boot-demo/spring-boot/204-web-static-resources-ui

1. A gray blog

The above contents are only the words of one family. Due to limited personal ability, it is inevitable that there are omissions and mistakes. If you find a bug or have better suggestions, you are welcome to criticize and correct and be grateful

The following is a gray personal blog, which records all blog posts in study and work. Welcome to visit

  • A personal blog https://blog.hhui.top
  • A gray blog spring special blog http://spring.hhui.top

[springboot web series] static resource configuration and reading