1.maven座標
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
必須增加web和thymeleaf的依賴。
2.項目結構
資源目錄templates是thymeleaf的默認路徑,增加thymeleat的依賴後,可以通過視圖解析器訪問模板。
static目錄下的文件可以直接訪問。
3.配置視圖解析器
#定義視圖解析器的規則
#文件前綴,templates是thymeleafd的默認路徑
spring.mvc.view.prefix=classpath:/templates/
#文件後綴
spring.mvc.view.suffix=.html
4.Controller跳轉訪問模板
package com.zyf.springMVC.mvcview;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/mvcview")
public class MvcViewController {
@RequestMapping("/v1")
public ModelAndView mvc1() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("mvcview/v1");
modelAndView.addObject("username", "張三");
return modelAndView;
}
@RequestMapping("/v2")
public String mvc2() {
return "mvcview/v2";
}
}
5.模板文件
v1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>hello spring mvc v1</p>
<p th:text="${username}"></p>
</body>
</html>
v2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>hello spring mvc v2</p>
</body>
</html>
6.測試
6.1.訪問static下的html文件
瀏覽器輸入http://localhost:8080/ 或者http://localhost:8080/index.html,都可以訪問index.html模板。
但是要訪問index2.html則只能輸入:http://localhost:8080/index2.html
6.2.跳轉訪問模板
如果沒有添加thymeleat的依賴,無法訪問templates下的模板,會有404錯誤。
github:https://github.com/zhangyangfei/SpringBootLearn.git中的springMVC工程。