Home Java javaTutorial How to explore the mapping rules of static resources through source code

How to explore the mapping rules of static resources through source code

May 06, 2021 am 09:36 AM
spring boot

本篇文章给大家介绍一下通过源码探究静态资源映射规则的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

How to explore the mapping rules of static resources through source code

Spring Boot——通过源码探究静态资源的映射规则

我们开发一个Spring Boot项目,肯定要导入许多的静态资源,比如css,js等文件

如果我们是一个web应用,我们的main下会有一个webapp,我们以前都是将所有的页面导在这里面的,对吧!但是我们现在的pom呢,打包方式是为jar的方式,那么这种方式SpringBoot能不能来给我们写页面呢?当然是可以的,但是SpringBoot对于静态资源放置的位置,是有规定的!

静态资源映射规则

第一种映射规则

SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置类里面;

WebMvcAutoConfigurationAdapter 中有很多配置方法;其中就有一个添加资源处理方法:addResourceHandlers (),源码如下。

@Override
		protected void addResourceHandlers(ResourceHandlerRegistry registry) {
			super.addResourceHandlers(registry);
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			ServletContext servletContext = getServletContext();
			addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
			addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
				registration.addResourceLocations(this.resourceProperties.getStaticLocations());
				if (servletContext != null) {
					registration.addResourceLocations(new ServletContextResource(servletContext, SERVLET_LOCATION));
				}
			});
		}
Copy after login

WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件,以对资源进行统一依赖管理。WebJars的jar包部署在Maven中央仓库上。

我们可以到webjars官网上找到自己需要的资源,在自己的工程中添加入maven依赖,即可直接使用这些资源了。

比如,我们要导入jquery资源

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.6.0</version></dependency>
Copy after login

导入后我们可以通过资源路径找到资源的存放位置并访问,我们在webjars网站导入的资源都符合下图的结构

How to explore the mapping rules of static resources through source code

通过路径访问,成功访问到静态资源!

How to explore the mapping rules of static resources through source code

第二种映射规则

下面我们继续分析源码

How to explore the mapping rules of static resources through source code

getStaticPathpattern():获得静态路径模式,点进去看一下源码

public String getStaticPathPattern() {
		return this.staticPathPattern;
	}
Copy after login

再看一下staticPathPattern的源码

How to explore the mapping rules of static resources through source code

