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即可。
编写Action代码如下:
在webroot下建立list.vm,内容如下:
在struts.xml配置文件中,需要注意配置result的type,如下:
创建一个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>