1. 程式人生 > >SpringBoot web開發-靜態資源對映規則

SpringBoot web開發-靜態資源對映規則

1 Hello World

如何建立一個SpringBoot web專案我這裡就不多贅述了,我們先看看如何傳送一個Hello World 請求把:

  • 建立一個HelloController
@RestController
public class HelloController {

    @RequestMapping(method = RequestMethod.GET,path = "/hello")
    public String hello(){
        return "hello world";
    }
}

這樣訪問http://localhost:8080/hello

就能返回給我們一個 hello world。

靜態資源

我們知道現在建立的springboot專案是以打jar的包形式那如何載入靜態資源呢?以前我們建立一個web專案我們可以把一些靜態資源:css、js、jsp等等放在webapp目錄下,那現在該如何做呢?

  • WebMvcAutoConfiguration類
    我們看看其中的addResourceHandlers這個方法:
		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(); if (!registry.hasMappingForPattern
("/webjars/**")) { customizeResourceHandlerRegistration(registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(getSeconds(cachePeriod)) .setCacheControl(cacheControl)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations(getResourceLocations( this.resourceProperties.getStaticLocations())) .setCachePeriod(getSeconds(cachePeriod)) .setCacheControl(cacheControl)); } }

這個方法其實很簡單先判斷是否禁止我們訪問預設的資源(好習慣,大家寫程式碼的時候也儘量這樣寫),然後註冊我們的靜態資源在/webjars/**目錄下,這就意味著我們的靜態資源可以放在該目錄下classpath:/META-INF/resources/webjars/。最後我們可以設定和靜態資源有關的引數,快取時間等。
這裡呢如何讓我們想引入jquery、js等相關的包可以直接新增在pom檔案中可以在https://www.webjars.org/這個網站中區查詢。

  • 例項
		<!--jquery-->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.3.1-1</version>
		</dependency>

引入pom檔案後我們可以發現:
在這裡插入圖片描述
我們可以通過 localhost:8080/webjars/jquery/3.3.1/jquery.js去訪問;所以說我們以後可以直接引入依賴加入到pom檔案中即可。

那如果引入我們自己寫的給該怎麼辦呢?其實在剛剛上面的一段程式碼中
靜態資原始檔夾對映

//靜態資原始檔夾對映
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(
						registry.addResourceHandler(staticPathPattern)
								.addResourceLocations(getResourceLocations(
										this.resourceProperties.getStaticLocations()))
								.setCachePeriod(getSeconds(cachePeriod))
								.setCacheControl(cacheControl));
			}

我們可以點進這個方法中看看this.resourceProperties.getStaticLocations()

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

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

	/**
	 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
	 * /resources/, /static/, /public/].
	 */
	private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

	/**
	 * Whether to enable default resource handling.
	 */
	private boolean addMappings = true;

“/**” 訪問當前專案的任何資源,都去(靜態資源的資料夾)找對映

  • 靜態資原始檔夾
"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/" 

那麼我們訪問localhost:8080/abc ===> 去靜態資原始檔夾裡面找abc

配置歡迎頁對映
WelcomePageHandlerMapping類可以設定歡迎頁面映射回去找index頁面

		@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(
				ResourceProperties resourceProperties) {
			return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
		}

我們可以在靜態資源目錄下配置index頁面,如歌沒有沒有配置訪問localhost://8080會顯示404

配置喜歡的圖示

		@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;
			}

		}

所有的 **/xxx.ico 都是在靜態資原始檔下找;

下圖就是靜態資原始檔夾可以是public、resoueces、static任選一個都可以:
在這裡插入圖片描述
這些靜態資源的載入位置都是springboot預設給我們建立的,當然我們可以自己設定可以通過:
spring.resources.static-locations=classpath:/hello,classpath:/spring 配置多個用逗號分隔。