如何强制我的模板解析器使用ClassLoaderTemplateResolver for / mail / * templates

时间:2017-05-16 06:42:21

标签: java spring-mvc spring-boot thymeleaf

我在Spring Boot Application ServletContextTemplateResolver和ClassLoaderTemplateResolver中使用了两个模板解析器。

我正在为我的网页使用ServletContextTemplateResolver for / WEB-INF / * html模板。另一方面,我将使用ClassLoaderTemplateResolver作为我的/ mail / html模板。这是代码:

@Bean(name ="templateResolver") 
public ServletContextTemplateResolver getTemplateResolver() {
    ServletContextTemplateResolver templateResolver = new 
    ServletContextTemplateResolver();
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("XHTML");
    templateResolver.setOrder(Integer.valueOf(1));
    return templateResolver;
}

@Bean(name ="emailTemplateResolver")    
public ClassLoaderTemplateResolver getEmailTemplateResolver() {
    ClassLoaderTemplateResolver templateResolver = new 
    ClassLoaderTemplateResolver();
    templateResolver.setOrder(Integer.valueOf(2));
    templateResolver.setPrefix("/mail/");
    templateResolver.setSuffix(".html");
    return templateResolver;
}

调用邮件模板时显示以下错误:

  

ServletContext的资源解析   org.thymeleaf.resourceresolver.ServletContextResourceResolver只能   在context实现org.thymeleaf.context.IWebContext时执行   [当前上下文:org.thymeleaf.context.Context]

如何强制它为/ mail / *模板使用ClassLoaderTemplateResolver?

1 个答案:

答案 0 :(得分:0)

您可能正在呈现一个html文件,并希望将生成的html文件保存在字符串变量中,稍后您将使用html转换为pdf。因此,以下代码将帮助您进行Spring启动:

@Controller
public class jataController {

    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping(value = "/manual-thym")
    @ResponseBody
    public void justSample() {
        Context context = new Context();
        String filename = "templates/view/generated-ticket.html";
        String html = renderHtml(filename, context);
        System.out.println("template\n" + html);
    }

    private String renderHtml(String filename, Context context) {

        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(false);
        templateResolver.setOrder(1);
        templateResolver.setCharacterEncoding("UTF-8");

        templateEngine.setTemplateResolver(templateResolver);

        String html = templateEngine.process(filename, context);

        return html;
    }
}