天天看點

Springboot的web開發中static和templates的差別1.建立一個SpringBoot Maven項目2. static目錄3. template目錄4.總結

在src/main/resources下面有兩個檔案夾,static和templates,springboot預設 static中放靜态頁面,而templates中放動态頁面

1.建立一個SpringBoot Maven項目

1.1 依賴設定(選中web和Thymeleaf)

Springboot的web開發中static和templates的差別1.建立一個SpringBoot Maven項目2. static目錄3. template目錄4.總結
Springboot的web開發中static和templates的差別1.建立一個SpringBoot Maven項目2. static目錄3. template目錄4.總結

1.2 resource結構如下

Springboot的web開發中static和templates的差別1.建立一個SpringBoot Maven項目2. static目錄3. template目錄4.總結

2. static目錄

2.1 在static下建立hello1.html

運作程式,浏覽器輸入http://localhost:8080/hello1.html

Springboot的web開發中static和templates的差別1.建立一個SpringBoot Maven項目2. static目錄3. template目錄4.總結
so,可以在根目錄下通路hello1.html,static目錄類似于傳統Java web中的webroot或webcontent

2.2 也可以通過接口跳轉

2.2.1 添加接口

@RequestMapping("hello1")
    public String hello1() {

        return "hello1.html";
    }
           

2.2.2 注釋掉thymeleaf依賴

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

2.2.3 浏覽器輸入http://localhost:8080/hello1

Springboot的web開發中static和templates的差別1.建立一個SpringBoot Maven項目2. static目錄3. template目錄4.總結

3. template目錄

3.1 在template下建立hello2.html

運作程式,浏覽器輸入http://localhost:8080/hello2.html

Springboot的web開發中static和templates的差別1.建立一個SpringBoot Maven項目2. static目錄3. template目錄4.總結
templates下的動态頁面不能直接通路

3.2 通過接口通路

3.2.1 添加接口

注意接口中return的頁面不包含.html字尾
@RequestMapping("hello2")
    public String hello2() {

        return "hello2";
    }
           

3.2.2 浏覽器輸入http://localhost:8080/hello2

Springboot的web開發中static和templates的差別1.建立一個SpringBoot Maven項目2. static目錄3. template目錄4.總結

4.總結

靜态頁面的return預設是跳轉到/static/目錄下,當在pom.xml中引入了thymeleaf元件,動态跳轉會覆寫預設的靜态跳轉,預設就會跳轉到/templates/下,注意看兩者return代碼也有差別,動态沒有html字尾。

繼續閱讀