velocity整合

来源:互联网 发布:数据质量评估体系 编辑:程序博客网 时间:2024/06/09 02:25

参考博客

velocity(vm)模板引擎学习介绍及语法
Velocity模板引擎语法
Velocity模板引擎的介绍和基本的模板语言语法使用
SpringMVC整合Velocity模版引擎
使用 Velocity 模板引擎快速生成代码
Velocity 简单Demo
springmvc集成 velocity,实现多视图整合(jsp,velocity)
velocity的使用简介
在velocity使用toolbox.xml

目录

  • 为什么使用Velocity,作用是什么
  • Velocity语法
  • Velocity的安装
  • 使用过程
  • Velocity与springMVC的整合
  • Velocity与SSH的整合

Velocity优劣

Velocity 是一个基于java 的模板引擎(template engine). 它可以让视图的设计者在web 页面中引用java 代码中定义的数据对象和命令。从而使Web designers 和java 开发者依照MVC 思想(Model-View-Controller )开发系统,这意味着Web designers 只须将精力注用于良好表现力的视图外观设计,而Java程序员则只要关心着如何写出高效简洁的java 对象以实现业务逻辑—–Velocity 会将他们组装到一起.
相比传统的jsp、PHP 等脚本语言,Velocity 彻底的将避免了在视图设计中出现的java 代码, 从而保证了web site 的长期可维护性.

二、Velocity与Jsp、Freemarker的对比

在java领域,表现层技术主要有三种:jsp、freemarker、velocity。

jsp是大家最熟悉的技术 优点: 1、功能强大,可以写java代码 2、支持jsp标签(jsp tag) 3、支持表达式语言(el)
4、官方标准,用户群广,丰富的第三方jsp标签库 5、性能良好。jsp编译成class文件执行,有很好的性能表现 缺点:
jsp没有明显缺点,非要挑点骨头那就是,由于可以编写java代码,如使用不当容易破坏mvc结构。

velocity是较早出现的用于代替jsp的模板语言 优点: 1、不能编写java代码,可以实现严格的mvc分离
2、性能良好,据说比jsp性能还要好些 3、使用表达式语言,据说jsp的表达式语言就是学velocity的 缺点: 1、不是官方标准
2、用户群体和第三方标签库没有jsp多。 3、对jsp标签支持不够好

freemarker 优点: 1、不能编写java代码,可以实现严格的mvc分离 2、性能非常不错 3、对jsp标签支持良好
4、内置大量常用功能,使用非常方便 5、宏定义(类似jsp标签)非常方便 6、使用表达式语言 缺点: 1、不是官方标准
2、用户群体和第三方标签库没有jsp多

性能:velocity应该是最好的,其次是jsp,普通的页面freemarker性能最差,但是在复杂页面上(包含大量判断、日期金额格式化)的页面上,freemarker的性能比使用tag和el的jsp好。

语法

基本语法

“#”用来标识Velocity的关键字,包括#set、#if
、#else、#end、#foreach、#end、#include、#parse、#macro等;

$”用来标识Velocity的变量;如:$i、$msg、$TagUtil.options(…)等。

“{}”用来明确标识Velocity变量;比如在页面中,页面中有一个$someonename,此时,Velocity将把someonename作为变量名,若我们程序是想在someone这个变量的后面紧接着显示name字符,则上面的标签应该改成${someone}name。

“!”用来强制把不存在的变量显示为空白。如:当找不到username的时候,$username返回字符串”$username”,而\$!username返回空字符串”“

Velocity语法使用

一、变量定义
#set($name =”velocity”) 等号后面的字符串 Velocity 引擎将重新解析,例如出现以$开始的字符串时,将做变量的替换。

二、变量赋值
#set($hello =”hello $name”) 上面的这个等式将会给$hello赋值为”velocity”

三、循环
#foreach($element in $list)
<\span>\$!element<\/span><\br>
#end

五、关系操作符
Velocity引擎提供了AND、OR和NOT操作符,分别对应&&、||和!例如:
#if($foo && $bar) …
#end

六、宏 Velocity 中的宏可以理解为函数定义。定义的语法如下:
#macro(macroName arg1 arg2 …) …
#end 调用这个宏的语法是:
#macroName(arg1 arg2 …) 这里的参数之间使用空格隔开,下面是定义和使用 Velocity 宏的例子:
#macro(sayHello $name) hello $name
#end
#sayHello(“velocity”)
输出的结果为 hello velocity

七、#parse 和 #include

#parse和#include指令的功能都是在外部引用文件,而两者的区别是,#parse会将引用的内容当成类似于源码文件,会将内容在引入的地方进行解析,#include
是将引入文件当成资源文件,会将引入内容原封不动地以文本输出。分别看以下例子:
foo.vm文件:
#set($name = “velocity”) parse.vm:
#parse(“foo.vm”) 输出结果为:velocity
include.vm:
#include(“foo.vm”) 输出结果为:#set($name = “velocity”)
九、单双引号

