Velocity模板(VM)语言介绍以及与MVC集成
Velocity是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。
当Velocity应用于web开发时,界面设计人员可以和java程序开发人员同步开发一个遵循MVC架构的web站点,也就是说,页面设计人 员可以只关注页面的显示效果,而由java程序开发人员关注业务逻辑编码。Velocity将java代码从web页面中分离出来,这样为web站点的长 期维护提供了便利,同时也为我们在JSP和PHP之外又提供了一种可选的方案。
Velocity现在应用非常广泛,现在尝试将SpringMVC项目与Velocity整合。
1.整合过程
采用以前整合的[SpringMVC项目]。
主要涉及改变的文件:
pom.xml(引入velocity的jar包)
spring-mvc.xml(视图配置,配置velocity)
velocity.properties(velocity配置文件)
下面简要描述一下在spring mvc中配置velocity的步骤:
1、引入velocity所需要的包(mvc的基础上做的添加在这里就省略mvc所导入的jar)
<!-- Velocity模板 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
2.添加配置信息(spring-mvc.xml)
<?xml version="1.0" encoding="UTF-8"?>
<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:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--包扫描-->
<context:component-scan base-package="controller"/>
<!--新的命名空间 mvc
自动注册处理器适配器 和 处理器映射器 处理一些响应相关的操作
不仅代替处理器映射器还代替处理器适配器,还可以处理响应相关的操作
@ResponseBody就是响应到前台的就要配置在这个命名空间里
-->
<mvc:annotation-driven/>
<!--创建处理器映射器
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
创建处理器适配器
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
-->
<!-- 视图解析器
根据controller方法的返回值解析结果为 前缀+ return返回值+后缀
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
-->
<!-- 视图模式配置,velocity配置文件-->
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/views" />
<property name="configLocation" value="classpath:velocity.properties" />
</bean>
<!-- 配置后缀 -->
<bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="suffix" value=".vm" />
<property name="contentType"><value>text/html;charset=UTF-8</value></property>
</bean>
</beans>
3.velocity.properties配置文件
#encoding 设置编码格式
input.encoding=UTF-8
output.encoding=UTF-8
#autoreload when vm changed
file.resource.loader.cache=false
file.resource.loader.modificationCheckInterval=2
velocimacro.library.autoreload=false
4.配置完后书写TestController
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloController {
private static Logger logger = Logger.getLogger(HelloController.class);
@RequestMapping("/showAllUser")
public String showAllUser(HttpServletRequest request,Model model){
//volicaty放入集合
List<User> list = new ArrayList<User>();
User user = new User();
user.setAge(1);
user.setDate(new Date());
user.setId("1");
user.setName("张三");
User user2 = new User();
user2.setAge(1);
user2.setDate(new Date());
user2.setId("s");
user2.setName("李四");
list.add(user);
list.add(user2);
logger.info("userList's size==============" +list.size());
model.addAttribute("userList",list);
//放入单个数据
model.addAttribute("user","测试数据");
return "showAllUser";
}
}
5.showAllUser.vm模板(放置在WEB-INFO下面添加views文件夹)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>show all users</title>
</head>
<body>
<h2>单个名字:$user</h2>
<hr/>
<table >遍历集合所得到的数据
#foreach($user in $userList)
<tr >
<td >$user.name</td>
<td >$user.age</td>
</tr>
#end
</table>
<hr/>
#set($directoryRoot = "www" )
#set($templateName = "index.vm" )
#set($template = "$directoryRoot/$templateName" )
最终结果:$template
</body>
</html>
6.访问结果展示:
2. Velocity基本使用语法
1.展示单条数据
<!--展示单条数据这两种方式都可以推荐第一种-->
<h2>1.单个名字:$user</h2>
<hr/>
<h2>2.单个名字:${user}</h2>
<hr/>
2.展示集合数据
<!--展示集合数据-->
<table >
#foreach($user in $userList)
<tr >
<td >$user.name</td>
<td >$user.age</td>
</tr>
#end
</table>
3.在模版中给变量赋值
<!--前面两个都是给变量赋值,展示的结果为:www/index.vm-->
#set($directoryRoot = "www" )
#set($templateName = "index.vm" )
#set($template = "$directoryRoot/$templateName" )
结果:$template
4.条件语句使用语法
<!-- 条件语句使用语法-->
#if (${a}>18) 小学
#elseif (${a}<15)中学
#else大学
#end
5.单行以及多行注释
<!-- 单行注释-->
## This is a single line comment.
<!-- 多行注释-->
#*
Thus begins a multi-line comment. Online visitors won’t
see this text because the Velocity Templating Engine will
ignore it.
*#
6.set语法
#set可以创建一个Velocity的变量,一般用于向一个变量或属性赋值,下面的第一个例子,大概和java中的String name=user.getName();是一个意思.
在Velocity语法树中,#set表达式对应的是一个ASTSetDirective类,"="两边的表达式值,分别对应该类的两个子节点,LHS和RHS.
#set($user.name="zhangsan") 可以理解为 user.setName("zhangsan")
#set(name=user.name) 可以理解为 user.getName();
像上述例子中的第一个:不仅可以表示 user.setName("zhangsan"),还可以表示user.setname("zhangsan"),或者user.put("name","zhangsan"),
这是动态语言的特点,不想java语法那样严格的定义.
注意:#set表达式,结尾不需要#end跟随,其他表达式基本都需要加#end.
#parse语法
#parse语法的作用是引用其他模块,比如你可以把多个vm文件中重复的代码抽取出来,放到一个单独的"common.vm"文件中,然后再在每一个模块的对应位置使用#parse('common.vm')把公共模块引入到当前模块.
需要特别注意的一点是,common.vm中的变量的值都可以由#paser()所在的vm文件模板的上下文中取得,也就是说,你只是把一段公共的vm代码放在一个单独的模板文件中,除此之外,和两者在一个模板文件中没有任何其他区别.
另外#parse()中不仅能引入其他模板文件,也可以引入一个变量.同时需要记得一点,#parse引入的模板文件中,也可以包含#parse.
说到了#parse就要提到另一个引入的指令#include,也是引入外部文件的意思,他们的区别总结如下:
-
- #include()可以同时引入多个文件, #parse()只能一次引入一个文件(或变量).
- #include引入的内容不会被Velocity的emplate engine即模板引擎处理, #parse引入的内容会被处理,也就是说#include引入的内容不能包含velocity语法,而后者,当然是可以的.
(转)Velocity和jsp的区别:
执行方式不一样: JSP是编译执行,Velocity是解释执行.如果JSP文件被修改了,对应的java类就会重新编译,而Velocity却不需要,只是会重新生成一棵语法树.
执行效率不同:理论上来说,编译执行的效率明显好于解释执行,在JSP中方法调用是直接执行的,而在velocity中使用反射执行的,从这方面来讲JSP效率会明显好于Velocity.如果JSP中有大量的jstl或者其他标签的话,就不一定了.
需要的环境支持不同:JSP的执行依赖Servlet环境,他需要ServletContext,request,response这些类.而渲染Velocity不需要其他环境的支持,所以说velocity的应用环境更广.