使用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. 生成代码的用法.
随机推荐
- lnmp环境搭建(Ubuntu)
dpkg -l | grep gcc ubuntu系统查看已安装的包 dpkg -S nginx 查看安装的nginx apt-get update 首先更新 ...
- input 唤起键盘后遮住页面元素
var windheight = $(window).height(); /*未唤起键盘时当前窗口高度*/ $(window).resize(function(){ var docheight = $ ...
- noi.ac #553 序列
[题目描述] 老虎和蒜头是好朋友. 众所周知,蒜头经常给老虎出一些题目,而老虎也常常被难倒,作为捧杯之王的老虎难免心有怨怼.今天,老虎发现了蒜头的一个序列 a .虽然老虎不知道这个序列是用来做什么的 ...
- getFieldDecorator用法(三)——Table增删改
后台管理系统常用到表单的增删改,这里也做了个封装 例如:user/index.js import React from 'react' import { Card, Button, Table, Fo ...
- Maximum upload size exceede上传文件大小超出解决
在这里记录三种方法, 努力提高自己的姿势水平 application.yml配置 spring: servlet: multipart: enabled: true max-file-size: 10 ...
- Java file.encoding
1. file.encoding属性的作用 file.encoding 的值是整个程序使用的编码格式. 可以使用 System.out.println(System.getProperty(&quo ...
- 6 Java Shell排序
希尔排序是先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录“基本有序”时,再对全体记录进行依次直接插入排序. 1.基本思想 将待排序数组按照步长gap进行分组,然后将 ...
- Fastadmin 写关联命名时,最好前后台用同一个model,方便管理(会出现命名空间问题)
1.php think crud -t test --relation=category(外键表1) --relation=admin(外键表2) --relationforeignkey=categ ...
- oracle表结构表数据导入导出
--------------------------------------imp/exp------------------------------------------------------- ...
- koa 项目实战(三)创建测试接口和用户模型
1.创建测试接口,并引入用户模型 根目录/routes/api/users.js const Router = require('koa-router'); const router = new Ro ...