项目搭建起来,数据库连接上,该整合一下前端框架了~因为之前一直使用的handlebar,感觉有个前端框架还是挺方便的,由于springboot推荐使用thymeleaf,所以想试试~~
第一步pom文件加依赖
<!--thymeleaf前端框架整合--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
第二步 配置文件
spring: # thymeleaf thymeleaf: prefix: classpath:/templates/ check-template-location: true encoding: utf-8 cache: false
配置文件可以默认不写,为了以后方便还是先写上一些。cache默认是true,这里需要改成false,否则修改页面内容无效。缓存~
第三步 写页面
由配置文件我们可以看出,页面模板默认路径是/templates ,创建项目的时候已经默认创建好了这个文件夹。
在此目录下创建HTML文件 index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 th:text="'我现在最想说:'+ ${msg}"></h1> </body> </html>
第四步 返回页面
Controller层
@Controller public class HelloWorldController { @RequestMapping("/hello") public String hello(ModelMap modelMap) { modelMap.addAttribute("msg","我擦嘞!!!"); return "index"; } }
这个地方要注意一下 注解 @Controller而不要是@RestController 否则返回给浏览器的只是字符串而不是index页面
看一下效果:
ojbk!
------------------------------------------------------------------------------------
遍历List
数据库增加一些数据
@RequestMapping("/hello") public String hello(ModelMap modelMap) { List<User> list=userMapper.searchList(); modelMap.addAttribute("msg","我擦嘞!!!"); modelMap.addAttribute("list",list); return "index"; }
把list放到ModelMap中传给页面
页面中取值:
<table> <tr> <td>姓名</td> <td>密码</td> <td>性别</td> <td>昵称</td> </tr> <tr th:each="user:${list}"> <td th:text="${user.userName}"></td> <td th:text="${user.passWord}"></td> <td th:text="${user.userSex}"></td> <td th:text="${user.nickName}"></td> </tr> </table>
效果: