SpringBoot_静态资源映射/自动配置

开发步骤:

使用IDEA进行SpringBoot开发:

1,创建 SpringBoot 应用,选中需要的模块;
2,SpringBoot 已经默认将选中的模块场景配置好了,若需要修改配置,只需要在配置文件中指定配置即可;
3,编写业务代码;


SpringBoot对静态资源的映射规则:

在 SpringBoot 中,SpringMVC 的相关配置都在 WebMvcAutoConfiguration 文件中,可反编译查看;

jar包资源 :

/webjars/ ** :以jar包的方式引入静态资源,可以在 classpath:/META-INF/resources/webjars/ 找到对应的资源;


public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
                CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }
                

只需要在 pom.xml 引入对应的依赖:

<!‐‐引入 jquery‐webjar ‐‐>在访问的时候只需要写 webjars 下面资源的名称即可
	<dependency>
		<groupId>org.webjars</groupId>
		<artifactId>jquery</artifactId>
		<version>3.3.1</version>
	</dependency>

js,css,image 等文件:

"/ ** " :访问当前项目的静态资源文件夹下的 js,css,image 等文件:

静态资源的文件夹 : “classpath:/META‐INF/resources/”“classpath:/resources/”“classpath:/static/”“classpath:/public/”"/" (当前项目的根路径)

请求进来,先去找Controller层看能不能处理,不能处理的所有请求又都交给静态资源处理器,静态资源也找不到则响应404页面。


  	 String staticPathPattern = this.mvcProperties.getStaticPathPattern();
				//静态资源文件夹映射
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

改变默认的静态资源路径:

spring:
  mvc:
    static-path-pattern: /res/**    #配置默认静态资源访问前缀,访问时需要添加 /res

  web:
    resources:
      static-locations: [classpath:/abc/]   #更改默认静态资源路径,只有abc文件下的才是静态资源



index.html 页面:

"/ ** " :访问当前项目的静态资源文件夹下的 index.html 页面:

静态资源的文件夹 : “classpath:/META‐INF/resources/”“classpath:/resources/”“classpath:/static/”“classpath:/public/”"/" (当前项目的根路径)


	//配置程序欢迎页映射
	    @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
            WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
            welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
            return welcomePageHandlerMapping;
        }
        

改变默认的静态资源路径:

spring:
#  mvc:
#    static-path-pattern: /res/**    #需要禁用静态资源访问前缀,否则index.html不能被默认访问

  web:
    resources:
      static-locations: [classpath:/abc/]   #更改默认静态资源路径,只有abc文件下的才是静态资源


项目图标:

** /favicon.ico :访问当前项目的静态资源文件夹下的图标:

静态资源的文件夹 : “classpath:/META‐INF/resources/”“classpath:/resources/”“classpath:/static/”“classpath:/public/”"/" (当前项目的根路径)

  //配置喜欢的图标
		@Configuration
		@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
		public static class FaviconConfiguration {

			private final ResourceProperties resourceProperties;

			public FaviconConfiguration(ResourceProperties resourceProperties) {
				this.resourceProperties = resourceProperties;
			}

			@Bean
			public SimpleUrlHandlerMapping faviconHandlerMapping() {
				SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
				mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
              	//所有  **/favicon.ico 
				mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
						faviconRequestHandler()));
				return mapping;
			}

			@Bean
			public ResourceHttpRequestHandler faviconRequestHandler() {
				ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
				requestHandler
						.setLocations(this.resourceProperties.getFaviconLocations());
				return requestHandler;
			}

		}

注意点: SpringBoot 2.2.X版本,将默认的 favicon.ico 配置移除,但是 仍支持该写法;


SpringMVC 配置:

SpringMVC 自动配置:

Spring Boot 自动配置好了SpringMVC,以下是SpringBoot对SpringMVC的默认配置:

自动配置解释
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans自动配置了ViewResolver(视图解析器),根据方法的返回值得到视图对象,视图对象决定通过转发或者重定向进行渲染;我们也可以自己给容器添加视图解析器,会自动将其组合进来;
Support for serving static resources, including support for WebJars (see below)静态资源文件夹路径,webjars
Static index.html support静态首页访问
Custom Favicon support (see below)项目图标
***Automatic registration of Converter, GenericConverter, Formatter beans ***Converter:转换器;Formatter:格式化器;添加的转换器和格式化器,我们只需要放在容器中即可
Support for HttpMessageConverters (see below)HttpMessageConverters 从容器中确定,用来获取所有的HttpMessageConverter;HttpMessageConverter是 SpringMVC 中用来转换 Http 请求和响应的 ;给容器中添加HttpMessageConverter,只需要将自己的组件通过 @Bean,@Component 注解注册容器中即可;
Automatic registration of MessageCodesResolver (see below)定义错误代码生成规则
Automatic use of a ConfigurableWebBindingInitializer bean (see below)ConfigurableWebBindingInitializer 用来初始化 WebDataBinder(Web数据绑定器),可以配置一个 ConfigurableWebBindingInitializer 来替换默认的,注册到容器即可;

扩展/修改 SpringMVC 配置:

编写一个配置类,是 WebMvcConfigurerAdapter 类型;不能标注为 @EnableWebMvc

Springboot1.x版本如何配置:

通过继承 webmvcconfigureradapter 类:

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
	
	//浏览器发送 /yp 请求来到 success页面
	registry.addViewController("/yp").setViewName("success");
	}
}
Springboot2.x版本如何配置:

通过实现 webmvcconfigure 接口:

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //浏览器发送 /yp 请求来到 success
        registry.addViewController("/yp").setViewName("success");
    }
}

说明WebMvcAutoConfiguration 是 SpringMVC 的自动配置类;在做其他自动配置时会导入Import(EnableWebMvcConfiguration.class),所以容器中所有的 WebMvcConfigurer 都会一起起作用,即 SpringMVC 的自动配置和我们编写的扩展配置都会起作用;

全面接管 SpringMVC 配置:

只在配置类中添加 @EnableWebMvc即可,这样所有的 SpringMVC 的自动配置都失效了

@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {

	//浏览器发送 /yp 请求来到 success页面
	registry.addViewController("/yp").setViewName("success");
	}
}

说明: EnableWebMvc 的核心是导入了 Import(DelegatingWebMvcConfiguration.class) (截图一), 而 DelegatingWebMvcConfiguration 又继承了 WebMvcConfigurationSupport (截图二);即EnableWebMvcWebMvcConfigurationSupport 组件导入进来了(导入的WebMvcConfigurationSupport 只是 SpringMVC 最基本的功能);但是在 WebMvcAutoConfiguration 类中,注解了ConditionalOnMissingBean(WebMvcConfigurationSupport.class) (截图三),这句注解表明当容器中没有 WebMvcConfigurationSupport.class 这个组件的时候,这个自动配置类才会生效,故注解 EnableWebMvc 会导致自动配置全部失效;

截图一:

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {

截图二:

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

截图三:

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})

//容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})

@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值