使用 Spring Boot 时如何使用 SpringTemplateEngine
Posted
技术标签:
【中文标题】使用 Spring Boot 时如何使用 SpringTemplateEngine【英文标题】:How to use SpringTemplateEngine when using Spring Boot 【发布时间】:2015-05-13 16:11:21 【问题描述】:我正在使用 Thymeleaf SpringTemplateEngine 在我的 Spring 应用程序上创建 html 电子邮件。当我使用纯 Spring MVC 时,一切都很完美。现在使用 Spring Boot,该类找不到我的 .html 模板。我认为问题在于 ServletContext 没有返回正确的路径,但我不知道如何解决它。那么我应该使用另一个上下文来处理模板吗?哪一个?
这是我为纯 Spring MVC 工作的 MailService。
@Service
public class MailService
private JavaMailSenderImpl mailSender;
private SpringTemplateEngine templateEngine;
public MailService()
mailSender = new JavaMailSenderImpl();
//mailSender config
templateEngine = new SpringTemplateEngine();
Set<ITemplateResolver> templatesResolvers = new HashSet<ITemplateResolver>();
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("mail/");
emailTemplateResolver.setTemplateMode("HTML5");
emailTemplateResolver.setCharacterEncoding("UTF-8");
emailTemplateResolver.setOrder(1);
templatesResolvers.add(emailTemplateResolver);
ServletContextTemplateResolver webTemplateResolver = new ServletContextTemplateResolver();
webTemplateResolver.setPrefix("/mail/");
webTemplateResolver.setTemplateMode("HTML5");
webTemplateResolver.setCharacterEncoding("UTF-8");
webTemplateResolver.setOrder(2);
templatesResolvers.add(webTemplateResolver);
templateEngine.setTemplateResolvers(templatesResolvers);
public void sendReport(String nome, String email, String obra,
long medicao, HttpServletRequest request,
HttpServletResponse response, ServletContext context, Locale locale)
throws MessagingException
String subject = "Novo relatório";
final WebContext ctx = new WebContext(request, response, context,
locale);
ctx.setVariable("nome", nome);
ctx.setVariable("obra", obra);
ctx.setVariable("data", DataUtils.getInstance().getDataString(medicao));
ctx.setVariable("logo", "logo.jpg");
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
true, "UTF-8");
message.setSubject(subject);
try
message.setFrom(new InternetAddress(mailSender.getUsername(),
"Sistema"));
catch (UnsupportedEncodingException e)
message.setTo(email);
final String htmlContent = this.templateEngine.process(
"email-relatorio.html", ctx);
message.setText(htmlContent, true);
try
File file = new File(context.getRealPath("app/img/logo-pro.jpg"));
InputStreamSource imageSource = new ByteArrayResource(
IOUtils.toByteArray(new FileInputStream(file)));
message.addInline("logo.jpg", imageSource, "image/jpg");
catch (IOException e)
e.printStackTrace();
this.mailSender.send(mimeMessage);
错误:
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "email-relatorio.html", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:924)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:898)
【问题讨论】:
【参考方案1】:您正在使用 Spring Boot,然后让 Spring Boot 完成繁重的工作,它已经完成了。删除您的构造函数,只需 @Autowire
JavaMailSender
和 SpringTemplateEngine
。
将邮件配置添加到application.properties
。
spring.mail.host=your-mail-server
spring.mail.port=
spring.mail.username
spring.mail.password
将百里香叶配置添加到 application.properties
# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.excluded-view-names= # comma-separated list of view names that should be excluded from resolution
spring.thymeleaf.view-names= # comma-separated list of view names that can be resolved
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added
spring.thymeleaf.cache=true # set to false for hot refresh
如果你这样做了,请改变你的班级
@Service
public class MailService
@Autowired
private JavaMailSender mailSender;
@Autowired
private SpringTemplateEngine templateEngine;
@Value("$spring.mail.username")
private String username;
public void enviarRelatorio(String nome, String email, String obra,long medicao, Locale locale) throws MessagingException
String subject = "Novo relatório";
final Context ctx = new Context(locale);
ctx.setVariable("nome", nome);
ctx.setVariable("obra", obra);
ctx.setVariable("data", DataUtils.getInstance().getDataString(medicao));
ctx.setVariable("logo", "logo.jpg");
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true, "UTF-8");
message.setSubject(subject);
message.setTo(email);
try
message.setFrom(new InternetAddress(username, "Sistema"));
catch (UnsupportedEncodingException e)
final String htmlContent = this.templateEngine.process( "email-relatorio", ctx);
message.setText(htmlContent, true);
try
message.addInline("logo.jpg", new FileSystemResource("imgs/logo-pro.jpg"), "image/jpg");
catch (IOException e)
e.printStackTrace();
this.mailSender.send(mimeMessage);
【讨论】:
嗨!我现在正在使用 application.properties。但是,前缀“classpath:/templates/”会引发相同的错误,如果我设置为“templates/”,ThymeleafAutoConfiguration 会引发“找不到模板位置:模板/(请添加一些模板或检查您的 Thymeleaf 配置)”。我的文件在 src/main/resources/templates 中。我错过了什么? 算了。问题是因为我传递了文件的全名,但是有一个后缀。使用 getUsername 时,请将“email-relatorio.html”更改为“email-relatorio”,并将 JavaMailSender 转换为 JavaMailSenderImpl。谢谢! 您不应该强制转换或使用getUsename
,只需使用基于@Value
的属性注入属性即可。查看修改后的代码。由于 AOP 可用,转换可能会出现问题,因此您无法转换为 JavaMailSenderImpl
,而只能转换为接口。接下来,您应该对接口而不是具体类进行编程....此外,src/main/resources/templates
是默认位置,因此您无需对其进行配置。以上是关于使用 Spring Boot 时如何使用 SpringTemplateEngine的主要内容,如果未能解决你的问题,请参考以下文章