Spring Boot 使用Thymeleaf模板引擎解析模板内容

       在我们系统开发中,常常会遇到样式格式一致但内容不一致的页面,比如用户注册后发送的用户激活邮件,找回密码邮件(html格式邮件)以及商品详情页等,先看看邮件发送服务API:

@Service  
public class EmailServiceImpl implements EmailService {  
    @Autowired private JavaMailSender mailSender;  
    @Override @Async  
    public void sendSimpleEmail(String sendTo, String subject, String content) {  
        SimpleMailMessage mailMessage = new SimpleMailMessage();  
        mailMessage.setFrom("");//发件人  
        mailMessage.setTo(sendTo);//收件人  
        mailMessage.setSubject(subject);//邮件主题  
        mailMessage.setText(content);//邮件内容  
        mailSender.send(mailMessage);//发送该邮件  
    }  
  
    @Override @Async  
    public void sendMimeMessageSend(String sendTo, String subject, String content) {  
        MimeMessage message = mailSender.createMimeMessage();  
        try {  
            MimeMessageHelper helper = new MimeMessageHelper(message,true,"UTF-8");  
            helper.setFrom("");  
            helper.setTo(sendTo);  
            helper.setSubject(subject);  
            helper.setText(content,true);  
            mailSender.send(message);  
        } catch (MessagingException e) {  
            e.printStackTrace();  
        }  
    }  
}  

   当用户注册成功后我们需要给用户发送一封账号激活邮件


  上面激活邮件中(很明显是一封HTML格式的邮件),除了红色框住的部分(动态渲染部分),其余部分内容样式都是一样的,针对这样的内容,我们一般做成一个公共模板,动态内容通过添加给模板的context使用thymeleaf的表达式进行获取渲染,现摘取出动态渲染部分:

<span class="cntext" th:inline="text" th:inline="text">[[${user.username}]]</span><br>  
 &nbsp; &nbsp; &nbsp; &nbsp; 您好!感谢您对XXX的信任与支持!<br>&nbsp; &nbsp;  
  
<span class="cntext">&nbsp; <strong>点击下面链接激活账号</strong></span><br/>  
   <a th:href="@{http://192.168.138.128/portal/user/active(username=${user.username}&code=${user.password})}"  
      th:text="|http://192.168.138.128/portal/user/active?username=${user.username}&code=${user.password}|">  
   </a>  
<br/>  

       在发送邮件时不能直接发送html(模板)文件,需要将模板渲染后解析成字符串内容进行发送,如何解析呢,springboot中添加spring-boot-starter-thymeleaf依赖后,springboot会自动注入

SpringResourceTemplateResolver(模板解析器),SpringTemplateEngine(模板引擎),ThymeleafViewResolver(thymeleaf视图解析器)等对象,

我们使用模板引擎就可以将模板解析成字符串以及生成文件等

@Service  
@Transactional  
public class BuyerServiceImpl implements BuyerService {  
    @Autowired private BuyerRepository repository;  
    @Autowired private EmailService emailService;  
    @Autowired private TemplateEngine templateEngine;  
    @Override  
    public void registe(Buyer buyer) {  
        //用户名不存在  
        if (!checkUsername(buyer.getUsername())) {  
            //MD5加密  
            buyer.setPassword(MD5.MD5Encode(buyer.getPassword()));  
            repository.save(buyer);  
  
            //解析邮件模板并绑定变量参数  
            var context = new Context();  
            context.setVariable("user", buyer);  
            var content = templateEngine.process("mailContent", context);  
            //异步发送电子邮件  
            emailService.sendMimeMessageSend(buyer.getEmail(), "账户激活", content);  
        }  
    }  
}  

 生成新的文件,如商品详情页需要生成详情页的静态html文件,只需指定特定的writer就可以了,比如

var realpath = servletContext.getRealPath("/product");  
var file = new File(realpath);  
if(!file.exists()) file.mkdirs();  
var htmlFile = new File(file,info.getCode() + ".html");  
//productview为模板名称  
templateEngine.process("productview",context,new FileWriter(htmlFile));

 就会在自己的容器中指定位置生成相应的html文件,当然这个就不能使用springboot默认提供的容器,我们需要对器进行排除

Java代码  

providedCompile("org.springframework.boot:spring-boot-starter-tomcat:2.0.3.RELEASE")  

 排除后我们的war部署在指定的服务器中,服务器需要启动spring boot

/** 
 * 修改启动类,继承 SpringBootServletInitializer 并重写 configure 方法 
 */  
public class SpringBootStartApplication extends SpringBootServletInitializer {  
    @Override  
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {  
        // 注意这里要指向原先用main方法执行的Application启动类  
        return builder.sources(ItemApplication.class);  
    }  
}  
  
@SpringBootApplication  
public class ItemApplication {  
    public static void main(String[] args) {  
        SpringApplication.run(ItemApplication.class,args);  
    }  
}  
posted @ 2022-06-15 16:55  Tiger-Adan  阅读(717)  评论(0编辑  收藏  举报