SpringMvc configures static resource access path

1. Overall process

1. 写一个配置类继承WebMvcConfigurationSupport
2. 利用 registry.addResourceHandler("访问路径").addResourceLocations("分配资源目录");
   将想要映射的访问路径令其去访问分配的资源路径当中

  Core: The path in the previously matched (**) will be used as a relative path, dynamically added to the subsequent directory path, and the two paths will be connected to dynamically access resources
  The preceding and following access paths and the writing of the resource directory must be able to match and connect. The previous matching path will be used as a relative path to search in the resource directory (very critical)

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    
    
	@Override
	protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
		registry.addResourceHandler("/Test/**").addResourceLocations("classpath:/D1/"+"");
	}
}

2. registry.addResourceHandler()

2.1 Function analysis

 a. This function allows adding a resource handler (ResourceHandlerRegistration) to the specified matching pathPatter. The resource handler will be called for the resource path matching the specified path.
 b. Allowed Add multiple matching paths, only one is legally satisfied

public ResourceHandlerRegistration addResourceHandler(String... pathPatterns) {
    
    
	ResourceHandlerRegistration registration = new ResourceHandlerRegistration(pathPatterns);
	this.registrations.add(registration);
	return registration;
}

2.2 Result demonstration

 Key a: For path resources, only one of them needs to be matched for access.
 Key b: For paths that may contain paths, the system will automatically prioritize the more accurate path first. match
Insert image description here

3. ResourceHandlerRegistration.addResourceLocations()

3.1 Function analysis

 a. For successfully matched paths, add one or more resource locations (valid directories) from which to serve static content. Match in the order written
 b. Allow adding multiple resource paths and matching one by one

	public ResourceHandlerRegistration addResourceLocations(String... locations) {
    
    
		this.locationValues.addAll(Arrays.asList(locations));
		return this;
	}

3.2 Result demonstration

 Key a: Allow matching multiple paths in resource directories
Insert image description here

Insert image description here
 Key b: Resource directories will be matched in order (this is different from the above path matching, which does not affect the result. The matching of this resource directory is related to the writing order, and the resource directory written earlier will be matched first)
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_51566349/article/details/131816800