/**就是当前目录下的所有静态资源都能识别,但是当前目录下具体指的又是什么呢?我们点开resourceProperties的源码便可看出来。源码如下:

How to explore the mapping rules of static resources through source code

上面源码很清楚的给出了我们四个静态资源路径,所以只要是这四个目录下的静态资源,都可以直接获取。

我们来测试一下,先补齐上面的目录,然后再resource目录放一个js资源

How to explore the mapping rules of static resources through source code

启动springboot应用测试:成功访问到静态资源!

How to explore the mapping rules of static resources through source code

以下四个目录存放的静态资源可以被我们识别:

"classpath:/META-INF/resources/""classpath:/resources/""classpath:/static/""classpath:/public/"
Copy after login

注意:

  • 第一个目录的访问路径为localhost:8080/webjars/资源目录结构,后面三个访问路径为localhost:8080/资源名

  • 第二种映射规则的优先级为:resources>static(默认)>public

自定义静态资源路径

我们可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置;

spring.resources.static-locations=classpath:/coding/,classpath:/cheng/
Copy after login

但是通过下面源码我们可以看出,如果自定义了资源路径,那么上面默认的四个路径就失效了,所以最好不要自定义路径,使用springboot帮我们自动配置好的就行。

if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
Copy after login

相关免费学习推荐:java基础教程

The above is the detailed content of How to explore the mapping rules of static resources through source code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Spring Boot+MyBatis+Atomikos+MySQL (with source code) Spring Boot+MyBatis+Atomikos+MySQL (with source code) Aug 15, 2023 pm 04:12 PM

In actual projects, we try to avoid distributed transactions. However, sometimes it is really necessary to do some service splitting, which will lead to distributed transaction problems. At the same time, distributed transactions are also asked in the market during interviews. You can practice with this case, and you can talk about 123 in the interview.

How to use Spring Boot to build big data processing applications How to use Spring Boot to build big data processing applications Jun 23, 2023 am 09:07 AM

With the advent of the big data era, more and more companies are beginning to understand and recognize the value of big data and apply it to business. The problem that comes with it is how to handle this large flow of data. In this case, big data processing applications have become something that every enterprise must consider. For developers, how to use SpringBoot to build an efficient big data processing application is also a very important issue. SpringBoot is a very popular Java framework that allows

Achieve multi-language support and international applications through Spring Boot Achieve multi-language support and international applications through Spring Boot Jun 23, 2023 am 09:09 AM

With the development of globalization, more and more websites and applications need to provide multi-language support and internationalization functions. For developers, implementing these functions is not an easy task because it requires consideration of many aspects, such as language translation, date, time and currency formats, etc. However, using the SpringBoot framework, we can easily implement multi-language support and international applications. First, let us understand the LocaleResolver interface provided by SpringBoot. Loc

How to use Spring Boot to build blockchain applications and smart contracts How to use Spring Boot to build blockchain applications and smart contracts Jun 22, 2023 am 09:33 AM

With the rise of digital currencies such as Bitcoin, blockchain technology has gradually become a hot topic. Smart contracts can be regarded as an important part of blockchain technology. SpringBoot, as a popular Java back-end development framework, can also be used to build blockchain applications and smart contracts. This article will introduce how to use SpringBoot to build applications and smart contracts based on blockchain technology. 1. SpringBoot and blockchain First, we need to understand some basic concepts related to blockchain. Blockchain

Implement ORM mapping based on Spring Boot and MyBatis Plus Implement ORM mapping based on Spring Boot and MyBatis Plus Jun 22, 2023 pm 09:27 PM

In the development process of Java web applications, ORM (Object-RelationalMapping) mapping technology is used to map relational data in the database to Java objects, making it convenient for developers to access and operate data. SpringBoot, as one of the most popular Java web development frameworks, has provided a way to integrate MyBatis, and MyBatisPlus is an ORM framework extended on the basis of MyBatis.

Integration and use of Spring Boot and NoSQL database Integration and use of Spring Boot and NoSQL database Jun 22, 2023 pm 10:34 PM

With the development of the Internet, big data analysis and real-time information processing have become an important need for enterprises. In order to meet such needs, traditional relational databases no longer meet the needs of business and technology development. Instead, using NoSQL databases has become an important option. In this article, we will discuss the use of SpringBoot integrated with NoSQL databases to enable the development and deployment of modern applications. What is a NoSQL database? NoSQL is notonlySQL

Building an ESB system using Spring Boot and Apache ServiceMix Building an ESB system using Spring Boot and Apache ServiceMix Jun 22, 2023 pm 12:30 PM

As modern businesses rely more and more on a variety of disparate applications and systems, enterprise integration becomes even more important. Enterprise Service Bus (ESB) is an integration architecture model that connects different systems and applications together to provide common data exchange and message routing services to achieve enterprise-level application integration. Using SpringBoot and ApacheServiceMix, we can easily build an ESB system. This article will introduce how to implement it. SpringBoot and A

Distributed data caching and storage system based on Spring Boot Distributed data caching and storage system based on Spring Boot Jun 22, 2023 am 09:48 AM

With the continuous development and popularization of the Internet, the demand for data processing and storage is also increasing. How to process and store data efficiently and reliably has become a hot topic among industry and researchers. The distributed data caching and storage system based on SpringBoot is a solution that has attracted much attention in recent years. What is a distributed data caching and storage system? Distributed data caching and storage system refers to the distributed storage of data through multiple nodes (servers), which improves the security and reliability of data, and can also improve data processing.

See all articles