org.thymeleaf.templatemode.StandardTemplateModeHandlers无法解析

时间:2019-05-30 12:43:26

标签: java spring-boot thymeleaf

在Spring Boot API中,我需要使用Thymeleaf发送电子邮件。因此,我选择了this教程。但是,在添加 ThymeleafConfig.java 时,STS会引发以下错误。

  

导入org.thymeleaf.templatemode.StandardTemplateModeHandlers   无法解决

this回答中所述,我将依存关系更改如下,但是并不能解决问题。

<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>
  <version>3.0.11.RELEASE</version>
</dependency>

<dependency>
  <groupId>nz.net.ultraq.thymeleaf</groupId>
  <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>

ThymeleafConfig.java

import java.nio.charset.StandardCharsets;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//following import is not resolved
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;


@Configuration
public class ThymeleafConfig {

  @Bean
  public ClassLoaderTemplateResolver htmlTemplateResolver(){
    ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
    emailTemplateResolver.setPrefix("/templates/");
    emailTemplateResolver.setSuffix(".html");
      emailTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.HTML5.getTemplateModeName());
    emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
    return emailTemplateResolver;
 }
}

1 个答案:

答案 0 :(得分:1)

使用TemplateMode代替StandardTemplateModeHandlers

import org.thymeleaf.templatemode.TemplateMode;

    @Bean
    public SpringResourceTemplateResolver htmlTemplateResolver(){
        SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
        emailTemplateResolver.setPrefix("classpath:/templates/");
        emailTemplateResolver.setSuffix(".html");
        emailTemplateResolver.setTemplateMode(TemplateMode.HTML);
        emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        return emailTemplateResolver;
    }

在HTML模板中,使用th:text

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
 <p th:text="${name}">
</body>
</html>

在处理模板时,请使用thymeleaf的TemplateEngine

 import org.thymeleaf.TemplateEngine; 

   @Autowired
    private TemplateEngine templateEngine;

       Context context = new Context();
            context.setVariables(mail.getModel());
            String html = templateEngine.process("email-template", context);