zoukankan      html  css  js  c++  java
  • 使用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样式

  • 相关阅读:
    oracle 自增序列实现 可作为主键
    oracle 10 升级补丁
    软件设计原则
    oracle查询截至到当前日期月份所在年份的所有月份
    Dockerfile 基本命令
    Mybatis自动生成代码,MyBatis Generator
    Java垃圾回收机制
    SqlServer 导入 .sql 文件
    备份个清库脚本
    备份一些开发配置
  • 原文地址:https://www.cnblogs.com/li-zhi-long/p/11687062.html
Copyright © 2011-2022 走看看