1. 程式人生 > >SpringBoot——web開發之靜態資源引入

SpringBoot——web開發之靜態資源引入

1、雖說SpringBoot為我們提供了很多可以放置靜態資源的資料夾,但靜態頁面(html)最好放在templates資料夾下,因為放在該資料夾下才能得到模板引擎的解析,放在其他靜態資原始檔夾下則不能得到模板引擎的解析,這樣就無法使用模板引擎的強大功能了

2、假如在public和templates資料夾下都存在index.html,那麼在不進行其他設定的情況下預設首頁是public資料夾下的index.html,而不是templates下的index.html,如果想使預設首頁變為templates下的則可以使用以下方式進行對映:

①在Controller中寫處理請求"/"的方法,在方法中返回資源的位置(模板引擎預設會到templates資料夾下找資源)

@Controller
public class TestController {

    @RequestMapping({"/","/index.html"})
    public String index(){
        return "index";
    }
}

②在我們自定義的WebMvcConfigurerAdapter中新增viewController:

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

③在我們自定義的WebMvcConfigurerAdapter中註冊一個返回WebMvcConfigurerAdapter型別物件的Bean,在該Bean中新增請求對映:

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        //因為WebMvcConfigurerAdapter是抽象類,需要在方法體中實現其抽象方法,雖然該類沒有抽象方法,但方法體不可省
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter(){
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("index");
                registry.addViewController("/index.html").setViewName("index");
            }
        };
        return adapter;
    }
}

原理很簡單,SpringBoot會將所有標註為@Configuration的類當做容器配置類,在該類中使用@Bean註解就相當於向容器中添加了一個WebMvcConfigurationAdapter元件,而在SpringBoot為SpringMVC提供的自動配置中會將容器中所有的WebMvcConfigurationAdapter進行組合,使它們一起起作用

3、公共資源使用webjars的方式引用

①匯入bootstrap的webjars:

<!-- bootstrap的webjar-->
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>bootstrap</artifactId>
	<version>4.1.3</version>
</dependency>

②引入模板引擎的名稱空間,會給我們程式碼提示:

<html lang="en" xmlns:th="http://www.thymeleaf.org">

③使用th:xxx屬性引入webjars資源,具體路徑需要看該資源在依賴包中的位置,比如:

<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.1.3/css/bootstrap.css}" rel="stylesheet">

④非webjars資源我們也可以使用th:xxx屬性引入,這樣有一個好處,就是資源的地址會隨著專案名的改變而動態改變:

<link th:href="@{/asserts/css/signin.css}" href="asserts/css/signin.css" rel="stylesheet">