分享

thymeleaf的使用

 贪挽懒月 2022-06-20 发布于广东

前言:

最近听说thymeleaf好像也挺流行的,还说是spring官方推荐使用,那thymeleaf究竟是什么呢?spring为什么推荐用它呢?怎么用呢?本文将为你揭秘!

一、thymeleaf简介:

thymeleaf是一种Java模板引擎,那何为模板引擎呢?模板引擎就是为了使用户页面和业务数据相互分离而出现的,将从后台返回的数据生成特定的格式的文档,这里说的特定格式一般都指HTML文档。它能够处理html、xml、js、css甚至纯文本,类似于freemarker。它的优点是语法优雅易懂、原型即页面、遵从web标准。原型即页面是它的特色,所谓原型即页面,就是你写的html,静态的去访问是什么样,动态的去访问还是这样,只不过动态的时候会把数据填充进去。

二、thymeleaf标准方言:

1、变量表达式:${...}例如前端接收一个user,想取出user的name属性,就可以用变量表达式:

  1. <span th:text="${user.name}">

2、消息表达式:#{...}也称为文本外部化、国际化或i18n.

  1. <p th:text=" #{header.address.city}" >...</p>

3、选择表达式:*{...}与变量表达式的区别:选择表达式是在当前选择的对象上执行而不是整个上下文。

  1. <form action="/users" th:action="@{/users}" method="POST" th:object="${userModel.user}">

  2.   <input type="hidden" name="id" th:value="*{id}">

  3. </form>

这里id就用了选择表达式,在此处 *{id}${userModel.user.id}效果一样。

4、链接表达式:@{...}url可以是相对的,也可以是绝对的。

  1. <a th:href="@{.../users/list}">...</a>

  2. <a th:href="@{http://www.baidu.com}">...</a>

5、分段表达式:th:insert 、th:replace 、th:include就相当插入。这三个的区别: 现有一个片段如下:

  1. <footer th:fragment="copy">

  2.   <h1> Hello Thymeleaf </h1>

  3. </footer>

#号分别代表insert、replace、include进行操作:

  1. <div th:#="footer :: copy"></div>

th:insert 的结果:

  1. <div>

  2.  <footer th:fragment="copy">

  3.     <h1> Hello Thymeleaf </h1>

  4.  </footer>

  5. </div>

把footer标签插入到了div标签中。

th:replace的结果:

  1. <footer th:fragment="copy">

  2.   <h1> Hello Thymeleaf </h1>

  3. </footer>

把div标签换成了footer标签。

th:include的结果:

  1. <div>

  2.   <h1> Hello Thymeleaf </h1>

  3. <div>

把div标签里面的内容换成了footer标签里面的内容。3.X版本后不再推荐使用。

6、字面量:字面量可以是文本、数字、布尔null等类型。

7、算术操作:+、-、*、/、%例如:

  1. <div th:with="isEven=(${user.age} % 2 == 0)">

8、其他运算符:比较: >、\<、>=、\<= (gt、lt、ge、le)等价: ==、!= (eq、ne)三目运算符:

  1. <tr th:class="${row.even} ? 'even' : 'odd' "></tr>

9、迭代器:th:each相当于Java的foreach.

  1. <tr th:each="user : ${userList}">

  2.         <td th:text="${user.id}"></td>

  3.         <td th:text="${user.email}"></td>

  4. </tr>

这样就是遍历userList集合。 迭代器的状态变量有:index、count、size、current、even/odd、first、last

10、条件语句:th:if、th:unless、switch

  1. <div th:switch="${user.role}">

  2.   <p th:case=" 'admin' ">User is admin</p>

  3.   <p th:case=" 'guest' ">User is guest</p>

  4. </div>

11、模板布局:th:fragment比如定义一个公用的页头:

  1. <div th:fragment="header">

  2.   <h1>Thymeleaf in action</h1>

  3.   <a href="/users" >首页</a>

  4. </div>

在其他页面直接这样引用就行:

  1. <div th:replace="~{fragments/header :: header}"></div>

12、表达式基本对象:表达式基本对象有:param、session、application、request、servletContext

三、thymeleaf与springboot集成案例:

本案例使用gradle构建,未涉及数据库,数据保存在ConcurrentMap中。未曾了解gradle的老铁可以参考一下gradle的使用。点我下载本案例源码。项目结构如下:

1、添加依赖:

  1. dependencies {

  2.    compile('org.springframework.boot:spring-boot-starter-web')

  3.    testCompile('org.springframework.boot:spring-boot-starter-test')

  4.    //thymeleaf的依赖

  5.    compile('org.springframework.boot:spring-boot-starter-thymeleaf')

  6. }

2、application.properties:

  1. #thymeleaf相关配置

  2. spring.thymeleaf.encoding=UTF-8

  3. spring.thymeleaf.cache=false

  4. spring.thymeleaf.mode=HTML5

3、entity层:

  1. public class User {

  2.    private Long id;

  3.    private String name;

  4.    private String email;

  5. }

4、dao层:

  1. import java.util.ArrayList;

  2. import java.util.List;

  3. import java.util.concurrent.ConcurrentHashMap;

  4. import java.util.concurrent.ConcurrentMap;

  5. import java.util.concurrent.atomic.AtomicLong;

  6. import org.springframework.stereotype.Repository;

  7. import com.zhu.test.dao.UserDao;

  8. import com.zhu.test.entity.User;

  9. /**

  10. * user dao层实现

  11. * @author zhu

  12. *

  13. */

  14. @Repository

  15. public class UserDaoImpl implements UserDao {

  16.    //用来计数的

  17.    private static AtomicLong counter = new AtomicLong();

  18.    // 用来保存user的map

  19.    private final ConcurrentMap<Long, User> userMap = new ConcurrentHashMap<>();

  20.    @Override

  21.    public User saveOrUpdateUser(User user) {

  22.        Long id = user.getId();

  23.        if(id == null) {//save

  24.            id = counter.incrementAndGet();

  25.            user.setId(id);

  26.        }

  27.        this.userMap.put(id, user);

  28.        return user;

  29.    }

  30.    @Override

  31.    public void deleteUser(Long id) {

  32.        this.userMap.remove(id);

  33.    }

  34.    @Override

  35.    public User getUserById(Long id) {

  36.        return this.userMap.get(id);

  37.    }

  38.    @Override

  39.    public List<User> listUsers() {

  40.        return new ArrayList<User>(this.userMap.values());

  41.    }

  42. }

将user保存在ConcurrentMap中,crud操作其实都是对这个map进行操作。

5、controller层:

  1. @RestController

  2. @RequestMapping("/users")

  3. public class UserController {

  4.    @Autowired

  5.    private UserDao userDao;

  6.    /**

  7.     * 查询所有用户

  8.     *

  9.     * @param model

  10.     * @return

  11.     */

  12.    @GetMapping

  13.    public ModelAndView list(Model model) {

  14.        model.addAttribute("userList", userDao.listUsers());

  15.        model.addAttribute("title", "用户管理");

  16.        return new ModelAndView("user/list", "userModel", model);

  17.    }

  18.    /**

  19.     * 根据id查询用户

  20.     *

  21.     * @param id

  22.     * @param model

  23.     * @return

  24.     */

  25.    @GetMapping("{id}")

  26.    public ModelAndView view(@PathVariable("id") Long id, Model model) {

  27.        User user = userDao.getUserById(id);

  28.        model.addAttribute("user", user);

  29.        model.addAttribute("title", "查看用户");

  30.        return new ModelAndView("user/view", "userModel", model);

  31.    }

  32.    /**

  33.     * 获取创建表单页面

  34.     *

  35.     * @param model

  36.     * @return

  37.     */

  38.    @GetMapping("/form")

  39.    public ModelAndView createForm(Model model) {

  40.        model.addAttribute("user", new User());

  41.        model.addAttribute("title", "创建用户");

  42.        return new ModelAndView("user/form", "userModel", model);

  43.    }

  44.    /**

  45.     * 保存或更新用户

  46.     *

  47.     * @param user

  48.     * @return

  49.     */

  50.    @PostMapping

  51.    public ModelAndView saveOrUpdateUser(User user) {

  52.        user = userDao.saveOrUpdateUser(user);

  53.        return new ModelAndView("redirect:/users");

  54.    }

  55.    /**

  56.     * 删除用户

  57.     *

  58.     * @param id

  59.     * @return

  60.     */

  61.    @GetMapping("/delete/{id}")

  62.    public ModelAndView delete(@PathVariable("id") Long id) {

  63.        userDao.deleteUser(id);

  64.        return new ModelAndView("redirect:/users");// 重定向到list页面

  65.    }

  66.    /**

  67.     * 获取修改用户的界面

  68.     *

  69.     * @param id

  70.     * @param model

  71.     * @return

  72.     */

  73.    @GetMapping("/modify/{id}")

  74.    public ModelAndView modify(@PathVariable("id") Long id, Model model) {

  75.        User user = userDao.getUserById(id);

  76.        model.addAttribute("user", user);

  77.        model.addAttribute("title", "修改用户");

  78.        return new ModelAndView("user/form", "userModel", model);

  79.    }

  80. }

6、前端页面:注意:要使用thymeleaf,需要在html标签中加上

  1. xmlns:th="http://www."

  2.      xmlns:layout="http://www./thymeleaf/layout"

如下页面:页头:header.html

  1. <!DOCTYPE html>

  2. <html xmlns:th="http://www."

  3.      xmlns:layout="http://www./thymeleaf/layout">

  4. <head>

  5. <meta charset="UTF-8">

  6. <title>thymeleaf in action</title>

  7. </head>

  8. <body>

  9. <div th:fragment="header">

  10.   <h1>Thymeleaf in action</h1>

  11.   <a href="/users" >首页</a>

  12. </div>

  13. </body>

  14. </html>

