7、SpringBoot 使用 thymeleaf
阿新 • • 發佈:2018-12-03
SpringBoot 使用 thymeleaf
步驟一:在pom.xml中引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
關閉thymeleaf快取
開發過程中建議關閉快取
spring:
thymeleaf:
cache: false
編寫hello.html
放到resources/templates/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
Hello thymeleaf!
<br>
My name is Nancy!
</h1>
</body >
</html>
編寫HelloController
package cn.ylx.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/templates")
public class HelloController {
@RequestMapping("/hello")
public String sayHello (){
return "hello";
}
}
瀏覽器請求 http://localhost:8080/templates/hello
會找到相應的servlet,返回hello,找到resources/templates/hello.html,返回頁面。
編寫模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
Hello thymeleaf!
<br>
My name is <span th:text="${name}"></span>!
</h1>
</body>
</html>
編寫訪問模板檔案Controller
package cn.ylx.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@Controller
@RequestMapping("/templates")
public class HelloController {
@RequestMapping("/hello")
public String sayHello(Map<String,Object> map){
map.put("name", "Nancy");
return "hello";
}
}
測試:能成功渠道Nancy。