Thymeleaf 学习笔记

目录

概述

物理视图和逻辑视图

thymeleaf入门

thymeleaf修改标签内容

thymeleaf修改标签属性

thymeleaf解析url

thymeleaf操作域对象

thymeleaf条件渲染

 thymeleaf分支渲染

thymeleaf列表渲染


概述

  • Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker 等, 它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。它的主要作用 是在静态页面上渲染显示动态数据
  • 特点

    • SpringBoot官方推荐使用的视图模板技术,和SpringBoot完美整合。

物理视图和逻辑视图

概述

  • 物理视图:请求转发到一个资源时使用的绝对路径

  • 逻辑视图:物理视图=视图前缀+逻辑视图+视图后缀

    • 视图前缀:物理视图中最大的公共前缀

    • 视图后缀:物理视图中最大的公共后缀

  • 举例

thymeleaf入门

开发步骤

  • ①引入thymeleaf的相关jar包

  • ②编写web.xml

    • 配置视图前缀

    • 配置视图后缀

  • ③定义ViewBaseServlet类

  • ④定义Servlet类继承ViewBaseServlet类

  • ⑤编写html页面

    • 使用thymeleaf渲染页面

<!--视图前缀-->
<context-param>
    <param-name>view-prefix</param-name>
    <param-value>/pages/</param-value>
</context-param>

<!--视图后缀-->
<context-param>
    <param-name>view-suffix</param-name>
    <param-value>.html</param-value>
</context-param>

定义ViewBaseServlet类

public class ViewBaseServlet extends HttpServlet {
    private TemplateEngine templateEngine;

    @Override
    public void init() throws ServletException {

        // 1.获取ServletContext对象
        ServletContext servletContext = this.getServletContext();

        // 2.创建Thymeleaf解析器对象
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);

        // 3.给解析器对象设置参数
        // ①HTML是默认模式,明确设置是为了代码更容易理解
        templateResolver.setTemplateMode(TemplateMode.HTML);

        // ②设置前缀
        String viewPrefix = servletContext.getInitParameter("view-prefix");

        templateResolver.setPrefix(viewPrefix);

        // ③设置后缀
        String viewSuffix = servletContext.getInitParameter("view-suffix");

        templateResolver.setSuffix(viewSuffix);

        // ④设置缓存过期时间(毫秒)
        templateResolver.setCacheTTLMs(60000L);

        // ⑤设置是否缓存
        templateResolver.setCacheable(true);

        // ⑥设置服务器端编码方式
        templateResolver.setCharacterEncoding("utf-8");

        // 4.创建模板引擎对象
        templateEngine = new TemplateEngine();

        // 5.给模板引擎对象设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);

    }


    /**
     * 执行视图
     * @param templateName : 逻辑视图
     * @param req : 请求
     * @param resp : 响应
     * @throws IOException
     */
    protected void processTemplate(String templateName, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 1.设置响应体内容类型和字符集
        resp.setContentType("text/html;charset=UTF-8");

        // 2.创建WebContext对象
        WebContext webContext = new WebContext(req, resp, getServletContext());

        // 3.处理模板数据
        templateEngine.process(templateName, webContext, resp.getWriter());
    }
}

定义Servlet类继承ViewBaseServlet类

