1 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
我們可以使用速度來實(shí)現(xiàn)這一點(diǎn),我已經(jīng)實(shí)現(xiàn)了使用模板控制器的目標(biāo),這是我的最終解決方案
使用這些 Maven 依賴項(xiàng)
<dependency>
? ? <groupId>org.apache.velocity</groupId>
? ? <artifactId>velocity</artifactId>
? ? <version>1.7</version>
</dependency>
<dependency>
? ? <groupId>org.apache.velocity</groupId>
? ? <artifactId>velocity-tools</artifactId>
? ? <version>2.0</version>
</dependency>
因?yàn)槲覀冃枰獮榇藙?chuàng)建一個(gè)模板(.vm)文件src/main/resources
然后創(chuàng)建一個(gè)VelocityEngine
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty("resource.loader", "class");
velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
velocityEngine.init();
現(xiàn)在我們需要用這個(gè)生成一個(gè)模板velocityEngine
String page = "./ww_email.vm";
Template template = velocityEngine.getTemplate(page);
要將數(shù)據(jù)傳遞給模板,我們應(yīng)該使用VelocityContext
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("title", title);
velocityContext.put("content", html);
然后創(chuàng)建一個(gè)StringWriter從模板中獲取HTML字符串
StringWriter stringWriter = new StringWriter();
然后將其stringWriter與velocityContext
template.merge(velocityContext, stringWriter);
最后,你可以得到像這樣的HTML字符串
String htmlCodeString = stringWriter.toString()
添加回答
舉報(bào)