Spring Boot +thymeleaf +IDEA,靜態資源CSS\JS\img 404 錯誤,No mapping for GET 靜態資源的問題。


1.問題描述

使用Spring Boot +thymeleaf +IDEA開發一個新項目,啟動后首頁css\js等全部404,起初分析是路徑錯誤,但是在IDEA中使用ctrl+鼠標左鍵可以找到,經過各種百度、各種嘗試。IDEA控制台出現警告No mapping for GET ‘XXX’,對於一個開發人而言處理一個問題時,錯誤出現的時候也恰恰是希望出現的時候。

解決:

我放棄了使用.properties配置mvc攔截器,改為使用配置類配置,問題解決。

我的項目  目錄

 

 

 1.在controller下創建文件夾config並創建

MvcConfigController配置類,類內容如下:
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 MvcConfigController extends WebMvcConfigurationSupport {

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

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**").addResourceLocations(
CLASSPATH_RESOURCE_LOCATIONS);
}
}
}

重啟項目,問題解決。

 

 JS、css、圖片加載正常。

 

至於配置的作用詳解,日后再談。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM