• 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

  • 相关阅读:
    BZOJ 4260: Codechef REBXOR (trie树维护异或最大值)
    BZOJ 3744 Gty的妹子序列 做法集结
    BZOJ 3289: Mato的文件管理 (区间查询逆序对)
    [JSOI2007]文本生成器
    [TJOI2013]单词
    模板 AC自动机
    POJ 3710 Christmas Game
    HDU 3094 A tree game
    BZOJ 3817 Sum
    BZOJ 4589 Hard Nim
  • 原文地址:https://www.cnblogs.com/sunxun/p/5390855.html
Copyright © 2020-2023  润新知