需求
项目中需要把Html的模板文件根据动态变量输出成string的html,供其他的调用(例如根据html生成html,或者根据html发送邮件等),项目是用SpringMVC5做的,用上了Thymeleaf模板引擎,还是挺方便的,发出来供参考,因为一些配置是基于xml的,网上看到的并不多。
实现
首先引入依赖,pom.xml增加thymeleaf-spring5:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
application-context.xml增加如下配置
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2021.
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd >
<context:annotation-config/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 自动扫描该路径的所有注解 -->
<context:component-scan base-package="com.terrynow.test"/>
<!--其他配置省略不写-->
<!-- ThymeLeaf 相关 -->
<!-- 模板解析器 -->
<bean id="templateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 模板文件的路径前缀,我们把html放在/WEB-INF/templates下 -->
<property name="prefix" value="/WEB-INF/templates/" />
<!-- 模板文件的路径后缀 -->
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
<!-- 配置是否缓存 -->
<!-- 默认情况下, 模板缓存为true。如果您想要设置为false -->
<property name="cacheable" value="false" />
<!-- 默认编码格式 -->
<property name="characterEncoding" value="UTF-8"/>
</bean>
<!-- 模板引擎 -->
<bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="enableSpringELCompiler" value="true" />
</bean>
<!-- 视图解析器 -->
<bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="characterEncoding" value="UTF-8"/>
</bean>
</beans>
使用Thymeleaf模板引擎生成HTML
@Autowired
private TemplateEngine templateEngine; // Autowired Thymeleaf模板引擎
public void test() {
Context context = new Context();
context.setVariable("foo", "bar");
String html = templateEngine.process("test", context); //test.html放在/WEB-INF/templates下
}
文章评论