Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the mapping rules for SpringBoot+Thymeleaf static resources

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the mapping rules of SpringBoot+Thymeleaf static resources". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Mapping rules of static Resources in Spring Boot

Static resources in Spring Boot mainly include two parts: 1, webjars resources, 2, custom other html, css, js resources, the following describes the mapping rules of the two resources.

1), webjars resources

WebJars is to make web front-end resources (js,css, etc.) into jar package files, and then use Maven tools to manage web front-end resources in the form of jar packages to ensure the version uniqueness of these Web resources. The xml code corresponding to webjars import can be copied on the official website of webjars.

Https://www.webjars.org/

The mapping rules for SpringBoot to webjars resources are in the WebMvcAutoConfiguration.java package. The screenshot of the code is shown below:

Public void addResourceHandlers (ResourceHandlerRegistry registry) {if (! this.resourceProperties.isAddMappings ()) {logger.debug ("Default resource handling disabled");} else {Integer cachePeriod = this.resourceProperties.getCachePeriod () If (! registry.hasMappingForPattern ("/ webjars/**")) {this.customizeResourceHandlerRegistration (registry.addResourceHandler (new String [] {"/ webjars/**"}) .addResourceLocations (new String [] {"classpath:/META-INF/resources/webjars/"}) .setCachePeriod (cachePeriod));} String staticPathPattern = this.mvcProperties.getStaticPathPattern () If (! registry.hasMappingForPattern (staticPathPattern)) {this.customizeResourceHandlerRegistration (registry.addResourceHandler (new String [] {staticPathPattern}) .addResourceLocations (this.resourceProperties.getStaticLocations ()) .setCachePeriod (cachePeriod));}}

As you can see from the above code, all resources under webjars under the root directory of the project are mapped to the classpath:/META-INF/resources/webjars/ folder, where classpath is the root of the resources resource folder or class.

The static resources (js, css) of the webjars package imported by maven are automatically placed under the classpath:/META-INF/resources/webjars/ folder, as shown below:

From the figure, you can see that the upper directory of the static resource file in dist is resources/webjars/**

Therefore, when referencing the front end (using the thymeleaf template engine here), you can reference it in the following way: you can write directly from the webjars directory. The actual effect of the above static resource mapping configuration is to prefix the resource path written by yourself with the classpath:/META-INF/resources prefix.

2) static resource files added by yourself

Spring Boot's mapping rules for the static resource files that he added are still in the WebMvcAutoConfiguration.java file, and the actual configuration is the CLASSPATH_RESOURCE_LOCATIONS variable in the ResourcesProperties.java resource file.

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

The above configuration effect is that when all static resources are accessed directly to the / webjars/** path, any string in the above configuration will be added to the access path until the corresponding static resources are found under the corresponding file. Therefore, when writing SpringBoot applications, you can generally place static resources under the static or public folder under the resources resource directory, as shown in the following figure:

As shown in the figure above, if you want to access layui.js, you can reference static resources as follows:

After the above reference, SpringBoot looks for layui/layui.js under the path specified by the CLASSPATH_RESOURCE_LOCATIONS variable until the file location is found.

The value of CLASSPATH_RESOURCE_LOCATIONS can be modified directly in the SpringBoot configuration file application.properties or yml file.

Mapping rules for Thymeleaf template engine

The mapping rules for the Thymeleaf template engine are as follows

@ ConfigurationProperties (prefix = "spring.thymeleaf") public class ThymeleafProperties {private static final Charset DEFAULT_ENCODING = Charset.forName ("UTF-8"); private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf ("text/html"); public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"

The actual effect of the above code is that using the template engine will prefix the request path string with classpath:/templates/, followed by html to make a resource request. Therefore, the html interface that needs to be rendered by the template engine is generally placed under the templates folder under the resources path, and there is no need to add the html suffix to the requested path string.

A simple example is as follows:

@ RequestMapping ("/ success") public String success (Map map) {/ / map=new HashMap (); this place can no longer new map.put ("hello", "hello"); return "success";}

The above code returns the rendered html interface, which is the success.html interface located under the resources/templates folder. The default settings page can be modified directly in the configuration file through the spring.thymeleaf option.

SpringBoot mapping rules for static resources source code learning notes

WebMvcAuotConfiguration:

@ Override public void addResourceHandlers (ResourceHandlerRegistry registry) {if (! this.resourceProperties.isAddMappings ()) {logger.debug ("Default resource handling disabled"); return;} Duration cachePeriod = this.resourceProperties.getCache () .getPeriod () CacheControl cacheControl = this.resourceProperties.getCache () .getCachecontrol () .toHttpCacheControl (); / / all / webjars/**, go to classpath:/META-INF/resources/webjars/ for resources / / webjars: introduce static resources in the form of jar packages If (! registry.hasMappingForPattern ("/ webjars/**")) {customizeResourceHandlerRegistration (registry.addResourceHandler ("/ webjars/**") .addResourceLocations ("classpath:/META-INF/resources/webjars/") .setCachePeriod (getSeconds (cachePeriod)) .setCacheControl (cacheControl)) } / / "/ * *" access any resources of the current project and go to (the folder of static resources) to find the mapping String staticPathPattern = this.mvcProperties.getStaticPathPattern () / / static resource folder mapping if (! registry.hasMappingForPattern (staticPathPattern)) {customizeResourceHandlerRegistration (registry.addResourceHandler (staticPathPattern) .addResourceLocations (getResourceLocations (this.resourceProperties.getStaticLocations () .setCachePeriod (getSeconds (cachePeriod)) .setCacheControl (cacheControl)) }}

ResourceProperties

Source code: / / you can set parameters related to static resources, cache time, etc. @ ConfigurationProperties (prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties {

GetStaticPathPattern ():

Source code: private String staticPathPattern = "/ * *"; public String getStaticPathPattern () {return this.staticPathPattern;}

GetStaticLocations ()

Source code: private static final String [] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"}; private String [] staticLocations = CLASSPATH_RESOURCE_LOCATIONS Public String [] getStaticLocations () {return this.staticLocations;}

/ / configure Welcome Page Mapping

@ Bean public WelcomePageHandlerMapping welcomePageHandlerMapping (ResourceProperties resourceProperties) {/ / all index.html pages under the static resource folder; mapped by "/ *" Return new WelcomePageHandlerMapping (resourceProperties.getWelcomePage (), this.mvcProperties.getStaticPathPattern ());} private Optional getWelcomePage () {String [] locations = getResourceLocations (this.resourceProperties.getStaticLocations ()) Return Arrays.stream (locations) .map (this::getIndexHtml) .filter (this::isReadable). FindFirst ();} private Resource getIndexHtml (String location) {return this.resourceLoader.getResource (location + "index.html");}

GetStaticPathPattern ()

Source code: private String staticPathPattern = "/ * *"; public String getStaticPathPattern () {return this.staticPathPattern;}

/ / configure your favorite icons

@ Configuration @ ConditionalOnProperty (value = "spring.mvc.favicon.enabled", matchIfMissing = true) public static class FaviconConfiguration implements ResourceLoaderAware {private final ResourceProperties resourceProperties; private ResourceLoader resourceLoader; public FaviconConfiguration (ResourceProperties resourceProperties) {this.resourceProperties = resourceProperties;} @ Override public void setResourceLoader (ResourceLoader resourceLoader) {this.resourceLoader = resourceLoader;} @ Bean public SimpleUrlHandlerMapping faviconHandlerMapping () {SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping (); mapping.setOrder (Ordered.HIGHEST_PRECEDENCE + 1) / / all * * / favicon.ico look for mapping.setUrlMap (Collections.singletonMap ("* * / favicon.ico", faviconRequestHandler ()) under static resource files; return mapping;} @ Bean public ResourceHttpRequestHandler faviconRequestHandler () {ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler (); requestHandler.setLocations (resolveFaviconLocations ()); return requestHandler;} private List resolveFaviconLocations () {String [] staticLocations = getResourceLocations (this.resourceProperties.getStaticLocations ()) List locations = new ArrayList (staticLocations.length + 1); Arrays.stream (staticLocations) .map (this.resourceLoader::getResource) .forEach (locations::add); locations.add (new ClassPathResource ("/")); return Collections.unmodifiableList (locations);}}

Thymeleaf usage

Source code: / / as long as we put the HTML page on classpath:/templates/,thymeleaf, it can be automatically rendered; @ ConfigurationProperties (prefix = "spring.thymeleaf") public class ThymeleafProperties {private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";} "what are the mapping rules for SpringBoot+Thymeleaf static resources" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report