解决css链接Thymeleaf外部项目

时间:2016-11-09 02:37:51

标签: java html spring spring-boot thymeleaf

我正在制作一个小框架,用于发送要在社区中使用的电子邮件。在此框架中,可以发送预定义的电子邮件。要使用Thymeleaf解析HTML文件(在我的外部.jar项目中),我使用以下代码:

//Here I build a specific Template Resolver (FileTemplateResolver) and add it to the 
//SpringTemplateEngine already created (by Spring Boot) with the lowest priority,
//to resolve the HTML files that are in my external project in
//resources / templates / mailTemplates / templatesPreDefined.
@PostConstruct
public void customTemplateResolver(){

    try {

        templateEngine.addTemplateResolver(getTemplateResolver());

    } catch (Exception e) {

        LOGGER.debug("Não foi possível definir um template resolver customizado para que seja utilizado"
                + " os templates pré definidos.", e);

    }

}

private ITemplateResolver getTemplateResolver() throws CustomTemplateResolverException {

    FileTemplateResolver resolver = new  FileTemplateResolver();

    resolver.setPrefix(getPrefixTemplateResolver());        
    resolver.setSuffix(".html");
    resolver.setTemplateMode("HTML5");
    resolver.setCharacterEncoding("UTF-8");
    resolver.setCacheable(false);
    resolver.setOrder(Ordered.LOWEST_PRECEDENCE);

    return resolver;
}

private String getPrefixTemplateResolver() throws CustomTemplateResolverException{

    try {           

        return getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath() 
                + "templates" + BARRA + "mailTemplates" + BARRA + "templatesPredefined" + BARRA;

    } catch (URISyntaxException e) {

        LOGGER.debug("Não foi possível obter o prefixo (classpath) do template resolver.", e);

        throw new CustomTemplateResolverException("Não foi possível obter o prefixo (classpath) do template resolver.", e);

    }

}

//In the section below is where to process the HTML files of my external project.
@Autowired
private TemplateEngine templateEngine;

@Autowired
private Context context;

templateEngine.process("mailTemplate", context)

这非常有效,但是为了使代码更有条理,我不想把所有的CSS放在HTML中,而是放在我稍后导入的外部文件中。但是当我使用下面的代码th:href="@{/css/app/app.css}"

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"    xmlns:th="http://www.thymeleaf.org">
<head>
//I need to import this app.css which is in my 
//resources/static/css/app/app.css folder in my external project.
<link id="appcss" rel="stylesheet" th:href="@{/css/app/app.css}" />
</head>
<body>
<span style="color: red; border-color: 1px solid red;" th:text="${message}">    </span>
<span class="teste">Mail Template</span>
</body>
</html> 

我收到以下错误:

Link base "/css/app/app.css" cannot be context relative (/) or page relative 
unless you implement the org.thymeleaf.context.IWebContext interface 
(context is of class: org.thymeleaf.context.Context) (mailTemplate:4)

我的项目将作为主项目的外部库运行,因此我拥有的上下文和路径是主项目。如何设置资源文件夹并让百万美元在导入将作为库(.jar)执行的项目中的功能时识别相同的内容?

注意:这两个项目(主要和次要)使用的是Spring Boot 1.4,因此也是Thymeleaf的聚合版本。

0 个答案:

没有答案