Spring Boot2.x 整合Thymeleaf模板

257 阅读1分钟
  • 添加依赖
 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
      <version>2.0.1.RELEASE</version>
 </dependency>
  • 默认路径下添加模板 src/main/resources/templates

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <!-- 可以看到 thymeleaf 是通过在标签里添加额外属性来绑定动态数据的 -->
  <title th:text="${title}">Title</title>
  <!-- 在/resources/static/js目录下创建一个hello.js 用如下语法依赖即可-->
  <script type="text/javascript" th:src="@{/js/hello.js}"></script>
</head>
<body>
<h1 th:text="${desc}">Hello World</h1>
<p th:text="${person?.name}"></p>
<p th:text="${person?.age}"></p>
<button onclick="click(this)">点击</button>
</body>
</html>
  • 编写控制器
@Controller
public class ThymeleafController {


	@RequestMapping("index2")
	public String index(HttpServletRequest model){

		model.setAttribute("title","你阿豪");
		model.setAttribute("desc","描述");


		Person person = new Person();

		person.setName("zhangsan");
		person.setAge(14);

		model.setAttribute("person",person);

		return "index";
	}


	class Person{
		private String name;
		private int age;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getAge() {
			return age;
		}

		public void setAge(int age) {
			this.age = age;
		}
	}


}