Maven依赖
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.0.11.RELEASE</version> </dependency>
封装Util
package cn.xiaohei; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; public class ThUtils { private static TemplateEngine te; static { te = new TemplateEngine(); ClassLoaderTemplateResolver r = new ClassLoaderTemplateResolver(); r.setCharacterEncoding("utf-8"); te.setTemplateResolver(r); } /** * * @param fileName html文件名 * @param context 上下文对象 * @param response HttPResponse */ public static void print(String fileName,Context context,HttpServletResponse response) { //将容器里面的数据和页面整合在一起 String html = te.process(fileName, context); //将得到的新的HTML返回给客户端 response.setContentType("text/html;charset=utf-8"); PrintWriter pw =null; try { pw = response.getWriter(); } catch (IOException e) { e.printStackTrace(); } pw.print(html); pw.close(); } }
使用
注意:需要使用的thymeleaf的HTML文件要放在resource文件夹中,如下图:
添加与获取
Context对象时上下文对象,用于存储用传递的数据。在Servlet中添加,在HTML页面中获取。
字符串对象
-
- //添加
- context.setVariable("数据名",字符串类容);
- //获取
- 获取文本类型
- <li th:text=${数据名}></li>
- 获取可编译为HTML代码的格式:如<b>你好</b> 读取后“你好”将被加粗
- <li th:utext=${数据名}></li>
- 获取文本类型
- //添加
任意类型的对象数据
- //添加
- context.setVariable("数据名",对象);
- //取数据
- <li th:text=${数据名.属性名}></li>
集合数据
- //遍历取集合数据
<ul th:each="p:${list}"> //p为遍历用的对象,可任意名。list为添加到context容器时的集合名
<li th:text=${p.name}></li> //获取对象的属性数据
</ul>
- 注意:th:each 和 th:text 无需分别写在父子标签中,可写在同一个标签中
替换a标签的href值
- <a th:href="'ck?id='+${name}">点我</a> 他表示将a标签的href值赋为:“ck?id=跟上${name}的值”
替换input标签的value值
- <input th:value=${name}>
示例:
添加字符串数据示例。
添加:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = "虞姬"; response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); //创建上下文对象可以理解为装数据的容器 Context context = new Context(); context.setVariable("name", name); //把容器里面的数据替换到模板页面中 ThUtils.print("th1.html", context, response); }
获取数据
下面两个li标签的内容都会被替换为“虞姬”。
<li th:text=${name}></li> <li th:text=${name}>我将被虞姬替换</li>