spring boot-html和templates


靜態頁面

spring boot項目只有src目錄,沒有webapp目錄,會將靜態訪問(html/圖片等)映射到其自動配置的靜態目錄,如下

/static

/public

/resources

/META-INF/resources


比如,在resources建立一個static目錄和index.htm靜態文件,訪問地址 http://localhost:8080/index.html 

如果要從后台跳轉到靜態index.html,代碼如下。

  1. @Controller  
  2. public class HtmlController {  
  3.     @GetMapping("/html")  
  4.     public String html() {  
  5.         return "/index.html";  
  6.     }  

動態頁面

動態頁面需要先請求服務器,訪問后台應用程序,然后再轉向到頁面,比如訪問JSP。spring boot建議不要使用JSP,默認使用Thymeleaf來做動態頁面。

在pom.xml  中添加Thymeleaf組件

  1. <dependency>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-thymeleaf</artifactId>  
  4. </dependency>  

TemplatesController.java

  1. package hello;    
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4.   
  5. import org.springframework.stereotype.*;    
  6. import org.springframework.web.bind.annotation.*;    
  7.     
  8. @Controller  
  9. public class TemplatesController {    
  10.      
  11.     @GetMapping("/templates")  
  12.     String test(HttpServletRequest request) {  
  13.         //邏輯處理  
  14.         request.setAttribute("key""hello world");  
  15.         return "/index";  
  16.     }    
  17. }    

@RestController:上一篇中用於將返回值轉換成json

@Controller:現在要返回的是一個頁面,所以不能再用@RestController,而用普通的@Controller/

request.setAttribute("key", "hello world"):這是最基本的語法,向頁面轉參數 key和value。

return "/index": 跳轉到 templates/index.html動態頁面,templates目錄為spring boot默認配置的動態頁面路徑。

index.html    將后台傳遞的key參數打印出來

  1. <!DOCTYPE html>  
  2. <html>  
  3. <span th:text="${key}"></span>  
  4. </html>     

訪問http://localhost:8080/templates


這只是一個最基本的傳參,templates標簽和JSP標簽一樣,也可以實現條件判斷,循環等各種功能。不過我在上一篇講過,建議用靜態html+rest替代動態頁面,所以關於templates在此不做詳細介紹

動態和靜態區別

靜態頁面的return默認是跳轉到/static/index.html,當在pom.xml中引入了thymeleaf組件,動態跳轉會覆蓋默認的靜態跳轉,默認就會跳轉到/templates/index.html,注意看兩者return代碼也有區別,動態沒有html后綴

重定向

如果在使用動態頁面時還想跳轉到/static/index.html,可以使用重定向return "redirect:/index.html"。

  1. @GetMapping("/html")  
  2. public String html() {  
  3.     return "redirect:/index.html";  
  4. }  


免責聲明!

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



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