springboot整合前端html頁面中出現的靜態資源不能訪問的問題

剛學springboot ,在整合前端頁面時發現 原來的html導入到springboot的resource目錄後,靜態樣式**.css 和 **.js沒法生效的

1.pom.xmlcss

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!--引入webjars -->

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>3.3.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

</dependencies>

2.控制類
複製代碼
/**
 * @Author: soul
 * @Date: 2019/4/14 19:48
 */
@Controller
public class ControllerClass {

    @RequestMapping("/man")
    public String man(){
        return "man";
    }

}

複製代碼

未導入springboot下的resource目錄前的 前端頁面目錄結構及link引入

導入springboot中 後的目錄結構爲

咱們訪問靜態資源style.css確保能訪問後

只需修改 link標籤下的路徑 href 爲便可解決html頁面出現的靜態資源沒法引用的問題

爲何呢?

咱們能夠打開springboot的配置類
  
@ConfigurationProperties(
    prefix = "spring.resources",
    ignoreUnknownFields = false
)
public class ResourceProperties {
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
    private String[] staticLocations;
    private boolean addMappings;
    private final ResourceProperties.Chain chain;
    private final ResourceProperties.Cache cache;
    複製代碼

咱們能夠看到springboot加載資源的路徑爲默認爲classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/html

再看Thymeleaf的配置

@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";
複製代碼

只要咱們將html頁面放到classpath:/templates/下,thmeleaf就能自動渲染前端

注意!!!

1.禁用掉thymeleaf的緩存功能
#禁用模板引擎的緩存
spring.thymeleaf.cache=false
2.在idea中修改 html代碼 時記得按 ctrl +f9刷新一下
想要源碼的能夠留下評論!!!-
相關文章
相關標籤/搜索