1. 程式人生 > >Spring Boot 靜態資源路徑分析

Spring Boot 靜態資源路徑分析

導致 路徑 分享圖片 ota thymeleaf map ppi contex pub

  最近在接觸一個看公司的java後臺項目(采用的耶魯大學開源的一個cas單點登錄系統),用的是框架是Spring Boot,用的模板是Thymeleaf,於是我生成一個Spring Boot的項目,並且引入Thymeleaf,開始了我的聯系,我在引靜態資源的時候總是報錯:

No mapping found for HTTP request with URI [/jquery.min.js] in DispatcherServlet with name ‘dispatcherServlet‘

  我在網上查資料,得知Spring Boot對靜態資源映射提供了默認配置(一般情況我們是不需要配置,除非我們要自定義路徑映射),默認情況下,Spring Boot從類路徑的以下位置提供靜態資源:

  • /static
  • /public
  • /resources
  • /META-INF/resources

  技術分享圖片

  我的jquery.min.js也在classpath/static下啊,為啥找不到...找了半天,我發現我引了我們項目中的一個文件,這個文件修改默認的Spring Boot的配置,導致靜態文件找不到:

  技術分享圖片

  文件內容如下:

package com.practice.springboot.hello.framework;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //將templates目錄下的CSS、JS文件映射為靜態資源,防止Spring把這些資源識別成thymeleaf模版
        registry.addResourceHandler("/templates/**.js").addResourceLocations("classpath:/templates/");
        registry.addResourceHandler("/templates/**.css").addResourceLocations("classpath:/templates/");
        //其他靜態資源
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

  我將路徑加上/static之後,http://localhost:8888/static/jquery.min.js就可訪問到了.請求路徑加上 /templates同理

  技術分享圖片

Spring Boot 靜態資源路徑分析