靜態頁面
spring boot項目只有src目錄,沒有webapp目錄,會將靜態訪問(html/圖片等)映射到其自動配置的靜態目錄,如下
/static
/public
/resources
/META-INF/resources
比如,在resources建立一個static目錄和index.htm靜態文件,訪問地址 http://localhost:8080/index.html
如果要從后台跳轉到靜態index.html,代碼如下。
- @Controller
- public class HtmlController {
- @GetMapping("/html")
- public String html() {
- return "/index.html";
- }
動態頁面
動態頁面需要先請求服務器,訪問后台應用程序,然后再轉向到頁面,比如訪問JSP。spring boot建議不要使用JSP,默認使用Thymeleaf來做動態頁面。
在pom.xml 中添加Thymeleaf組件
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
TemplatesController.java
- package hello;
- import javax.servlet.http.HttpServletRequest;
- import org.springframework.stereotype.*;
- import org.springframework.web.bind.annotation.*;
- @Controller
- public class TemplatesController {
- @GetMapping("/templates")
- String test(HttpServletRequest request) {
- //邏輯處理
- request.setAttribute("key", "hello world");
- return "/index";
- }
- }
@RestController:上一篇中用於將返回值轉換成json
@Controller:現在要返回的是一個頁面,所以不能再用@RestController,而用普通的@Controller/
request.setAttribute("key", "hello world"):這是最基本的語法,向頁面轉參數 key和value。
return "/index": 跳轉到 templates/index.html動態頁面,templates目錄為spring boot默認配置的動態頁面路徑。
index.html 將后台傳遞的key參數打印出來
- <!DOCTYPE html>
- <html>
- <span th:text="${key}"></span>
- </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"。
- @GetMapping("/html")
- public String html() {
- return "redirect:/index.html";
- }