SpringBoot Web詳解靜態(tài)資源規(guī)則與定制化處理
1.相關(guān)概念
- Spring Boot 默認(rèn)為我們提供了靜態(tài)資源處理,使用 WebMvcAutoConfiguration 中的配置各種屬性。
- 建議使用Spring Boot的默認(rèn)配置方式,如果需要特殊處理的再通過配置文件進(jìn)行修改。
- 如果想要自己完全控制WebMVC,就需要在@Configuration注解的配置類上增加@EnableWebMvc, 增加該注解以后WebMvcAutoConfiguration中配置就不會(huì)生效,你需要自己來配置需要的每一項(xiàng)(可以使用繼承)。
2.靜態(tài)資源目錄
默認(rèn)只要靜態(tài)資源放在類路徑(resources)下:
/static
/public
/resources
/META-INF/resources
瀏覽器訪問: 當(dāng)前項(xiàng)目根路徑/ + 靜態(tài)資源名





請求進(jìn)來,先去找Controller看能不能處理。不能處理的所有請求又都交給靜態(tài)資源處理器。靜態(tài)資源也找不到則響應(yīng)404頁面。
我們在controller里寫個(gè)測試方法來測試一下


把controller里的方法注釋后


也可以改變默認(rèn)的靜態(tài)資源路徑,/static,/public,/resources, /META-INF/resources失效
application.properties
#靜態(tài)資源路徑
spring.resources.static-locations=classpath:/dir1/,classpath:/dir2/




3.靜態(tài)資源訪問前綴
application.properties
#靜態(tài)資源訪問前綴, 就是瀏覽器網(wǎng)址路徑加前綴
spring.mvc.static-path-pattern=/res/**


4.歡迎頁支持
就是網(wǎng)址上沒有訪問映射時(shí), 會(huì)自動(dòng)跳轉(zhuǎn)到歡迎頁,
靜態(tài)資源路徑下 index.html。
- 可以配置靜態(tài)資源路徑
- 但是不可以配置靜態(tài)資源的訪問前綴。否則導(dǎo)致 index.html不能被默認(rèn)訪問


5.自定義favicon
指網(wǎng)頁標(biāo)簽上的小圖標(biāo)。
favicon.ico 放在靜態(tài)資源目錄下即可。


6.源碼分析
- SpringBoot啟動(dòng)默認(rèn)加載 xxxAutoConfiguration 類(自動(dòng)配置類)
- SpringMVC功能的自動(dòng)配置類WebMvcAutoConfiguration生效
@AutoConfiguration(
after = {DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class}
)
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
public class WebMvcAutoConfiguration {
public static final String DEFAULT_PREFIX = "";
public static final String DEFAULT_SUFFIX = "";
public static final PathPatternParser pathPatternParser = new PathPatternParser();
private static final String SERVLET_LOCATION = "/";
public WebMvcAutoConfiguration() {
}
給容器中配置的內(nèi)容:
配置文件的相關(guān)屬性的綁定:WebMvcProperties == spring.mvc、WebProperties==spring.web
@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
@EnableConfigurationProperties({WebMvcProperties.class, WebProperties.class})
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {
private static final Log logger = LogFactory.getLog(WebMvcConfigurer.class);
private final Resources resourceProperties;
private final WebMvcProperties mvcProperties;
private final ListableBeanFactory beanFactory;
private final ObjectProvider<HttpMessageConverters> messageConvertersProvider;
private final ObjectProvider<DispatcherServletPath> dispatcherServletPath;
private final ObjectProvider<ServletRegistrationBean<?>> servletRegistrations;
private final WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer;
private ServletContext servletContext;
配置類只有一個(gè)有參構(gòu)造器
public WebMvcAutoConfigurationAdapter(WebProperties webProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider, ObjectProvider<WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider, ObjectProvider<DispatcherServletPath> dispatcherServletPath, ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
this.resourceProperties = webProperties.getResources();
this.mvcProperties = mvcProperties;
this.beanFactory = beanFactory;
this.messageConvertersProvider = messageConvertersProvider;
this.resourceHandlerRegistrationCustomizer = (WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer)resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
this.dispatcherServletPath = dispatcherServletPath;
this.servletRegistrations = servletRegistrations;
this.mvcProperties.checkConfiguration();
}
- ResourceProperties resourceProperties;獲取和spring.resources綁定的所有的值的對(duì)象
- WebMvcProperties mvcProperties 獲取和spring.mvc綁定的所有的值的對(duì)象
- ListableBeanFactory beanFactory Spring的beanFactory
- HttpMessageConverters 找到所有的HttpMessageConverters
- ResourceHandlerRegistrationCustomizer 找到 資源處理器的自定義器。
- DispatcherServletPath
- ServletRegistrationBean 給應(yīng)用注冊Servlet、Filter…
資源處理的默認(rèn)規(guī)則
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
registration.addResourceLocations(new Resource[]{resource});
}
});
}
}根據(jù)上述代碼,我們可以同過配置禁止所有靜態(tài)資源規(guī)則。
application.properties
#禁用所有靜態(tài)資源規(guī)則
spring.web.resources.add-mappings=false
靜態(tài)資源處理規(guī)則:
public static class Resources {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS
= new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
private boolean addMappings;
private boolean customized;
private final WebProperties.Resources.Chain chain;
private final WebProperties.Resources.Cache cache;
歡迎頁處理規(guī)則:
@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));
welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
return welcomePageHandlerMapping;
}
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders, ApplicationContext applicationContext, Resource welcomePage, String staticPathPattern) {
if (welcomePage != null && "/**".equals(staticPathPattern)) {
logger.info("Adding welcome page: " + welcomePage);
this.setRootViewName("forward:index.html");
} else if (this.welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
logger.info("Adding welcome page template: index");
this.setRootViewName("index");
}
}到此這篇關(guān)于SpringBoot Web詳解靜態(tài)資源規(guī)則與定制化處理的文章就介紹到這了,更多相關(guān)SpringBoot靜態(tài)資源規(guī)則與定制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring,mybatis事務(wù)管理配置與@Transactional注解使用詳解
這篇文章主要介紹了spring,mybatis事務(wù)管理配置與@Transactional注解使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
快速入門介紹Java中強(qiáng)大的String.format()
這篇文章主要給大家介紹了如何快速入門介紹Java中強(qiáng)大的String.format()的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03
利用consul在spring boot中實(shí)現(xiàn)分布式鎖場景分析
這篇文章通過場景分析給大家介紹如何利用consul在spring boot中實(shí)現(xiàn)簡單的分布式鎖功能,代碼簡單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-09-09
Java實(shí)現(xiàn)計(jì)網(wǎng)循環(huán)冗余檢驗(yàn)算法的方法示例
這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)計(jì)網(wǎng)循環(huán)冗余檢驗(yàn)算法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
RocketMQ4.5.X 實(shí)現(xiàn)修改生產(chǎn)者消費(fèi)者日志保存路徑
這篇文章主要介紹了RocketMQ4.5.X 實(shí)現(xiàn)修改生產(chǎn)者消費(fèi)者日志保存路徑方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Spring Boot使用Spring的異步線程池的實(shí)現(xiàn)
這篇文章主要介紹了Spring Boot使用Spring的異步線程池的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
Java轉(zhuǎn)換流(InputStreamReader/OutputStreamWriter)的使用
本文主要介紹了Java轉(zhuǎn)換流(InputStreamReader/OutputStreamWriter)的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01

