java 使用 Spring Boot 时如何使用 SpringTemplateEngine

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28993936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:31:17  来源:igfitidea点击:

How to use SpringTemplateEngine when using Spring Boot

javajavamailspring-bootthymeleaf

提问by rcorreia

I am using Thymeleaf SpringTemplateEngine to create a HTML e-mail on my Spring application. When I was using pure Spring MVC everything was perfect. Now with Spring Boot the class can't find my .html template. I think the problem is with ServletContext that is not returning the right path, but I can't figure out how to resolve it. So should I use another Context to process the template? Which one?

我正在使用 Thymeleaf SpringTemplateEngine 在我的 Spring 应用程序上创建一个 HTML 电子邮件。当我使用纯 Spring MVC 时,一切都很完美。现在使用 Spring Boot,该类无法找到我的 .html 模板。我认为问题在于 ServletContext 没有返回正确的路径,但我不知道如何解决它。那么我应该使用另一个 Context 来处理模板吗?哪一个?

This is my MailService working for pure Spring MVC.

这是我为纯 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);
    }
}

The error:

错误:

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)

回答by M. Deinum

You are using Spring Boot then let Spring Boot do the heavy lifting, which it already does. Remove your constructor and simply @Autowirethe JavaMailSenderand SpringTemplateEngine.

您正在使用 Spring Boot,然后让 Spring Boot 完成它已经完成的繁重工作。删除您的构造函数和简单@AutowireJavaMailSenderand SpringTemplateEngine

Add the mail configuration to the application.properties.

将邮件配置添加到application.properties.

spring.mail.host=your-mail-server
spring.mail.port=
spring.mail.username
spring.mail.password

Add the thyme leaf configuration to the application.properties

将百里香叶配置添加到 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

If you have done that change your class

如果你这样做了,改变你的班级

@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);
    }
}