@WebServlet("/demo01")
public class Demo01Servlet extends ViewBaseServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String errorMsg = "用户名已经存在!";
        req.setAttribute("errorMsg", errorMsg);
        //转发到demo01.html
        processTemplate("demo01", req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

编写html页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>04-thymeleaf入门</title>
</head>
<body>

<font color="red" th:text="${errorMsg}"></font>

</body>
</html>
  • 注意事项

    • 如果要使用thymeleaf指令,必须要通过ViewBaseServlet

thymeleaf修改标签内容

  • 概述

    • 使用th:text指令修改标签内容

  • 代码实现

@WebServlet("/demo02")
public class Demo02Servlet extends ViewBaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String msg = "helloworld";
        request.setAttribute("msg", msg);
        processTemplate("demo02", request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>05-thymeleaf修改标签内容</title>
</head>
<body>

<span th:text="${msg}"></span>

</body>
</html>

thymeleaf修改标签属性

  • 概述

    • 使用"th:属性"修改标签的属性值

  • 代码实现

@WebServlet("/demo03")
public class Demo03Servlet extends ViewBaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String msg = "helloworld";
        request.setAttribute("msg", msg);
        processTemplate("demo03", request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>06-thymeleaf修改标签属性</title>
</head>
<body>

<input type="text" th:value="${msg}">
<a th:href="${msg}">超链接</a>


</body>
</html>

thymeleaf解析url

1.无参

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>07-thymeleaf解析url</title>

    <!--不带参数的URL-->
</head>
<body>

<a href="/day06/demo04">请求Demo04Servlet</a>

<a th:href="@{/demo04}">请求Demo04Servlet</a>


</body>
</html>

2.有参

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>07-thymeleaf解析url</title>

    <!--不带参数的URL-->
</head>
<body>

<a href="/day06/demo05?msg=aaa&msg2=bbb">请求Demo04Servlet</a>
<a th:href="@{/demo05(msg=aaa,msg2=bbb)}">请求Demo04Servlet</a>

</body>
</html>

thymeleaf操作域对象

域对象

  • ServletRequest

  • HttpSession

  • ServletContext

@WebServlet("/demo06")
public class Demo06Servlet extends ViewBaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //当前请求有效
        request.setAttribute("msg1","request");
        //当前会话有效
        request.getSession().setAttribute("msg2","session");
        //当前项目有效
        getServletContext().setAttribute("msg3","servletContext");
        processTemplate("demo06",request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>08-thymeleaf操作域对象</title>
</head>
<body>

<span th:text="${msg1}"></span>
<span th:text="${session.msg2}"></span>
<span th:text="${application.msg3}"></span>


</body>
</html>

thymeleaf条件渲染

概述

  • 使用th:if、th:unless指令来进行条件渲染。

@WebServlet("/demo08")
public class Demo08Servlet extends ViewBaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean flag = false;
        request.setAttribute("flag", flag);
        processTemplate("demo08", request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>11-thymeleaf条件渲染</title>
</head>
<body>


<span th:if="${flag}">
    这是一个span if
</span>

<span th:unless="${flag}">
    这是一个span  unless
</span>



</body>
</html>

 thymeleaf分支渲染

概述

  • 使用th:swtich、th:case指令进行分支渲染

@WebServlet("/demo01")
public class Demo01Servlet extends ViewBaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String role = "super";
        request.setAttribute("role", role);
        processTemplate("demo01", request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>01-thymeleaf分支渲染</title>
</head>
<body>


<span th:switch="${role}">

    <span th:case="super">超级管理员</span>
    <span th:case="admin">管理员</span>
    <span th:case="user">用户</span>

</span>



</body>
</html>

thymeleaf列表渲染

概述

  • 使用th:each进行列表渲染,类似于vue中的v-for

@WebServlet("/demo02")
public class Demo02Servlet extends ViewBaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "张聚义", "root"));
        userList.add(new User(2, "敬镇源", "admin"));
        userList.add(new User(3, "李世鑫", "12345"));
        request.setAttribute("userList", userList);
        processTemplate("demo02", request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>02-thymeleaf列表渲染</title>
</head>
<body>

<table border="1px" rules="all" cellspacing="0px" cellpadding="10px" width="400px" height="300px">

    <tr>
        <td>状态</td>
        <td>编号</td>
        <td>姓名</td>
        <td>密码</td>
    </tr>

    <tr th:each="user ,state : ${userList}">
        <td th:text="${state.index}"></td>
        <td th:text="${user.userId}">编号</td>
        <td th:text="${user.userName}">姓名</td>
        <td th:text="${user.userPwd}">密码</td>
    </tr>

</table>


</body>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值