一、新建springboot项目
1. 访问 http://start.spring.io/,选择构建工具 Maven Project、Java、Spring Boot 版本 2.1.3 以及一些工程基本信息,解压后,使用 Idea 导入项目,File -> New -> Model from Existing Source.. -> 选择解压后的文件夹 -> OK,选择 Maven
2. 根据mvc分层原则,建立包
3. 配置thymeleaf
在application.properties文件中配置如下:
##thymeleaf的配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
也可以不用配置按照默认的来:可以查看ThymeleafProperties该类,这个类有thymeleaf的默认配置
4. 编写html
thymeleaf需要添加:<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<p th:text="${session.u}">Welcome to our grocery store!</p>:该写法动态替换<p></p>中的内容
以下是遍历list集合的方式:
<tr th:each="user : ${session.users}">
<td th:text="${user.userName}">user.userName</td>
<td th:text="${user.passWord}">user.passWord</td>
<td th:text="${user.email}">user.email</td>
</tr>
5. 编写controller
@RequestMapping(value = "/thy" ,method = RequestMethod.GET)
public String toThyTest(HttpSession session){
session.setAttribute("u","thymeleaf test!!!!!");
List<User> users = new ArrayList<User>();
users.add(new User("小明","111222","ming@qq.com",""));
users.add(new User("小红","1112224","hong1@qq.com",""));
users.add(new User("小王","1112122","wang@qq.com",""));
users.add(new User("小黑","11122322","hei@qq.com",""));
users.add(new User("小白","1112222","bai1@qq.com",""));
session.setAttribute("users",users);
return "thyTest";
}
之后启动应用,浏览器键入http://127.0.0.1:8080/thy,即可访问编写的thyTest.html页面
碰到的几点问题:
1.一开始总是报,cannot find classpath:/templates/ ,一直找不到原因,重新bulid项目之后就好了
2.如果需要返回模板,注意不要使用@RestController, 该注释相当于@Controller和@ResponseBody的综合