Spring Boot整合Thymeleaf簡單例項
阿新 • • 發佈:2018-12-19
1、定義
Thymeleaf是一種用於Web和獨立環境的現代伺服器端的Java模板引擎。
2、簡單例項
(1)目錄結構
(2)MySpringBootApplication.java
package cn.hwd.thymeleaf; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MySpringBootApplication { public static void main(String[] args) { SpringApplication.run(MySpringBootApplication.class, args); } }
(3)HelloController.java
package cn.hwd.thymeleaf.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value = "/hello") public class HelloController { @RequestMapping(value = "/index", method = RequestMethod.GET) public String index(HttpServletRequest request) { request.setAttribute("message", "Hello world."); return "index"; } }
(4)index.html
<!DOCTYPE html> <html> <head> <link rel="stylesheet" th:href="@{/css/default.css}"/> <meta charset="UTF-8"/> <title>Insert title here</title> </head> <body> <div class="hello"> <p th:text="${message}"></p> </div> </body> </html>
(5)default.css
.hello {color: red;}
(6)application.properties
spring.thymeleaf.cache = false
(7)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.hwd</groupId>
<artifactId>thymeleaf01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>thymeleaf01</name>
<url>http://www.example.com</url>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
</dependencies>
</project>
(8)執行結果