使用Themleaf 模板引擎手动生成html文件
1.为什么要写这一篇呢?
在做一个邮件发送功能的时候,需要发送html邮件,javaMail 发送html 的时候需要有已经生成的html正文,所以需要提前将要发送的内容生成,所以就需要模板引擎来动态填充数据。
public void sendHtmlEmail(String to, String object, String content) {
MimeMessage message = mailSender.createMimeMessage();//创建一个MINE消息 try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(object);
helper.setText(content, true); mailSender.send(message);
log.info("html邮件发送成功");
} catch (MessagingException e) {
log.error("发送html邮件时发生异常!", e);
}
}
2.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
ognl 的jar包可能并不需要,在生成过程中报classNotFound ,应该是和我的项目结构有关系,这个包根据实际情况来使用
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.2</version>
</dependency>
3.代码
(1)首先准备一个html模板,需要替换的内容使用themleaf的th表达式来占位。我的工程是springboot 项目,文件位置放在resources/templates,也就是classpath:templates/
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<html>
<head>
<title>Title</title>
<style type="text/css">
td{
width: 80px;
height: 25px;
align-content: center;
}
</style>
</head>
<body>
<h4>亲爱的<span th:text="${name}"></span>,您<span th:text="${month}"></span>月份的工资如下:</h4>
<table border="1" style="border-collapse: collapse" >
<tr>
<td th:each="item:${th}" th:text="${item}"></td>
</tr>
<tr>
<td th:each="ib:${tb}" th:text="${ib}"></td>
</tr>
</table>
</body>
</html>
2.配置模板引擎
@Configuration
public class MailConfig { @Bean("myTemplateEngine")
public TemplateEngine templateEngine(){
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/");
resolver.setSuffix(".html");
TemplateEngine engine = new TemplateEngine();
engine.setTemplateResolver(resolver);
return engine;
}
}
为手动生成html文件单独定义一个模板引擎,其他的使用默认配置。其中制定了模板文件的位置及后缀名,这个配置和application.properties 中配置是一样的
3.生成html
@PostMapping("/sendEmail")
@ResponseBody
public AjaxResult sendEmail(Integer id) throws IOException {
List<ComponentVo> componentVos = salaryCompnentService.selectComponentSum(id);
List<String> th = Lists.newArrayList();
List<String> tb = Lists.newArrayList();
for (int i = 0; i < componentVos.size(); i++) {
ComponentVo vo = componentVos.get(i);
th.add(i, vo.getName());
tb.add(i, vo.getAmount());
}
SalaryCalculateVo salaryCalculate = salaryService.selectSalaryById(id);
Context context = new Context();
context.setVariable("name", salaryCalculate.getEmpName());
context.setVariable("month", salaryCalculate.getWorkMonth());
context.setVariable("th", th);
context.setVariable("tb", tb); String res = engine.process("mailTeamlate", context);
salaryService.sendEmail(id,res, salaryCalculate.getWorkMonth() + "工资条", salaryCalculate.getEmail());
return toAjax(1);
}
由于是测试功能,没有在代码结构上下功夫,随便写一下。主要的代码是王模板上下文Context中填充参数,engine.process()有很多重载的方法,主要有两类,一类是直接输出内容,一类是将文件输出到指定文件里。String template 这个参数指的是模板的名称。比如我的叫mailTeamlate,解析的时候模板引擎会找classpath:templates/mailTeamlate.html 这个文件。
public final String process(String template, IContext context) {
return this.process(new TemplateSpec(template, (Set)null, (TemplateMode)null, (String)null, (Map)null), context);
}
public final void process(String template, IContext context, Writer writer) {
this.process(new TemplateSpec(template, (Set)null, (TemplateMode)null, (String)null, (Map)null), context, writer);
}
4.效果
具体的文件内容就不说了,直接看我放到邮件的里面正文里的html样式
使用Themleaf 模板引擎手动生成html文件的更多相关文章
- SpringBoot获取Freemarker模板引擎,生成HTML代码
今天用Ajax异步添加评论,加载Freemarker模板引擎,生成模板模块 1.新建Freemarker模板 <li id="${comment.oId}"> < ...
- 使用 Velocity 模板引擎快速生成代码(zhuan)
http://www.ibm.com/developerworks/cn/java/j-lo-velocity1/ ****************************************** ...
- 使用Velocity 模板引擎快速生成代码
Velocity 模板引擎介绍 在现今的软件开发过程中,软件开发人员将更多的精力投入在了重复的相似劳动中.特别是在如今特别流行的MVC架构模式中,软件各个层次的功能更加独立,同时代码的相似度也更加高. ...
- 使用VTemplate模板引擎动态生成订单流程图
1.VTemplate模板引擎的简介 VTemplate模板引擎也简称为VT,是基于.NET的模板引擎,它允许任何人使用简单的类似HTML语法的模板语言来引用.NET里定义的对象.当VTemplate ...
- Java使用 VelocityEngine模板引擎快速生成HTML等各种代码
https://blog.csdn.net/icannotdebug/article/details/79725297 一.简介 Velocity 是一个基于 Java 的模板引擎框架,提供的模板语言 ...
- 手动生成moc文件
在VS中写Qt项目时,手动添加了一个类,由于要用到信号槽,所以需要生成相应的moc文件.写好信号槽以后,在类里面第一行应该写上Q_OBJECT关键字,编译项目会提示无法找到moc_XXX.cpp文件. ...
- 由动态库文件dll生成lib库文件(手动生成.def文件,然后使用lib命令编译,非常牛),同理可使用dll生成.a库文件
本文基于OpenBlas的编译和安装,来说明如何从一个dll文件生成lib库文件. 参考OpenBlas的说明“Howto generate import library for MingW”,和Mi ...
- WebApi中利用Razor模板引擎来生成html
在服务器端基于Razor来生成html的一个思路 using System.Web.Mvc; using System.IO; using System.Web.Routing; using Syst ...
- 转: 使用 Velocity 模板引擎快速生成代码
from:https://www.ibm.com/developerworks/cn/java/j-lo-velocity1/ 评注: 1. velocity 的基本语法 2. 生成代码的用法.
随机推荐
- flask框架(十): 闪现
一:闪现flash基本用法 # -*- coding: utf-8 -*- # @Author : Felix Wang # @time : 2018/7/5 9:34 from flask impo ...
- epplus动态合并列数据
private static void SetColMerge(DataTable tb, ExcelWorksheet worksheet, string dtColumnName) { KeyVa ...
- Spring Boot教程(三十七)整合MyBatis
Spring中整合MyBatis就不多说了,最近大量使用Spring Boot,因此整理一下Spring Boot中整合MyBatis的步骤.搜了一下Spring Boot整合MyBatis的文章,方 ...
- [c++] C++中public、protected、private的区别
转:https://blog.csdn.net/vanturman/article/details/79393317 第一: private,public,protected的访问范围: privat ...
- PHP-异常-1
PHP 错误处理 在 PHP 中,默认的错误处理很简单.一条消息会被发送到浏览器,这条消息带有文件名.行号以及一条描述错误的消息. 在创建脚本和 web 应用程序时,错误处理是一个重要的部分.如果您的 ...
- 如何评价深度学习框架Keras?
python机器学习-乳腺癌细胞挖掘(博主亲自录制视频)https://study.163.com/course/introduction.htm?courseId=1005269003&ut ...
- WebStrom编程小技巧--HTML快速创建指定id或者类名的div
打印div标签快速方法:“先打出#yz,然后Tab键补全即可获得<div id="yz"></div>同理:我们也可以先打出“.tz"然后Tab键 ...
- 设计模式--观察者模式--python
观察者模式: 对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新. 主要解决: 当一个抽象模型有两个方面, 其中一个方面依赖于另一方面.将这二者封装在 ...
- LC 965. Univalued Binary Tree
A binary tree is univalued if every node in the tree has the same value. Return true if and only if ...
- [Python]切换工作目录|python将目录切换为脚本所在目录
Python使用os.chdir命令切换python工作目录 代码示例: In []: import os In []: os.system("pwd") /home/wangju ...