最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則說明

 更新時(shí)間:2021年11月11日 11:21:44   作者:qq_39602928  
這篇文章主要介紹了SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Spring Boot中靜態(tài)資源的映射規(guī)則

Spring Boot中靜態(tài)資源主要包括兩部分:1、webjars資源,2、自定義的其他html、css、js資源,下面分別介紹兩種資源的映射規(guī)則。

1)、webjars資源

WebJars是將web前端資源(js,css等)打成jar包文件,然后借助Maven工具,以jar包形式對(duì)web前端資源進(jìn)行統(tǒng)一依賴管理,保證這些Web資源版本唯一性。webjars導(dǎo)入對(duì)應(yīng)的xml代碼可以在webjars的官網(wǎng)進(jìn)行復(fù)制。

https://www.webjars.org/

在這里插入圖片描述

SpringBoot對(duì)webjars資源的映射規(guī)則在WebMvcAutoConfiguration.java包里面,代碼部分截圖如下所示:

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        Integer cachePeriod = this.resourceProperties.getCachePeriod();
        if (!registry.hasMappingForPattern("/webjars/**")) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(cachePeriod));
        }
        String staticPathPattern = this.mvcProperties.getStaticPathPattern();
        if (!registry.hasMappingForPattern(staticPathPattern)) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));
        }
    }
}

由上述代碼可以看出,所有訪問項(xiàng)目根目錄下的webjars下的所有資源,都會(huì)被映射到classpath:/META-INF/resources/webjars/文件夾下,其中classpath是resources資源文件夾或類的根目錄。

而使用maven方式導(dǎo)入的webjars包的靜態(tài)資源(js、css)會(huì)自動(dòng)放到classpath:/META-INF/resources/webjars/文件夾下,如下所示:

在這里插入圖片描述

