参考资料
1 使用 Velocity 实现客户端和服务器端模板
http://www.ibm.com/developerworks/cn/java/j-velocity/
2 velocity整合servlet
http://www.blogjava.net/sxyx2008/archive/2010/11/11/337819.html
3 Velocity学习之Servlet初体验
http://jzhua.iteye.com/blog/311399
4 Velocity初体验
http://blog.csdn.net/zyk220/article/details/1927298
5 Velocity用户手册---中文版
http://blog.csdn.net/zyk220/article/details/1927304
Velocity是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象.
一 环境:Win7 64 + Eclipse3.7 + Tomcat6 + JDK1.6
二 工程图片如下:
三 具体实现
1 MyVelocityServlet3.java
package velocity;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.servlet.VelocityServlet;
import service.UserService;
import bean.User;
@SuppressWarnings("deprecation")
public class MyVelocityServlet3 extends VelocityServlet {
private static final long serialVersionUID = 1L;
public MyVelocityServlet3() {
}
@Override
protected void setContentType(HttpServletRequest request,
HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
}
protected Properties loadConfiguration(ServletConfig config)
throws IOException, FileNotFoundException {
/*
* 得到属性配置文件并load它
*/
String propsFile = config.getInitParameter(INIT_PROPS_KEY);
Properties p = new Properties();
if (propsFile != null) {
String realPath = getServletContext().getRealPath(propsFile);
if (realPath != null) {
propsFile = realPath;
}
p.load(new FileInputStream(propsFile));
}
/*
* 设置velocity日志文件在web应用中的位置
*/
String log = p.getProperty(Velocity.RUNTIME_LOG);
if (log != null) {
log = getServletContext().getRealPath(log);
if (log != null) {
p.setProperty(Velocity.RUNTIME_LOG, log);
}
}
/*
* 设置模板文件在web应用中的位置
*/
String path = p.getProperty(Velocity.FILE_RESOURCE_LOADER_PATH);
if (path != null) {
path = getServletContext().getRealPath(path);
if (path != null) {
p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
}
}
return p;
}
public Template handleRequest(HttpServletRequest request,
HttpServletResponse response, Context ctx) {
//普通变量演示
String userName = "咫尺天涯";
ctx.put("userName", userName);
int userAge = 30;
ctx.put("userAge", userAge);
String blog = "http://liuzidong.iteye.com/";
ctx.put("userBlog", blog);
//JavaBean演示.
double money = 3999.89;
ctx.put("user", new User(userAge,userName,blog,money,true));
//List
List list = new ArrayList();
list.add("天涯");
list.add(30);
list.add(money);
ctx.put("list",list);
//List<User>
List<User> users = new ArrayList<User>();
users.add(new User(23,"david",blog,money,true));
users.add(new User(18,"天涯",blog,646.89,true));
users.add(new User(32,"jack",blog,2323.45,false));
ctx.put("users",users);
//Map
Map map = new HashMap();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
ctx.put("map", map);
//Map<User>
Map<String,User> userMap = new HashMap<String,User>();
userMap.put("1",new User(23,"david",blog,money,true));
userMap.put("2",new User(18,"天涯",blog,646.89,true));
userMap.put("3",new User(32,"jack",blog,2323.45,false));
ctx.put("userMap", userMap);
//调用方法
ctx.put("userService", new UserService());
/*
* 获取模板对象,有三种可能产生的异常
*/
Template outty = null;
try {
outty = getTemplate("demo3.vm");
} catch (ParseErrorException pee) {
System.out.println("SampleServlet : parse error for template "
+ pee);
} catch (ResourceNotFoundException rnfe) {
System.out.println("SampleServlet : template not found " + rnfe);
} catch (Exception e) {
System.out.println("Error " + e);
}
return outty;
}
}
2 velocity.properties
# 指定模板文件存放目录
file.resource.loader.path = templates
# 指定日志文件位置
runtime.log = log/velocity.log
input.encoding=utf-8
output.encoding=utf-8
3 demo3.vm
<html>
<head><title>Demo velocity page</title></head>
<body bgcolor="#ffffff">
<br>姓名:$userName,年龄:$userAge,$userName的博客:<a href="$userBlog">$userBlog</a>
<br>年龄if elseif else end使用:
#if($userAge < 18)
未成年
#elseif($userAge >= 18 && $userAge <= 30)
青年
#elseif($userAge > 30 && $userAge <= 60)
中年
#else
老年
#end
<br>JavaBean演示:$user.getUsername(),$user.age,$user.blog,$user.momey,#if($user.xb)男#else女#end;
<br> List:
<ui>
#foreach($index in $list)
<li>$index</li>
#end
</ui>
<br> List<User>:
<ui>
#foreach($user in $users)
<li>$user.age,$user.username,<a href="$user.blog">$user.blog</a>,#if($user.xb)男#else女#end</li>
#end
</ui>
<br> Map:
<ui>
#foreach($entity in $map.entrySet())
<li>$entity.key,$entity.value</li>
#end
</ui>
<br> Map<User>:
<ui>
#foreach($entity in $userMap.entrySet())
<li>$entity.key,$entity.value.age,$entity.value.username,<a href="$entity.value.blog">$entity.value.blog</a>,#if($entity.value.xb)男#else女#end</li>
#end
</ui>
<br> 调用类方法(好强大^_^):$userService.getUserName('咫尺天涯');
<br>变量<br><textarea rows="4" cols="60">
变量的简略标记是有一个前导"$"字符后跟一个VTL标识符(Identifier.)标识符必须以一个字母开始(a...z或A...Z).
剩下的字符将由以下类型的字符组成:字母(a...z,A...Z) 数字(0...9) 连字符("-")下划线("_")
</textarea>
<br>#set ( $a ="Velocity") Hello $a World!
<br>使用$!文本框的初始值就不会是myuserName而是空值<input type="text" value="$!myuserName"/>
<br>VTL中使用"/”作为逃逸符:<br>
#set( $email ="davidliuzd@163.com")
<br> $email
<br>/$email
<br>//$email
<br>///$email
#macro ( d )
<ui>
<li >1</li>
<li >2</li>
<li >3</li>
</ui>
#end
<br>macro使用:#d()
<br>
#macro ( tablerows $color $somelist $mycolor)
#foreach ( $something in $somelist )
<tr>
<td>$velocityCount</td>
#set ( $tdColor = "green")
#if($velocityCount % 2 == 0)
#set ( $tdColor = $color)
#else
#set ( $tdColor = $mycolor)
#end
<td bgcolor=$tdColor>$something</td>
</tr>
#end
#end
<br>macro常见应用:隔行变色
#set ( $greatlakes = [ "Superior", "Michigan", "Huron", "Erie", "Ontario" ] )
#set ( $color = "blue")
#set ( $color2 = "red")
<table>
#tablerows($color $greatlakes $color2)
</table>
<br>math 在模板中可以使用Velocity内建的算术函数,如:加、减、乘、除
<br>
#set ($numer = 6)
#set ( $foo = $numer + 3 )$foo<br>
#set ( $foo = $numer - 4 )$foo<br>
#set ( $foo = $numer * 6 )$foo<br>
#set ( $foo = $numer / 2 )$foo<br>
#set ( $foo = $numer % 5 )$foo<br>
</body>
</html>
4 web.xml
<servlet>
<description></description>
<display-name>MyVelocityServlet3</display-name>
<servlet-name>MyVelocityServlet3</servlet-name>
<servlet-class>velocity.MyVelocityServlet3</servlet-class>
<init-param>
<param-name>org.apache.velocity.properties</param-name>
<param-value>/WEB-INF/classes/velocity.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyVelocityServlet3</servlet-name>
<url-pattern>/velocity3</url-pattern>
</servlet-mapping>
具体参见代码注释^_^
- 大小: 76.1 KB
分享到:
相关推荐
List<Map, Object>> list = service.queryKsxxList(1); context.put("ds", list); StringWriter writer = new StringWriter(); velocityEngine.mergeTemplate("/ksxx.vm", "GBK", context, writer); request....
5、${list[0].name} means get the first object from list, then read the property of name. 6、${map(key)} get the value from the map by the key name. 7、${list[${index}].name} [] can be a variable. ...
6. **集合操作**:OGNL支持集合操作,如`list.add(item)`或`map.put(key, value)`,甚至可以动态创建集合和映射。 7. **表达式语法**:OGNL支持丰富的表达式语法,包括但不限于对象导航、算术运算、逻辑运算、比较...
Map, Object> model = new HashMap(); model.put("newsItems", newsItems); StringWriter writer = new StringWriter(); template.process(model, writer); return writer.toString(); } } ``` 最后,这个...
本书适合Java Web 程序员阅读和参考 第1章 Model 2应用程序 1 1.1 Model 2概览 1 1.2 带servlet控制器的Model 2 2 1.2.1 Product动作类 3 1.2.2 ControllerServlet类 4 1.2.3 视图 6 1.2.4 部署描述文件 8 ...
视图部分则通过丰富的标签库呈现用户界面,这些标签使用OGNL(Object Graph Navigation Language)表达式作为基础,不仅支持OGNL,还兼容JSTL, Groovy和Velocity等表达式。Struts2的标签库定义在URI为 `/struts-tags...
Putting a great looking site together takes a lot of work, and most Java developers are more interested in creating a great looking object interface than a user interface. JavaServer Pages (JSP) ...
此外,熟悉Java集合框架(如List、Set和Map)、异常处理以及线程管理也是必要的。 2. **JSP语法**:JSP主要由指令(directives)、脚本元素(scripting elements)和动作(actions)组成。指令用于配置页面,如导入...
4.2 读取Object Stack里的对象的属性 53 4.3 读取Context Map里的对象的属性 54 4.4 如何调用字段和方法 55 4.5 如何访问数组类型的属性 56 4.6 如何访问List类型的属性 56 4.7 如何访问Map类型的属性 57 4.8 JSP EL...
Map, Object> data = new HashMap(); data.put("items", Arrays.asList(new Item("Sample Name"))); // 输出XML StringWriter writer = new StringWriter(); template.process(data, writer); FileUtils.write(new ...
Struts框架是Java Web开发中的一个关键组件,属于SSH(Spring、Struts、Hibernate)三大框架之一。在Struts框架中,值栈(ValueStack)和OGNL(Object-Graph Navigation Language)是两个核心概念,它们极大地简化了...
接着,创建`Map, Object>`来存储数据模型,最后调用`Template`的`process`方法将数据合并到模板中,生成Excel内容。 2. **导出Word** - 导出Word文件可以借助于Apache POI或OpenOffice API。流程与导出Excel相似,...
2.5. Web层 2.5.1. Spring MVC的表单标签库 2.5.2. Spring MVC合理的默认值 2.5.3. Portlet 框架 2.6. 其他特性 2.6.1. 动态语言支持 2.6.2. JMX 2.6 .3. 任务规划 2.6.4. 对Java 5(Tiger)的支持 2.7. 移植到...
map, set, list, bag 5.1.16. 引用(import) 5.2. Hibernate 的类型 5.2.1. 实体(Entities)和值(values) 5.2.2. 基本值类型 5.2.3. 持久化枚举(Persistent enum)类型 5.2.4. 自定义值类型...
map, set, list, bag 5.1.16. 引用(import) 5.2. Hibernate 的类型 5.2.1. 实体(Entities)和值(values) 5.2.2. 基本值类型 5.2.3. 持久化枚举(Persistent enum)类型 5.2.4. 自定义值类型...