Spring Boot集成Thymeleaf简单实例
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)运行结果