本节将学习使用thymeleaf模板引擎开发mvc页面。
先在build.gradle中加载相应的包,如下:
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
创建controller,注意此时不能用@RestController
,而要用@Controller
,下面直接上方法。
@GetMapping("/index")
public ModelAndView index() {
ModelAndView view = new ModelAndView();
view.setViewName("index"); //这里是要跳转的html页面
// 设置属性
view.addObject("title", "WEB页面");
view.addObject("desc", "欢迎进入web系统");
Author author = new Author();
author.setAge(22);
author.setName("ITI");
view.addObject("author", author);
return view;
}
设置跳转的视图 默认映射到 /resources/templates/{viewName}.html
接着写html文件,文件中可以使用th:xxx的标签以解析变量,如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title th:text="${title}">Title</title>
<script th:src="@{/js/my.js}"></script>
</head>
<body>
<h1 th:text="${desc}">Hello World</h1>
<p th:text="${author.name}"></p>
<p th:text="${author.age}"></p>
<p th:text="${author.email}"></p>
<div id="content"></div>
</body>
</html>
再看看js:
window.onload = function (ev) {
document.querySelector("#content").innerHTML="这是用JS写入的";
}
若想知道更多标签,可以打开官网https://www.thymeleaf.org/
学习交流,请加群:64691032