单引号不解析引用内容,双引号解析引用内容
#set ($var=”hello”)
$var’ ## 结果为:$var “$var” ## 结果为:hello

Velocity的安装

velocity的jar下载
HelloVelocity.java

package velocity;import java.io.StringWriter;import java.util.ArrayList;import java.util.Date;import java.util.List;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;import org.apache.velocity.app.Velocity;import org.apache.velocity.app.VelocityEngine;import org.apache.velocity.runtime.RuntimeConstants;import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;public class HelloVelocity {    public static String exportFixedVelocity() {        // 创建引擎        VelocityEngine ve = new VelocityEngine();        // 设置模板加载路径,这里设置的是class下        ve.setProperty(Velocity.RESOURCE_LOADER, "class");        ve.setProperty("class.resource.loader.class",                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");        try {            // 进行初始化操作            ve.init();            // 加载模板,设定模板编码            Template t = ve.getTemplate("template/hellovelocity.vm",                    "UTF-8");            // 设置初始化数据            VelocityContext context = new VelocityContext();            context.put("name", "velocity");            context.put("date", (new Date()).toString());            String[] hobbyArray = { "吃饭", "喝水", "洗澡" };            context.put("hobby", "爱好");            context.put("list", hobbyArray);            // 设置输出            StringWriter writer = new StringWriter();            // 将环境数据转化输出            t.merge(context, writer);            return writer.toString();        } catch (Exception e) {            throw new RuntimeException("模版转化错误!");        }    }    public static void main(String[] args) {        System.out.println(exportFixedVelocity());        ;    }}

模板文件,放在resources目录下
hellovelocity.vm

#set( $iAmVariable = "good!" )Welcome $name to velocity.comtoday is $date.#foreach ($i in $list)$i#end$iAmVariable

demo下载地址

SpringMVC整合

在pom.xml中增加velocity的引用,mvean依赖

<dependency>    <groupId>org.apache.velocity</groupId>    <artifactId>velocity</artifactId>    <version>1.7</version></dependency><dependency>    <groupId>org.apache.velocity</groupId>    <artifactId>velocity-tools</artifactId>    <version>2.0</version></dependency> <dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-context-support</artifactId>    <version>4.1.3.RELEASE</version></dependency>

mvc配置文件

<!--jsp视图解析器--><bean id="jspViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">    <property name="order" value="1"/>    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>    <property name="prefix" value="/page/"/>    <property name="suffix" value=".jsp"/></bean><!-- velocity环境配置 --><bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">    <!-- velocity配置文件路径  或者直接用velocityProperties属性 -->    <property name="configLocation" value="classpath:velocity.properties"/>    <!-- velocity模板路径 -->    <property name="resourceLoaderPath" value="/WEB-INF/templates/"/></bean><!-- velocity视图解析器 --><bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">    <property name="order" value="0"/>    <property name="contentType" value="text/html;charset=UTF-8"/>    <property name="cache" value="true"/>    <property name="suffix" value=".vm"/>    <property name="layoutUrl" value="layout/layout.vm"/>    <property name="exposeSpringMacroHelpers" value="true" /><!--是否使用spring对宏定义的支持-->    <property name="exposeSessionAttributes" value="true" /><!--是否开放request属性-->    <property name="requestContextAttribute" value="request"/><!--request属性引用名称-->    <property name="dateToolAttribute" value="dateTool"/>    <property name="numberToolAttribute" value="numberTool"/></bean>

velocity.properties

#设置字符集#encodinginput.encoding  =UTF-8output.encoding=UTF-8contentType=text/html;charset=UTF-8#autoreload when vm changedfile.resource.loader.cache=falsefile.resource.loader.modificationCheckInterval  =1velocimacro.library.autoreload=false

TestController

/** * Created by Stay on 2017/2/23  17:43. */@Controller@RequestMapping(value = "/test")public class TestController {    @RequestMapping(value = "/velocity", method = RequestMethod.GET)    public String getTest(Model model) {        model.addAttribute("hello", "test velocity");        return "test";    }}

demo地址

SSH整合

依赖Jar包导入
最新的Struts2中已经提供了集成Velocity时所需的依赖jar包,集成时需要导入以下Jar包(struts-2.3.20-all\struts-2.3.20\lib)。
・velocity-tools-1.3.jar
・velocity-1.6.4.jar
・commons-collections-3.1.jar
・commons-lang-2.4.jar

配置文件Check
检查struts-default.xml文件中Velocity Result是否已配置。
struts-default.xml路径:struts2-core-2.3.20.jar/struts-default.xml
这里写图片描述

在Struts2中使用Velocity

<action name="testLogin" class="gravehistory.test.struts.LoginAction">      <result name="fail">/test/login.jsp</result>      <result name="input">/test/login.jsp</result>      <result name="success" type="velocity">/test/test-success.vm</result>  </action>