页脚:footer.html

  1. <!DOCTYPE html>

  2. <html xmlns:th="http://www."

  3.      xmlns:layout="http://www./thymeleaf/layout">

  4. <head>

  5. <meta charset="UTF-8">

  6. <title>thymeleaf in action</title>

  7. </head>

  8. <body>

  9. <div th:fragment="footer">

  10.   <a href="#" >邮箱</a>

  11. </div>

  12. </body>

  13. </html>

form.html:

  1. <!DOCTYPE html>

  2. <html xmlns:th="http://www."

  3.      xmlns:layout="http://www./thymeleaf/layout">

  4. <head>

  5. <meta charset="UTF-8">

  6. <title>thymeleaf in action</title>

  7. </head>

  8. <body>

  9. <div th:replace="~{fragments/header :: header}"></div>

  10. <h3 th:text="${userModel.title}">test</h3>

  11. <form action="/users" th:action="@{/users}" method="POST" th:object="${userModel.user}">

  12.   <input type="hidden" name="id" th:value="*{id}">

  13.   名称:<br>

  14.   <input type="text" name="name" th:value="*{name}"><br>

  15.   邮箱:<br>

  16.   <input type="text" name="email"th:value="*{email}">

  17.   <input type="submit" value="提交">

  18. </form>

  19. <div th:replace="~{fragments/footer :: footer}"></div>

  20. </body>

  21. </html>

list.html:

  1. <!DOCTYPE html>

  2. <html xmlns:th="http://www."

  3.      xmlns:layout="http://www./thymeleaf/layout">

  4. <head>

  5. <meta charset="UTF-8">

  6. <title>thymeleaf in action</title>

  7. </head>

  8. <body>

  9. <!-- 引用头部信息 -->

  10. <!-- 在fragments下的header文件下有名为header的片段 -->

  11. <div th:replace="~{fragments/header :: header}"></div>

  12. <h3 th:text="${userModel.title}"></h3>

  13. <div>

  14.   <a href="/users/form.html" th:href="@{/users/form}">创建用户</a>

  15. </div>

  16. <table border="1">

  17.   <thead>

  18.      <tr>

  19.         <td>ID</td>

  20.         <td>Email</td>

  21.         <td>Name</td>

  22.      </tr>

  23.   </thead>

  24.   <tbody>

  25.     <tr th:if="${userModel.userList.size()} eq 0">

  26.         <td colspan="3">没有用户信息</td>

  27.     </tr>

  28.     <tr th:each="user : ${userModel.userList}">

  29.         <td th:text="${user.id}"></td>

  30.         <td th:text="${user.email}"></td>

  31.         <td ><a th:href="@{'/users/'+${user.id}}" th:text="${user.name}"></a></td>

  32.     </tr>

  33.   </tbody>

  34. </table>

  35. <div th:replace="~{fragments/footer :: footer}"></div>

  36. </body>

  37. </html>

view.html:

  1. <!DOCTYPE html>

  2. <html xmlns:th="http://www."

  3.      xmlns:layout="http://www./thymeleaf/layout">

  4. <head>

  5. <meta charset="UTF-8">

  6. <title>thymeleaf in action</title>

  7. </head>

  8. <body>

  9. <div th:replace="~{fragments/header :: header}"></div>

  10. <h3 th:text="${userModel.title}">test</h3>

  11. <div>

  12.   <p><strong>ID:</strong><span th:text="${userModel.user.id}"></span></p>

  13.   <p><strong>Name:</strong><span th:text="${userModel.user.name}"></span></p>

  14.   <p><strong>Email:</strong><span th:text="${userModel.user.email}"></span></p>

  15. </div>

  16. <div>

  17.   <a th:href="@{'/users/delete/'+${userModel.user.id}}">删除</a>

  18.   <a th:href="@{'/users/modify/'+${userModel.user.id}}">修改</a>

  19. </div>

  20. <div th:replace="~{fragments/footer :: footer}"></div>

  21. </body>

  22. </html>

以上页面就涉及到了thymeleaf的常用标签,通过这几个页面,理解thymeleaf的用法。

7、测试效果:

点击“创建用户”:

点击“提交”后:

点击name栏可以进入view页面:

这个页面还可以进行删除和修改,这里不再截图。

总结:

thymeleaf标签看起来很多,其实常用的也不多,且很好理解。主要别忘了在html标签中需要加上 xmlns:th="http://www."xmlns:layout="http://www./thymeleaf/layout"。如果eclipse写thymeleaf标签时没有提示,安装一下thymeleaf插件重启eclipse即可,点击 help-->installnewsoftware,地址为: http://www./eclipse-plugin-update-site/.

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多