1.首先需要导入velocity需要的jar包,这个可以在网上下载到
2.在application.xml中进行配置
<!-- 模板信息设置 -->
<bean id="velocityConfigurer"
class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="WEB-INF/templates" /><!-- 設置模板防止位置-->
<property name="velocityProperties">
<props>
<prop key="directive.foreach.counter.name">loopCounter</prop>
<prop key="directive.foreach.counter.initial.value">0</prop>
<prop key="input.encoding">UTF-8</prop><!-- 指定模板引擎进行模板处理的编码 -->
<prop key="output.encoding">UTF-8</prop><!-- 指定输出流的编码 -->
</props>
</property>
</bean>
3.写vm文件,这个文件一定要放到web-inf文件夹下,否者会报找不到文件错误
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
#set( $this = "Velocity")
$this is great! <br/>
$name <br/>
hi , i am letian
<h1>你好</h1>
</body>
</html>
如图放置

4.写Java方法
public void init(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
VelocityEngine velocityEngine = velocityConfigurer.getVelocityEngine();
VelocityContext context = new VelocityContext();
context.put("name", "test");
StringWriter sw = new StringWriter();
velocityEngine.mergeTemplate("../templates/test.vm", "utf-8", context, sw);
System.out.println(sw.toString());
}
5.运行以后就可以在控制台输出
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
Velocity is great! <br/>
test <br/>
hi , i am letian
<h1>你好</h1>
</body>
</html>
好了,完成
本文详细介绍了如何在Spring框架下利用Velocity模板引擎动态生成HTML页面,包括配置Velocity、编写VM文件、Java方法调用及输出验证等步骤。
1万+

被折叠的 条评论
为什么被折叠?



