Velocity 入门(一)

Velocity是一种Java模版引擎技术,该项目由Apache提出。因为非常好用,和工作中有啥用,所以我在在理简单的入门一下。

网上找了很多教程,写的不是很明白,要么就是全部拷贝下来时候运行不起来。

在这里我来写一份比较完成的配置 struts2 + Velocity的。相信能用到这个模板引擎的人,对 struts都会有一定的了解,这里就不细说了。

第一步:

导入包 

 -- velocity-1.7.jar

 -- velocity-tools-1.4.jar

第二步:

web.xml 因为这里是用的struts2 所以写入的是它的配置

 <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>*.action</url-pattern>  
    </filter-mapping>  

第三步:struts.xml 这里其实并没有写其他的,只是用struts的动态方法进行调用。

通过制定type = "velocity" 确定返回的页面的类型。

<?xml version="1.0" encoding="UTF-8" ?>  
 <!DOCTYPE struts PUBLIC  
     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
     "http://struts.apache.org/dtds/struts-2.3.dtd">  
 <struts>  
     <!-- 动态方法调用打开,可以通过感叹号调用action里面的方法 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    
    <package   name="default"  extends="struts-default"  namespace="/">  
        <!-- to welPage -->  
        <action  name="*"  class="com.ape.action.{1}Action">  
            <result  type="velocity">/{1}.vm</result>  
        </action>  
    </package> 
 </struts>  

第四步:TestAction.java

注意:这里如果要在Vm页面进行输入变量,要将变量进行get set 封装下。不然输出不了

package com.ape.action;

import com.opensymphony.xwork2.ActionSupport;

public class TestAction extends ActionSupport {  
      
    /** 
     *  
     */  
    private static final long serialVersionUID = 9061932498262928875L;  
    private String name;  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public String test() {  
        name = "Hello";  
        return SUCCESS;  
    }  
  
} 

第六步:Test.vm

<html>  
 <head>  
 <title>Insert title here</title>  
 </head>  
  <body>  
  #set($world="world") 
    ${name}-${world}
</body>  
 </html> 

 

代码完毕:访问:http://localhost:8080/VelocityS/Test!test.action

源码:http://pan.baidu.com/s/1nv0Aevv

posted on 2016-04-14 14:01  手撕高达的村长  阅读(433)  评论(0编辑  收藏  举报

导航