Spring Boot Road Primer (5) --- Spring Boot in the process of static resources

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Geffin/article/details/99719377

In Spring Boot, the default has provided resources to deal with static, we can use WebMvcConfigurer be configured. Personal suggest that you use Spring Boot default configuration is better, if there are special circumstances, can be modified through configuration.

1 of static default mapping resources

Spring Boot default four directories can be accessed directly (in the directory under src / main / resources resource directory) under the file:

  1. classpath:/META-INF/resources
  2. classpath:/resources
  3. classpath:/static
  4. classpath:/public

Order catalog search order for static resources. If there is a static resource of the same name, in order to find the front of the subject.

requires attention:

  • The default configuration / ** mapped to the classpath: / META-INF / resources directory four
  • The default configuration / webjars / ** mapped to the classpath: / META-INF / resources / webjars /
    Here Insert Picture Description
    if we want to access img.jpg, should request address is http: // localhost: 8080 / img.jpg .

2 custom mapping of static resources

The above example of the resources we are being packaged in a jar package, but in fact, some dynamic resources are in need of maintenance, it is impossible on the package. For this resource freely specified directory, how to access?

Due to demand, we now need to add the / test / * to classpath: / test / * mapping
Here Insert Picture Description
Normally, directly enter the address http: // localhost: 8080 / test / img.jpg, simply can not access
Here Insert Picture Description

At this point, we need to customize the directory mapping by code that only needs to implement WebMvcConfigurer interfaces and methods to achieve addResourceHandlers. code show as below

@Configuration
public class WebConfig implements WebMvcConfigurer {

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

At this point directly enter the address http: // localhost: 8080 / test / img.jpg can visit
Directly enter the address http: // localhost: 8080 / test / img.jpg
note, our custom directory mapping will not affect the default mapping, which can be used simultaneously.

Override the automatic mapping

If we will / * Modify mapped to / test / *, the system configuration will be covered, we can repeatedly use addResourceLocations add directory, add a priority higher than after the first addition.

registry.addResourceHandler("/**").addResourceLocations("classpath:/test/").addResourceLocations("classpath:/static/");

Access test img.jpg the URL in the root directory of http: // localhost: 8080 / img.jpg (/ ** overrides the system default configuration)

Using an external directory

If we need to use absolute file path to the folder can be written as follows:

@Configuration
public class WebConfig implements WebMvcConfigurer {

	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/test/**").addResourceLocations("file:D:/test/");
    }
	
}

Note that when you specify the disk need to add file absolute path.

Profile configuration map static resources

In fact, we can configure the mapping application.properties, the code is as follows:

# 默认值为 /**
spring.mvc.static-path-pattern =
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ 
spring.resources.static-locations = 这里设置要指向的路径,多个使用英文逗号隔开,
  1. spring.mvc.static-path-pattern can be re-defined pattern, such as modifications to / test / **, the access to static and other img.jpg files in the directory should be localhost: 8080 / test / img.jpg, prior revised to localhost : 8080 / img.jpg. Note, spring.mvc.static-path-pattern can only define a
  2. Spring.resources.static-locations can be used to redefine the path pattern is directed.

3 WebJars

对于 web 开发而言,对静态资源版本管理是比较混乱的,以 Jquery,Bootstrap举例,可能各个前端框架所依赖的各个组件的版本都不尽相同,一不注意就可能引起不同版本的冲突问题。所以,是否有一种像后端管理 jar 包一样的解决方案呢?答案当然是有的,这就是我们要讲到的 WebJars。

WebJars 的工作原理

WebJars 是将 web 前端资源打成 jar 包文件。借助版本管理工具(例如 Maven )进行版本管理,保证这些 web 资源的版本唯一性,避免文件混乱、版本不一致等问题。

实际上 WebJars 就是将资源文件放到 classpath:/META-INF/resources/webjars/ 中,然后打包成 jar 发布到 maven 仓库中。

WebJars 的应用

在 Spring Boot 中默认将 /webjars/** 映射到 classpath:/META-INF/resources/webjars/ ,因此,在 JSP 页面中引入 jquery.js 的方法为:

<script type="text/javascript" src="${pageContext.request.contextPath }/webjars/jquery/2.1.4/jquery.js"></script>

同时需要在 pom.xml 文件中添加 jquery 的 WebJars 依赖

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

版本号统一管理

在实际开发中,也许我们会遇到升级版本号的情况,若有上千的页面,全部页面都按上面引入了 jquery.js ,那么如果有一天需要把版本号升级为 3.0.0,岂不累死?显然不能一个一个页面地去修改。

下面提供一个进行版本号统一管理的方法

在pom.xml 中添加依赖:

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

增加一个WebJarsController:

@Controller
public class WebJarsController {

     private final WebJarAssetLocator assetLocator = new WebJarAssetLocator();

    @ResponseBody
    @RequestMapping("/webjarslocator/{webjar}/**")
    public ResponseEntity<Object> locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
        try {
            String mvcPrefix = "/webjarslocator/" + webjar + "/"; // This prefix must match the mapping path!
            String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            String fullPath = assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
            return new ResponseEntity<>(new ClassPathResource(fullPath), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}

在页面中使用的方式:

<script type="text/javascript" src="${pageContext.request.contextPath }/webjarslocator/jquery/jquery.js"></script>

4 对静态资源的版本管理

当资源内容发生改变时,由于浏览器缓存,用户本地的资源还是旧资源,为了防止这种情况发生。我们可能会选择在资源文件后面加上参数“版本号”或其他方式。

使用版本号参数的例子:

<script type="text/javascript" src="${pageContext.request.contextPath }/js/common.js?v=1.0.1"></script>

当文件修改后,手工修改版本号来达到 URL 文件不被浏览器缓存的目的。同样也存在很多文件都需要修改的问题。

Spring provides a solution to this problem for the resource name md5 way method.

First, we need to modify the configuration file application.properties

spring.resources.chain.strategy.content.enabled = true
spring.resources.chain.strategy.content.paths = /**

All / ** static resource requests will be processed.

Then create ResourceUrlProviderController file:

//处理静态资源URL
@ControllerAdvice
public class ResourceUrlProviderController {

    @Autowired
    private ResourceUrlProvider resourceUrlProvider;

    @ModelAttribute("urls")
    public ResourceUrlProvider urls() {
        return this.resourceUrlProvider;
    }
}

That wording used in the page:

<script type="text/javascript" src="${pageContext.request.contextPath }${urls.getForLookupPath('/js/common.js') }"></script>

And when the page is accessed, HTML is actually generated code is:

<script type="text/javascript" src="/test/js/common-c6b7da8fffc9be141b48c073e39c7340.js"></script>

Note that when using the md5 file names the way, Spring is caching mechanism, that is, in the case of service does not restart, changes modify these resource files, md5 file name and its value does not change, only to restart the service again before access It will take effect.

5 summary of the Spring Boot in the process of static resources

  1. For third-party libraries, due to changes in project development frequency is small, even if the change is to modify the version number. So I recommend using WebJars way, and be used by the dynamic version number (webjars-locator way).
  2. For static resource files (write your own js, css files, etc.) stored in our own, due to the frequent changes, so I recommend use md5 resource file name to use.
  3. For the project source file, it is recommended into the classpath: Under / static directory.

Reference: the Spring static resources to deal with the Boot

Guess you like

Origin blog.csdn.net/Geffin/article/details/99719377