jimphei學習工作室

          jimphei學習工作室

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            23 隨筆 :: 0 文章 :: 1 評論 :: 0 Trackbacks

          2009年11月23日 #

          import java.util.Map;

          import org.apache.velocity.app.VelocityEngine;
          import org.springframework.ui.velocity.VelocityEngineUtils;

          public class MsgBean ...{
              private VelocityEngine velocityEngine;

              private String msg;

              private Map model; // 用來保存velocity中的參數值

              private String encoding; // 編碼

              private String templateLocation; // 注入的velocity模塊

              public String getEncoding() ...{
                  return encoding;
              }

              public void setEncoding(String encoding) ...{
                  this.encoding = encoding;
              }

              public String getTemplateLocation() ...{
                  return templateLocation;
              }

              public void setTemplateLocation(String templateLocation) ...{
                  this.templateLocation = templateLocation;
              }

              public Map getModel() ...{
                  return model;
              }

              public void setModel(Map model) ...{
                  this.model = model;
              }

              public String getMsg() ...{
                  // return title;
                  // 將參數值注入到模塊后的返回值
                  return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                          templateLocation, encoding, model);

              }

              public void setMsg(String msg) ...{
                  this.msg = msg;
              }

              public VelocityEngine getVelocityEngine() ...{
                  return velocityEngine;
              }

              public void setVelocityEngine(VelocityEngine velocityEngine) ...{
                  this.velocityEngine = velocityEngine;
              }

          }

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

           

             
           <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean"> 
             <property name="resourceLoaderPath">
                      <value>classpath:velocity</value>
               </property>
              <property name="velocityProperties">
                           <props>
                                 <prop key="resource.loader">class</prop>
                                 <prop key="class.resource.loader.class">
                                       org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
                                 </prop>
                                 <prop key="velocimacro.library"></prop>
                                 <prop key="input.encoding">GBK</prop>
                                 <prop key="output.encoding">GBK</prop>
                                 <prop key="default.contentType">text/html; charset=GBK</prop>
                           </props>
                     </property>
          </bean>

          <bean id="msgBean" class="MsgBean">
                  <property name="templateLocation" value="test.vm"></property>
                  <property name="encoding" value="GBK"></property>
                  <property name="velocityEngine" ref="velocityEngine"></property>
          </bean>


          </beans>

          import java.io.File;
          import java.io.IOException;
          import java.util.HashMap;
          import java.util.Map;

          import org.apache.commons.io.FileUtils;
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.ClassPathXmlApplicationContext;


          public class TestVeloctiy ...{
              public static void main(String[] args) ...{
                  // TODO Auto-generated method stub
                  ApplicationContext ctx=new ClassPathXmlApplicationContext("test3.xml");
                  MsgBean    msgBean=((MsgBean)ctx.getBean("msgBean"));
                  Map<String, String> data = new HashMap<String, String>();
                  data.put("me","yourname");
                  msgBean.setModel(data);
                  System.out.println(msgBean.getMsg());
                 
                  
                  //根據apache common IO 組件直接將內容寫到一個文件中去.
                   File dest = new File( "test.html" );         
                    try ...{
                      FileUtils.writeStringToFile( dest, msgBean.getMsg(), "GBK" );
                  } catch (IOException e) ...{
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }

              }
          }

          本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/pengchua/archive/2008/01/17/2049490.aspx

          posted @ 2009-11-26 11:36 jimphei 閱讀(1150) | 評論 (0)編輯 收藏

          引用自:http://blog.csdn.net/axzywan/archive/2008/07/12/2643921.aspx

          取Session中的值

          <c:out value="${sessionScope.user.userId}"></c:out><br>  

          <c:out value="${user.userLoginName}"></c:out><br>    

          <s:property value="#session.user.userId"/><br>  

          ${session.user.userId}<br> 

          ${sessionScope.user.userId}<br>

          OGNL

          OGNL 是Object Graph Navigation Language 的簡稱,詳細相關的信息可以參考:http://www.ognl.org 。這里我們只涉及Struts2 框架中對OGNL 的基本支持。

           

          OGNL 是一個對象,屬性的查詢語言。在OGNL 中有一個類型為Map 的Context (稱為上下文),在這個上下文中有一個根元素(root ),對根元素的屬性的訪問可以直接使用屬性名字,但是對于其他非根元素屬性的訪問必須加上特殊符號# 。

           

          在Struts2 中上下文為ActionContext ,根元素位Value Stack (值堆棧,值堆棧代表了一族對象而不是一個對象,其中Action 類的實例也屬于值堆棧的一個)。ActionContext 中的內容如下圖:

                        |

                        |--application

                        |

                        |--session

          context map---|

                         |--value stack(root)

                        |

                        |--request

                        |

                        |--parameters

                        |

                        |--attr (searches page, request, session, then application scopes)

                        |

          因為Action 實例被放在Value Stack 中,而Value Stack 又是根元素(root )中的一個,所以對Action 中的屬性的訪問可以不使用標記# ,而對其他的訪問都必須使用# 標記。

           

          引用Action 的屬性

          <s:property value="postalCode"/>

          ActionContext 中的其他非根(root )元素的屬性可以按照如下的方式訪問:

          <s:property value="#session.mySessionPropKey"/> or

          <s:property value="#session["mySessionPropKey"]"/> or

          <s:property value="#request["mySessionPropKey"]/>

           

          Action 類可以使用ActionContext 中的靜態方法來訪問ActionContext 。

          ActionContext.getContext().getSession().put("mySessionPropKey", mySessionObject);

           

          OGNL 與Collection (Lists ,Maps ,Sets )

           

          生成List 的語法為: {e1,e2,e3}.

          <s:select label="label" name="name"

          list="{'name1','name2','name3'}" value="%{'name2'}" />

          上面的代碼生成了一個HTML Select 對象,可選的內容為: name1 ,name2 ,name3 ,默認值為:name2 。

           

          生成Map 的語法為:#{key1:value1,key2:value2}.

          <s:select label="label" name="name"

          list="#{'foo':'foovalue', 'bar':'barvalue'}" />

          上面的代碼生成了一個HTML Select 對象,foo 名字表示的內容為:foovalue ,bar 名字表示的內容為:barvalue 。

           

          判斷一個對象是否在List 內存在:

          <s:if test="'foo' in {'foo','bar'}">

             muhahaha

          </s:if>

          <s:else>

             boo

          </s:else>

           

          <s:if test="'foo' not in {'foo','bar'}">

             muhahaha

          </s:if>

          <s:else>

             boo

          </s:else>

           

          取得一個List 的一部分:

          ?   –   所有滿足選擇邏輯的對象

          ^   -    第一個滿足選擇邏輯的對象

          $   -    最后一個滿足選擇邏輯的對象

          例如:

          person.relatives.{? #this.gender == 'male'}

          上述代碼取得這個人(person )所有的男性(this.gender==male )的親戚(relatives)

           

           

          Lambda 表達式

           

          OGNL 支持簡單的Lambda 表達式語法,使用這些語法可以建立簡單的lambda 函數。

           

          例如:

          Fibonacci:

          if n==0 return 0;

          elseif n==1 return 1;

          else return fib(n-2)+fib(n-1);

          fib(0) = 0

          fib(1) = 1

          fib(11) = 89

           

          OGNL 的Lambda 表達式如何工作呢?

          Lambda 表達式必須放在方括號內部,#this 表示表達式的參數。例如:

          <s:property value="#fib =:[#this==0 ? 0 : #this==1 ? 1 : #fib(#this-2)+#fib(#this-1)], #fib(11)" />

           

          #fib =:[#this==0 ? 0 : #this==1 ? 1 : #fib(#this-2)+#fib(#this-1)] 定義了一個Lambda 表達式,

          #fib(11) 調用了這個表達式。

           

          所以上述代碼的輸出為:89

           

          在JSP2.1 中# 被用作了JSP EL (表達式語言)的特殊記好,所以對OGNL 的使用可能導致問題,

          一個簡單的方法是禁用JSP2.1 的EL 特性,這需要修改web.xml 文件:

          <jsp-config>

              <jsp-property-group>

                <url-pattern>*.jsp</url-pattern>

                <el-ignored>true</el-ignored>

              </jsp-property-group>

          </jsp-config>

          關于EL表達式語言的簡單總結
           

          基本語法

          一、EL簡介
            1.語法結構
              ${expression}
            2.[]與.運算符
              EL 提供.和[]兩種運算符來存取數據。
              當要存取的屬性名稱中包含一些特殊字符,如.或?等并非字母或數字的符號,就一定要使用 []。例如:
                  ${user.My-Name}應當改為${user["My-Name"] }
              如果要動態取值時,就可以用[]來做,而.無法做到動態取值。例如:
                  ${sessionScope.user[data]}中data 是一個變量
            3.變量
              EL存取變量數據的方法很簡單,例如:${username}。它的意思是取出某一范圍中名稱為username的變量。
              因為我們并沒有指定哪一個范圍的username,所以它會依序從Page、Request、Session、Application范圍查找。
              假如途中找到username,就直接回傳,不再繼續找下去,但是假如全部的范圍都沒有找到時,就回傳null。
              屬性范圍在EL中的名稱
                  Page         PageScope
                  Request         RequestScope
                  Session         SessionScope
                  Application     ApplicationScope
                 
          二、EL隱含對象
            1.與范圍有關的隱含對象
            與范圍有關的EL 隱含對象包含以下四個:pageScope、requestScope、sessionScope 和applicationScope;
            它們基本上就和JSP的pageContext、request、session和application一樣;
            在EL中,這四個隱含對象只能用來取得范圍屬性值,即getAttribute(String name),卻不能取得其他相關信息。
           
            例如:我們要取得session中儲存一個屬性username的值,可以利用下列方法:
              session.getAttribute("username") 取得username的值,
            在EL中則使用下列方法
              ${sessionScope.username}

            2.與輸入有關的隱含對象
            與輸入有關的隱含對象有兩個:param和paramValues,它們是EL中比較特別的隱含對象。
           
            例如我們要取得用戶的請求參數時,可以利用下列方法:
              request.getParameter(String name)
              request.getParameterValues(String name)
            在EL中則可以使用param和paramValues兩者來取得數據。
              ${param.name}
              ${paramValues.name}

            3.其他隱含對象
           
            cookie
            JSTL并沒有提供設定cookie的動作,
            例:要取得cookie中有一個設定名稱為userCountry的值,可以使用${cookie.userCountry}來取得它。

            header和headerValues
            header 儲存用戶瀏覽器和服務端用來溝通的數據
            例:要取得用戶瀏覽器的版本,可以使用${header["User-Agent"]}。
            另外在鮮少機會下,有可能同一標頭名稱擁有不同的值,此時必須改為使用headerValues 來取得這些值。

            initParam
            initParam取得設定web站點的環境參數(Context)
            例:一般的方法String userid = (String)application.getInitParameter("userid");
              可以使用 ${initParam.userid}來取得名稱為userid

            pageContext
            pageContext取得其他有關用戶要求或頁面的詳細信息。
              ${pageContext.request.queryString}         取得請求的參數字符串
              ${pageContext.request.requestURL}         取得請求的URL,但不包括請求之參數字符串
              ${pageContext.request.contextPath}         服務的web application 的名稱
              ${pageContext.request.method}           取得HTTP 的方法(GET、POST)
              ${pageContext.request.protocol}         取得使用的協議(HTTP/1.1、HTTP/1.0)
              ${pageContext.request.remoteUser}         取得用戶名稱
              ${pageContext.request.remoteAddr }         取得用戶的IP 地址
              ${pageContext.session.new}             判斷session 是否為新的
              ${pageContext.session.id}               取得session 的ID
              ${pageContext.servletContext.serverInfo}   取得主機端的服務信息

          三、EL運算符
            1.算術運算符有五個:+、-、*或$、/或div、%或mod
            2.關系運算符有六個:==或eq、!=或ne、<或lt、>或gt、<=或le、>=或ge
            3.邏輯運算符有三個:&&或and、||或or、!或not
            4.其它運算符有三個:Empty運算符、條件運算符、()運算符
              例:${empty param.name}、${A?B:C}、${A*(B+C)}
           
          四、EL函數(functions)。
            語法:ns:function( arg1, arg2, arg3 …. argN)
            其中ns為前置名稱(prefix),它必須和taglib 指令的前置名稱一置

          ---------------------------------------------

          補充:

          <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt " %>

          FOREACH:

          <c:forEach items="${messages}"
          var="item"
          begin="0"
          end="9"
          step="1"
          varStatus="var">
          ……
          </c:forEach>


          OUT:

          <c:out value="${logininfo.username}"/>
          c:out>將value 中的內容輸出到當前位置,這里也就是把logininfo 對象的
          username屬性值輸出到頁面當前位置。
          ${……}是JSP2.0 中的Expression Language(EL)的語法。它定義了一個表達式,
          其中的表達式可以是一個常量(如上),也可以是一個具體的表達語句(如forEach循環體中
          的情況)。典型案例如下:
          Ø ${logininfo.username}
          這表明引用logininfo 對象的username 屬性。我們可以通過“.”操作符引
          用對象的屬性,也可以用“[]”引用對象屬性,如${logininfo[username]}
          與${logininfo.username}達到了同樣的效果。
          “[]”引用方式的意義在于,如果屬性名中出現了特殊字符,如“.”或者“-”,
          此時就必須使用“[]”獲取屬性值以避免語法上的沖突(系統開發時應盡量避免
          這一現象的出現)。
          與之等同的JSP Script大致如下:
          LoginInfo logininfo =
          (LoginInfo)session.getAttribute(“logininfo”);
          String username = logininfo.getUsername();
          可以看到,EL大大節省了編碼量。
          這里引出的另外一個問題就是,EL 將從哪里找到logininfo 對象,對于
          ${logininfo.username}這樣的表達式而言,首先會從當前頁面中尋找之前是
          否定義了變量logininfo,如果沒有找到則依次到Request、Session、
          Application 范圍內尋找,直到找到為止。如果直到最后依然沒有找到匹配的
          變量,則返回null.
          如果我們需要指定變量的尋找范圍,可以在EL表達式中指定搜尋范圍:
          ${pageScope.logininfo.username}
          ${requestScope.logininfo.username}
          ${sessionScope.logininfo.username}
          ${applicationScope.logininfo.username}
          在Spring 中,所有邏輯處理單元返回的結果數據,都將作為Attribute 被放
          置到HttpServletRequest 對象中返回(具體實現可參見Spring 源碼中
          org.springframework.web.servlet.view.InternalResourceView.
          exposeModelAsRequestAttributes方法的實現代碼),也就是說Spring
          MVC 中,結果數據對象默認都是requestScope。因此,在Spring MVC 中,
          以下尋址方法應慎用:
          ${sessionScope.logininfo.username}
          ${applicationScope.logininfo.username}
          Ø ${1+2}
          結果為表達式計算結果,即整數值3。
          Ø ${i>1}
          如果變量值i>1的話,將返回bool類型true。與上例比較,可以發現EL會自
          動根據表達式計算結果返回不同的數據類型。
          表達式的寫法與java代碼中的表達式編寫方式大致相同。

          IF / CHOOSE:

          <c:if test="${var.index % 2 == 0}">
          *
          </c:if>
          判定條件一般為一個EL表達式。
          <c:if>并沒有提供else子句,使用的時候可能有些不便,此時我們可以通過<c:choose>
          tag來達到類似的目的:
          <c:choose>
          <c:when test="${var.index % 2 == 0}">
          *
          </c:when>
          <c:otherwise>
          !
          </c:otherwise>
          </c:choose>
          類似Java 中的switch 語句,<c:choose>提供了復雜判定條件下的簡化處理手法。其
          中<c:when>子句類似case子句,可以出現多次。上面的代碼,在奇數行時輸出“*”號,
          而偶數行時輸出“!”。
          ---------------------------------------------

          再補充:

           1    EL表達式用${}表示,可用在所有的HTML和JSP標簽中 作用是代替JSP頁面中復雜的JAVA代碼.

                  2   EL表達式可操作常量 變量 和隱式對象. 最常用的 隱式對象有${param}和${paramValues}. ${param}表示返回請求參數中單個字符串的值. ${paramValues}表示返回請求參數的一組值.pageScope表示頁面范圍的變量.requestScope表示請求對象的變量. sessionScope表示會話范圍內的變量.applicationScope表示應用范圍的變量.

                  3   <%@  page isELIgnored="true"%> 表示是否禁用EL語言,TRUE表示禁止.FALSE表示不禁止.JSP2.0中默認的啟用EL語言.

                  4   EL語言可顯示 邏輯表達式如${true and false}結果是false    關系表達式如${5>6} 結果是false     算術表達式如 ${5+5} 結果是10

                  5   EL中的變量搜索范圍是:page request session application   點運算符(.)和"[ ]"都是表示獲取變量的值.區別是[ ]可以顯示非詞類的變量


          本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/stonec/archive/2009/10/09/4647394.aspx

          posted @ 2009-11-23 10:53 jimphei 閱讀(285) | 評論 (0)編輯 收藏

          主站蜘蛛池模板: 安化县| 雷山县| 彩票| 称多县| 建湖县| 阳西县| 都安| 侯马市| 原平市| 洛浦县| 三台县| 凌源市| 岐山县| 东至县| 札达县| 桃源县| 芮城县| 柘荣县| 石河子市| 昌乐县| 高雄市| 洛阳市| 屏东市| 平阳县| 来凤县| 斗六市| 琼中| 交口县| 文成县| 郯城县| 汤阴县| 雅安市| 黔西县| 石泉县| 江口县| 华容县| 巴彦县| 土默特左旗| 青川县| 邳州市| 吐鲁番市|