由圖可以看出dist中的靜態(tài)資源文件上層目錄為resources/webjars/**

因此在前端引用(此處用的是thymeleaf模板引擎)時(shí)可以用如下方式引用:直接從webjars目錄開始寫即可,上述靜態(tài)資源映射配置的實(shí)際效果即在自己寫的資源路徑前面加上classpath:/META-INF/resources前綴

<link  th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="external nofollow"  rel="stylesheet">

2)、自己添加的靜態(tài)資源文件

Spring Boot對(duì)自己添加的靜態(tài)資源文件的映射規(guī)則仍然在WebMvcAutoConfiguration.java文件中,實(shí)際配置是在ResourcesProperties.java資源文件中CLASSPATH_RESOURCE_LOCATIONS變量。

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

上述配置效果即所有的靜態(tài)資源的訪問除直接訪問/webjars/**路徑時(shí),會(huì)在訪問路徑前加上上述配置中的任意一個(gè)字符串進(jìn)行查找,直到在相應(yīng)的文件下找到對(duì)應(yīng)的靜態(tài)資源。因此在編寫SpringBoot應(yīng)用時(shí)一般可以將靜態(tài)資源放置在resources資源目錄下的static或者public文件夾下,如下圖所示:

在這里插入圖片描述

如上圖若想訪問layui.js可以如下引用靜態(tài)資源:

<script  th:src="@{/layui/layui.js}"></script>

上述引用之后,SpringBoot會(huì)去CLASSPATH_RESOURCE_LOCATIONS變量指定的路徑下找layui/layui.js直到找到該文件位置。

CLASSPATH_RESOURCE_LOCATIONS的值可以直接在SpringBoot的配置文件application.properties或yml文件中進(jìn)行修改。

Thymeleaf模板引擎的映射規(guī)則

Thymeleaf模板引擎的映射規(guī)則如下所示

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";

上述代碼的實(shí)際效果是在使用模板引擎是會(huì)將請(qǐng)求路徑字符串的前面加上classpath:/templates/,后面加上html進(jìn)行資源請(qǐng)求。因此一般將需要模板引擎進(jìn)行渲染的html界面放在resources路徑下的templates文件夾下,并且在請(qǐng)求的路徑字符串中不需要加html后綴。

一個(gè)簡(jiǎn)單的例子如下所示:

    @RequestMapping("/success")
    public String success(Map<String,Object> map){
//        map=new HashMap<>();  這個(gè)地方不能再new了
        map.put("hello","hello");
        return "success";
    }

上述代碼返回所渲染的html界面即位于resources/templates文件夾下的success.html界面。該默認(rèn)設(shè)置頁(yè)可以直接在配置文件中通過spring.thymeleaf選項(xiàng)進(jìn)行修改。

SpringBoot對(duì)靜態(tài)資源的映射規(guī)則源碼學(xué)習(xí)筆記

在這里插入圖片描述

WebMvcAuotConfiguration:

		@Override
		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();
			//所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找資源;
			//webjars:以jar包的方式引入靜態(tài)資源;
			if (!registry.hasMappingForPattern("/webjars/**")) {
				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
			//"/**" 訪問當(dāng)前項(xiàng)目的任何資源,都去(靜態(tài)資源的文件夾)找映射
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			//靜態(tài)資源文件夾映射
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
		}

resourceProperties

			源碼:
			//可以設(shè)置和靜態(tài)資源有關(guān)的參數(shù),緩存時(shí)間等
			@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
			public class ResourceProperties {

getStaticPathPattern():

		源碼:			
		private String staticPathPattern = "/**";		
		public String getStaticPathPattern() {
			return this.staticPathPattern;
		}

getStaticLocations()

			源碼:
			private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
			"classpath:/resources/", "classpath:/static/", "classpath:/public/" };			
			private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;			
			public String[] getStaticLocations() {
				return this.staticLocations;
			}

//配置歡迎頁(yè)映射

		@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(
				ResourceProperties resourceProperties) {
				//靜態(tài)資源文件夾下的所有index.html頁(yè)面;被"/**"映射;
			return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
		}
		private Optional<Resource> getWelcomePage() {
			String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
			return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
		}
		private Resource getIndexHtml(String location) {
			return this.resourceLoader.getResource(location + "index.html");
		}	

getStaticPathPattern()

   源碼:
   private String staticPathPattern = "/**";
   public String getStaticPathPattern() {
    return this.staticPathPattern;
   }

//配置喜歡的圖標(biāo)

  @Configuration
  @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
  public static class FaviconConfiguration implements ResourceLoaderAware {
   private final ResourceProperties resourceProperties;
   private ResourceLoader resourceLoader;
   public FaviconConfiguration(ResourceProperties resourceProperties) {
    this.resourceProperties = resourceProperties;
   }
   @Override
   public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
   }
   @Bean
   public SimpleUrlHandlerMapping faviconHandlerMapping() {
    SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
    //所有  **/favicon.ico 都是在靜態(tài)資源文件下找
    mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler()));
    return mapping;
   }
   @Bean
   public ResourceHttpRequestHandler faviconRequestHandler() {
    ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
    requestHandler.setLocations(resolveFaviconLocations());
    return requestHandler;
   }
   private List<Resource> resolveFaviconLocations() {
    String[] staticLocations = getResourceLocations(this.resourceProperties.getStaticLocations());
    List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
    Arrays.stream(staticLocations).map(this.resourceLoader::getResource).forEach(locations::add);
    locations.add(new ClassPathResource("/"));
    return Collections.unmodifiableList(locations);
   }
  }

Thymeleaf使用

 源碼:
 //只要我們把HTML頁(yè)面放在classpath:/templates/,thymeleaf就能自動(dòng)渲染;
 @ConfigurationProperties(prefix = "spring.thymeleaf")
 public class ThymeleafProperties {
  private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
  public static final String DEFAULT_PREFIX = "classpath:/templates/";
  public static final String DEFAULT_SUFFIX = ".html"; 
 }

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

林周县| 新河县| 平武县| 武威市| 灵石县| 江都市| 清镇市| 乌兰县| 板桥市| 肥乡县| 林口县| 万全县| 旅游| 沧州市| 宝坻区| 江华| 柏乡县| 陆良县| 潜江市| 江阴市| 察雅县| 英德市| 金华市| 双流县| 平安县| 察哈| 平山县| 邢台市| 天长市| 韶山市| 绿春县| 合水县| 奇台县| 绵竹市| 泉州市| 桦南县| 酉阳| 莒南县| 繁昌县| 元阳县| 江油市|