溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則是什么

發(fā)布時(shí)間:2021-11-11 13:33:34 來源:億速云 閱讀:181 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則是什么”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

    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+Thymeleaf靜態(tài)資源的映射規(guī)則是什么

    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/文件夾下,如下所示:

    SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則是什么

    由圖可以看出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文件夾下,如下圖所示:

    SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則是什么

    如上圖若想訪問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í)筆記

    SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則是什么

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

    “SpringBoot+Thymeleaf靜態(tài)資源的映射規(guī)則是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI