Velocity在Struts 2框架下的应用

本文介绍如何在Struts2框架中集成Velocity模板引擎。包括项目搭建、配置web.xml和struts.xml文件、编写Action类及Velocity模板等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Struts 2更是提供了对Velocity和FreeMarker模板引擎的支持。通过以下几个步骤,实现在Struts 2中使用velocity模板。
创建一个Web Project,除了Struts2所必备的包外,还需要引入如下包:velocity-1.4.jar、velocity-dep-1.4.jar、velocity-tools-1.1.jar

在web.xml中不需要配置关于Velocity的Servlet,只配置Struts 2的filter即可。
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>


编写Action代码如下:
public class Velocity_II {
private String str;
private List<String> names;
private List<User> users;

public String execute() {
this.str = "Use Velocity";
this.names = getStringData();
this.users = getObjectData();
return "success";
}
public List<String> getStringData() {
List<String> list = new ArrayList<String>();
String name = null;
for(int i=0;i<20;i++){
name = "Hoffman "+i+" Name";
list.add(name);
}
return list;
}
public List<User> getObjectData() {
List<User> lusers = new ArrayList<User>();
for(int i=0;i<5;i++) {
User user = new User();
user.setName("中文测试 "+i);
user.setPhone("1395487"+i);
user.setAddress("Shop Street "+i);
lusers.add(user);
}
return lusers;
}
……省略Geter and Settr Method……
}


在webroot下建立list.vm,内容如下:
<html>
<head> <title>List Velocity</title> </head>
<body>
<b>Use Valocity to Show String:</b> $str   ${str}<hr>
<b>Use Valocity to Show List:</b></br>
#set($num = 0)
#set($bool = true)
#foreach($name in $names)
#if($bool)
$name   
#if($num == 4) </br> #end
#if($num == 9) #set($bool = false) #end
#set($num = $num + 1)
#end
#end <hr>
<b>Use Valocity to Show List:</b></br>
#foreach($user in $users)
$user.name - $user.phone - $user.address </br>
#end <hr>
</body>
</html>


在struts.xml配置文件中,需要注意配置result的type,如下:
<struts>
<constant name="struts.i18n.encoding" value="GBK"/>
<package name="struts" extends="struts-default">
<action name="listVelocity" class="com.mixele.velocityII.Velocity_II">
<result name="success" type="velocity">list.vm</result>
</action>
</package>
</struts>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值