自学SpringBoot学习笔记--整合thymeleaf

项目搭建起来,数据库连接上,该整合一下前端框架了~因为之前一直使用的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>

效果:


if switch 表达式待补充




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值