jimphei學(xué)習(xí)工作室

          jimphei學(xué)習(xí)工作室

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

          2009年9月22日 #

          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中的參數(shù)值

              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;
                  // 將參數(shù)值注入到模塊后的返回值
                  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());
                 
                  
                  //根據(jù)apache common IO 組件直接將內(nèi)容寫到一個(gè)文件中去.
                   File dest = new File( "test.html" );         
                    try ...{
                      FileUtils.writeStringToFile( dest, msgBean.getMsg(), "GBK" );
                  } catch (IOException e) ...{
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }

              }
          }

          本文來自CSDN博客,轉(zhuǎn)載請標(biāo)明出處: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 的簡稱,詳細(xì)相關(guān)的信息可以參考:http://www.ognl.org 。這里我們只涉及Struts2 框架中對OGNL 的基本支持。

           

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

           

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

                        |

                        |--application

                        |

                        |--session

          context map---|

                         |--value stack(root)

                        |

                        |--request

                        |

                        |--parameters

                        |

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

                        |

          因?yàn)锳ction 實(shí)例被放在Value Stack 中,而Value Stack 又是根元素(root )中的一個(gè),所以對Action 中的屬性的訪問可以不使用標(biāo)記# ,而對其他的訪問都必須使用# 標(biāo)記。

           

          引用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 中的靜態(tài)方法來訪問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'}" />

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

           

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

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

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

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

           

          判斷一個(gè)對象是否在List 內(nèi)存在:

          <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>

           

          取得一個(gè)List 的一部分:

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

          ^   -    第一個(gè)滿足選擇邏輯的對象

          $   -    最后一個(gè)滿足選擇邏輯的對象

          例如:

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

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

           

           

          Lambda 表達(dá)式

           

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

           

          例如:

          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 表達(dá)式如何工作呢?

          Lambda 表達(dá)式必須放在方括號內(nèi)部,#this 表示表達(dá)式的參數(shù)。例如:

          <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)] 定義了一個(gè)Lambda 表達(dá)式,

          #fib(11) 調(diào)用了這個(gè)表達(dá)式。

           

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

           

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

          一個(gè)簡單的方法是禁用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>

          關(guān)于EL表達(dá)式語言的簡單總結(jié)
           

          基本語法

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

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

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

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

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

            pageContext
            pageContext取得其他有關(guān)用戶要求或頁面的詳細(xì)信息。
              ${pageContext.request.queryString}         取得請求的參數(shù)字符串
              ${pageContext.request.requestURL}         取得請求的URL,但不包括請求之參數(shù)字符串
              ${pageContext.request.contextPath}         服務(wù)的web application 的名稱
              ${pageContext.request.method}           取得HTTP 的方法(GET、POST)
              ${pageContext.request.protocol}         取得使用的協(xié)議(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}   取得主機(jī)端的服務(wù)信息

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

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

          補(bǔ)充:

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

          IF / CHOOSE:

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

          再補(bǔ)充:

           1    EL表達(dá)式用${}表示,可用在所有的HTML和JSP標(biāo)簽中 作用是代替JSP頁面中復(fù)雜的JAVA代碼.

                  2   EL表達(dá)式可操作常量 變量 和隱式對象. 最常用的 隱式對象有${param}和${paramValues}. ${param}表示返回請求參數(shù)中單個(gè)字符串的值. ${paramValues}表示返回請求參數(shù)的一組值.pageScope表示頁面范圍的變量.requestScope表示請求對象的變量. sessionScope表示會(huì)話范圍內(nèi)的變量.applicationScope表示應(yīng)用范圍的變量.

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

                  4   EL語言可顯示 邏輯表達(dá)式如${true and false}結(jié)果是false    關(guān)系表達(dá)式如${5>6} 結(jié)果是false     算術(shù)表達(dá)式如 ${5+5} 結(jié)果是10

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


          本文來自CSDN博客,轉(zhuǎn)載請標(biāo)明出處:http://blog.csdn.net/stonec/archive/2009/10/09/4647394.aspx

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

           sitemesh應(yīng)用Decorator模式,用filter截取request和response,把頁面組件head,content,banner結(jié)合為一個(gè)完整的視圖。通常我們都是用include標(biāo)簽在每個(gè)jsp頁面中來不斷的包含各種header, stylesheet, scripts and footer,現(xiàn)在,在sitemesh的幫助下,我們可以開心的刪掉他們了。如下圖,你想輕松的達(dá)到復(fù)合視圖模式,那末看完本文吧。

          一、在WEB-INF/web.xml中copy以下filter的定義:

          <?xml version="1.0" encoding="GBK"?>
          <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
          version="2.4">

          <filter>
            <filter-name>sitemesh</filter-name>
               <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
            </filter>

            <filter-mapping>
               <filter-name>sitemesh</filter-name>
               <url-pattern>/*</url-pattern>
            </filter-mapping>

          </web-app>

          二、copy所需sitemesh-2.3.jar到WEB-INF\lib下。(這里可以下載http://www.opensymphony.com/sitemesh/)

          三、
          建立WEB-INF/decorators.xml描述各裝飾器頁面。

          <decorators defaultdir="/decorators">
                                         <decorator name="main" page="main.jsp">
                                             <pattern>*</pattern>
                                         </decorator>
                                  </decorators>

            上面配置文件指定了裝飾器頁面所在的路徑,并指定了一個(gè)名為main的裝飾器,該裝飾器默認(rèn)裝飾web應(yīng)用根路徑下的所有頁面。

          四、
          建立裝飾器頁面 /decorators/main.jsp

        1. <%@ page contentType="text/html; charset=GBK"%>
          <%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%> <html>
                <head>
                    <title><decorator:title default="裝飾器頁面..." /></title>
                    <decorator:head />
                </head>
               <body>
                  sitemesh的例子<hr>
                  <decorator:body />
                  <hr>chen56@msn.com
              </body>
          </html>
           

          五、建立一個(gè)的被裝飾頁面 /index.jsp(內(nèi)容頁面)

        2. <%@ page contentType="text/html; charset=GBK"%>
                                  <html>
                                       <head>
                                         <title>Agent Test</title>
                                       </head>
                                       <body>
                                         <p>本頁只有一句,就是本句.</p>
                                       </body>
                                  </html>

            最后訪問index.jsp,將生成如下頁面:

                而且,所有的頁面也會(huì)如同index.jsp一樣,被sitemesh的filter使用裝飾模式修改成如上圖般模樣,卻不用再使用include標(biāo)簽。



          1. 裝飾器     decorator概念
                為了建立可復(fù)用的web應(yīng)用程序,一個(gè)通用的方法是建立一個(gè)分層系統(tǒng),如同下面一個(gè)普通的web應(yīng)用:
            • 前端:JSP和Servlets,或jakarta的velocity 。。。
            • 控制層框架 Controller : (Struts/Webwork)
            • 業(yè)務(wù)邏輯 Business :主要業(yè)務(wù)邏輯
            • 持久化框架 :hibernate/jdo

                可糟糕的是前端的頁面邏輯很難被復(fù)用,當(dāng)你在每一個(gè)頁面中用數(shù)之不盡的include來復(fù)用公共的header, stylesheet, scripts,footer時(shí),一個(gè)問題出現(xiàn)了-重復(fù)的代碼,每個(gè)頁面必須用copy來復(fù)用頁面結(jié)構(gòu),而當(dāng)你需要?jiǎng)?chuàng)意性的改變頁面結(jié)構(gòu)時(shí),災(zāi)難就愛上了你。

                 sitemesh通過filter截取request和response,并給原始的頁面加入一定的裝飾(可能為header,footer...),然后把結(jié)果返回給客戶端,并且被裝飾的原始頁面并不知道sitemesh的裝飾,這也就達(dá)到了脫耦的目的。

                 據(jù)說即將新出臺的Portlet規(guī)范會(huì)幫助我們標(biāo)準(zhǔn)的實(shí)現(xiàn)比這些更多更c(diǎn)ool的想法,但可憐的我還不懂它到底是一個(gè)什末東東,有興趣的人可以研究
            jetspeed,或JSR (Java Specification Request) 168,但我想sitemesh如此簡單,我們不妨先用著。

             

            讓我們看看怎樣配置環(huán)境
                除了要copy到WEB-INF/lib中的sitemesh.jar外,還有2個(gè)文件要建立到WEB-INF/:
            • sitemesh.xml (可選)  
            • decorators.xml

            sitemesh.xml 可以設(shè)置2種信息:

            Page Parsers :負(fù)責(zé)讀取stream的數(shù)據(jù)到一個(gè)Page對象中以被SiteMesh解析和操作。(不太常用,默認(rèn)即可)

            Decorator Mappers : 不同的裝飾器種類,我發(fā)現(xiàn)2種比較有用都列在下面。一種通用的mapper,可以指定裝飾器的配置文件名,另一種可打印的裝飾器,可以允許你當(dāng)用http://localhost/aaa/a.html?printable=true方式訪問時(shí)給出原始頁面以供打印(免得把header,footer等的花哨的圖片也搭上)

            (但一般不用建立它,默認(rèn)設(shè)置足夠了:com/opensymphony/module/sitemesh/factory/sitemesh-default.xml):

            范例:

            <sitemesh>
                 <page-parsers>
                   <parser default="true" class="com.opensymphony.module.sitemesh.parser.DefaultPageParser" />
                   <parser content-type="text/html" class="com.opensymphony.module.sitemesh.parser.FastPageParser" />
                   <parser content-type="text/html;charset=ISO-8859-1" class="com.opensymphony.module.sitemesh.parser.FastPageParser" />
                 </page-parsers>

                 <decorator-mappers>
                   <mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">
                     <param name="config" value="/WEB-INF/decorators.xml" />
                   </mapper>
                     <mapper class="com.opensymphony.module.sitemesh.mapper.PrintableDecoratorMapper">
                        <param name="decorator" value="printable" />
                        <param name="parameter.name" value="printable" />
                                <param name="parameter.value" value="true" />
                     </mapper>
              
            </decorator-mappers>
            </sitemesh>

            decorators.xml :定義構(gòu)成復(fù)合視圖的所有頁面構(gòu)件的描述(主要結(jié)構(gòu)頁面,header,footer...),如下例:

            <decorators defaultdir="/decorators">
                 <decorator name="main" page="main.jsp">
                   <pattern>*</pattern>
                 </decorator>
                 <decorator name="printable" page="printable.jsp" role="customer" webapp="aaa" />
            </decorators>
            • defaultdir: 包含裝飾器頁面的目錄
            • page : 頁面文件名
            • name : 別名
            • role : 角色,用于安全
            • webapp : 可以另外指定此文件存放目錄
            • Patterns : 匹配的路徑,可以用*,那些被訪問的頁面需要被裝飾。

             

            最重要的是寫出裝飾器本身(也就是那些要復(fù)用頁面,和結(jié)構(gòu)頁面)。
                其實(shí),重要的工作就是制作裝飾器頁面本身(也就是包含結(jié)構(gòu)和規(guī)則的頁面),然后把他們描述到decorators.xml中。

                讓我們來先看一看最簡單的用法:其實(shí)最常用也最簡單的用法就是我們的hello例子,面對如此眾多的技術(shù),我想只要達(dá)到功能點(diǎn)到為止即可,沒必要去研究太深(除非您有更深的需求)。

            <%@ page contentType="text/html; charset=GBK"%>
                                        <%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
                                        <html>
                                             <head>
                                               <title><decorator:title default="裝飾器頁面..." /></title>
                                               <decorator:head />
                                             </head>
                                             <body>
                                               sitemesh的例子<hr>
                                               <decorator:body />
                                               <hr>chen56@msn.com
                                             </body>
                                        </html>
                                        

            我們在裝飾器頁面只用了2個(gè)標(biāo)簽:

            <decorator:title default="裝飾器頁面..." />       : 把請求的原始頁面的title內(nèi)容插入到<title></title>中間。

            <decorator:body /> : 把請求的原始頁面的body內(nèi)的全部內(nèi)容插入到相應(yīng)位置。

            然后我們在decorator.xml中加入以下描述即可:

            <decorator name="main" page="main.jsp">
                   <pattern>*</pattern>
            </decorator>

            這樣,請求的所有頁面都會(huì)被重新處理,并按照main.jsp的格式重新展現(xiàn)在你面前。

             

            讓我們看看更多的用法。(抄襲sitemesh文檔)
            以下列著全部標(biāo)簽:
            Decorator Tags Page Tags
            被用于建立裝飾器頁面. 被用于從原始內(nèi)容頁面訪問裝飾器.
            <decorator:head />
            <decorator:body />
            <decorator:title />
            <decorator:getProperty />
            <decorator:usePage />
            <page:applyDecorator />
            <page:param
             

            <decorator:head />

            插入原始頁面(被包裝頁面)的head標(biāo)簽中的內(nèi)容(不包括head標(biāo)簽本身)。

            <decorator:body />

            插入原始頁面(被包裝頁面)的body標(biāo)簽中的內(nèi)容。

            <decorator:title [ default="..." ] />

            插入原始頁面(被包裝頁面)的title標(biāo)簽中的內(nèi)容,還可以添加一個(gè)缺省值。

            例:

            /decorator/main.jsp中 (裝飾器頁面): <title><decorator:title default="卻省title-hello"     /> - 附加標(biāo)題</title>

            /aaa.jsp中 (原始頁面):<title>aaa頁面</title>

            訪問/aaa.jsp的結(jié)果:<title>aaa頁面 - 附加標(biāo)題</title>

            <decorator:getProperty property="..." [ default="..." ] [ writeEntireProperty="..." ]/>

            在標(biāo)簽處插入原始頁面(被包裝頁面)的原有的標(biāo)簽的屬性中的內(nèi)容,還可以添加一個(gè)缺省值。

            sitemesh文檔中的例子很好理解:
            The decorator: <body bgcolor="white"<decorator:getProperty property="body.onload" writeEntireProperty="true" />>
            The undecorated page: <body onload="document.someform.somefield.focus();">
            The decorated page: <body bgcolor="white" onload="document.someform.somefield.focus();">

            注意,writeEntireProperty="true"會(huì)在插入內(nèi)容前加入一個(gè)空格。

            <decorator:usePage id="..." />
            象jsp頁面中的<jsp:useBean>標(biāo)簽一樣,可以使用被包裝為一個(gè)Page對象的頁面。 (懶的用)

            例:可用<decorator:usePage id="page" /><%=page.getTitle()%>達(dá)到<decorator:title/>的訪問結(jié)果。

            <page:applyDecorator name="..." [ page="..." title="..." ] >
            <page:param name="..."> ... </page:param>
            <page:param name="..."> ... </page:param>
            </page:applyDecorator>

            應(yīng)用包裝器到指定的頁面上,一般用于被包裝頁面中主動(dòng)應(yīng)用包裝器。這個(gè)標(biāo)簽有點(diǎn)不好理解,我們來看一個(gè)例子:

            包裝器頁面 /decorators/panel.jsp:<p><decorator:title /></p>     ... <p><decorator:body /></p>
                 并且在decorators.xml中有<decorator name="panel" page="panel.jsp"/>

            一個(gè)公共頁面,即將被panel包裝:/public/date.jsp:  
                 ... <%=new java.util.Date()%>     ...<decorator:getProperty property="myEmail" />

            被包裝頁面 /page.jsp :
                 <title>page的應(yīng)用</title>
                 .....  

                 <page:applyDecorator name="panel" page="/_public/date.jsp" >
                   <page:param name="myEmail"> chen_p@neusoft.com </page:param>
                 </page:applyDecorator>

            最后會(huì)是什末結(jié)果呢?除了/page.jsp會(huì)被默認(rèn)的包裝頁面包裝上header,footer外,page.jsp頁面中還內(nèi)嵌了date.jsp頁面,并且此date.jsp頁面還會(huì)被panel.jsp包裝為一個(gè)title加body的有2段的頁面,第1段是date.jsp的title,第2段是date.jsp的body內(nèi)容。

            另外,page:applyDecorator中包含的page:param標(biāo)簽所聲明的屬性值還可以在包裝頁面中用decorator:getProperty標(biāo)簽訪問到。


            可打印的界面裝飾
                 前面說過有1種可打印的裝飾器,可以允許你當(dāng)用http://localhost/aaa/a.html?printable=true方式訪問時(shí),應(yīng)用其他的裝飾器(自己指定),給出原始頁面以供打印(免得把header,footer等的花哨的圖片也搭上)。

            讓我們來看一看怎樣實(shí)現(xiàn)他:

            1.首先在WEB-INFO/sitemesh.xml中設(shè)置:
                 <mapper class="com.opensymphony.module.sitemesh.mapper.PrintableDecoratorMapper">
                   <param name="decorator" value="printable" />
                   <param name="parameter.name" value="printable" />
                   <param name="parameter.value" value="true" />
                 </mapper>
            這樣就可以通過?printable=true來使用名為printable的裝飾器,而不是用原來的裝飾器。

            2.在WEB-INFO/decorators.xml中定義相應(yīng)的printable裝飾器
                 <decorator name="printable" page="printable.jsp"/>

            3.最后編寫printable裝飾器/decorators/printable.jsp

            <%@ taglib uri="sitemesh-decorator" prefix="decorator" %>
            <html>
            <head>
                 <title><decorator:title /></title>
                 <decorator:head />
            </head>
            <body>

                 <h1><decorator:title /></h1>
                 <p align="right"><i>(printable version)</i></p>

                 <decorator:body />

            </body>
            </html>

            這樣就可以讓一個(gè)原始頁面通過?printable=true開關(guān)來切換不同的裝飾器頁面。

             

            中文問題
            由于sitemesh內(nèi)部所使用的缺省字符集為iso-8859-1,直接使用會(huì)產(chǎn)生亂碼,我們可以通過以下方法糾正之:
            • 方法1:可以在您所用的application server的配置文件中找一找,有沒有設(shè)置encoding或charset的項(xiàng)目,然后設(shè)成gbk或gb2312即可
            • 方法2:這也是我們一直使用的方法。
              1.在每一個(gè)jsp頁里設(shè)置: <%@ page contentType="text/html; charset=gbk"%> 來告訴server你所要求的字符集。
              2.在每個(gè)jsp頁的head中定義:<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=gbk"> 來告訴瀏覽器你所用的字符集。
            總結(jié):使用sitemesh最通常的途徑:

            1.配置好環(huán)境,

            2.在WEB-INFO/decroators.xml中描述你將建立的包裝器。

            3.開發(fā)在decroators.xml中描述的包裝器,最好存放在/_decorators目錄下

            4.ok ,可以看看辛勤的成果了 :)

            posted @ 2009-11-22 09:55 jimphei 閱讀(197) | 評論 (0)編輯 收藏

            package com.yaday.test;

            import java.io.StringWriter;
            import java.util.Properties;

            import org.apache.velocity.Template;
            import org.apache.velocity.VelocityContext;
            import org.apache.velocity.app.Velocity;
            import org.apache.velocity.app.VelocityEngine;
            import org.junit.Test;

            public class VelocityTest {
                @Test 
            public void testVelocity(){
                    
            try {
                        VelocityEngine ve 
            = new VelocityEngine();
                        ve.setProperty(
            "resource.loader" , "class");
                        ve.setProperty(
            "class.resource.loader.class""org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
                        ve.init();
                        Template template
            =null;
                        template
            =ve.getTemplate("velocity/first.vm");

                        VelocityContext context
            =new VelocityContext();
                        context.put(
            "name"new String("jimphei"));
                        
                    
                        

                        StringWriter sw
            =new StringWriter();
                        template.merge(context, sw);
                        System.out.println(sw.toString());
                    }
             catch (Exception e) {
                        
            // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

            }

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

            Linux+Apache+PHP+MySQL是一個(gè)低成本效率高而又穩(wěn)定的WEB Server,但是我們絕大部分開發(fā)都是在Windows環(huán)境下完成開發(fā),然后移植到Linux或者Unix下?,F(xiàn)在依據(jù)個(gè)人體驗(yàn)來說明一下Windows XP+I(xiàn)IS下安裝Apache2+PHP 5。沒有IIS安裝就更加簡單,除去IIS相關(guān)步驟就可以了。

            一、關(guān)閉IIS,如果不關(guān)閉IIS安裝Apache會(huì)出錯(cuò)。apache整合tomcat配置

            關(guān)閉IIS有兩種方法,任意一種都可以:

            1. 控制面板--性能和維護(hù)--管理工具--服務(wù)中,關(guān)閉IIS Admin服務(wù)。
              控制面板--性能和維護(hù)--管理工具--服務(wù)中,關(guān)閉IIS Admin服務(wù)
            2. 在開始--運(yùn)行中直接輸入如下代碼,或者先輸入cmd,在彈出的窗口中輸入也行net stop iisadmin上述命令關(guān)閉了iis相關(guān)的所有服務(wù)器,比如web sites 、smtp等。net stop iisadmin /y避免輸入上面那個(gè)命令后需要在輸入y如果用net stop w3svc只是關(guān)閉一個(gè)站點(diǎn)3w服務(wù)器,但是如果是多個(gè)web站點(diǎn)就不行。

            如果開啟IIS可以在控制面板中找到interet信息服務(wù)打開網(wǎng)站服務(wù)的方法,也可以用命名,net start w3svc都可以。注意如果直接在服務(wù)中打開IIS Admin服務(wù)或者運(yùn)動(dòng)net start iisadmin,是可以打開IIS Admin服務(wù),但是3w服務(wù)沒有打開,所以依舊需要用上面的方法打開3w服務(wù),因?yàn)樵诖蜷_IIS Admin服務(wù)沒有打開3w服務(wù),但是打開3w服務(wù)肯定就打開了IIS Admin服務(wù)。

            二、安裝Apache2。

            ps,Apache 2不能在Windows 95上運(yùn)行;在Windows 98上勉強(qiáng)能夠運(yùn)行,但不能作為服務(wù)使用。從4.3版本開始,PHP也不再支持Windows 95。所以,你的Windows操作系統(tǒng)必須是Windows NT、2000或者XP。

            1. Apache可以到http://www.apache.org/dyn/closer.cgi/httpd/binaries/win32/下載
            2. 對于本機(jī)開發(fā)Network Domain,ServerName都填入localhost就可以了,填入email地址即可。
              安裝apache時(shí)需要填入的信息
            3. 上圖中的單項(xiàng)選擇,對于初學(xué)者來說,不管Apache的服務(wù)是否使用80單口,建議都選第一個(gè),這樣就直接把Apache注冊為系統(tǒng)服務(wù),穩(wěn)定方便。然后下一步選擇Typical。
            4. 安裝路徑一般會(huì)默認(rèn)為c:\Programme Files\Apache Group改成c:\web或者其他符合8.3格式的名稱,這樣以來以后每次輸入Apache安裝路徑不用加引號,并且Apache安裝時(shí)會(huì)自動(dòng)生成Apache2文件夾,所以文件會(huì)安裝到c:\web\apache2,這樣以后也可以把PHP,MySQL都安裝到web下便于幾種管理。
            5. 由于Apache&IIS都默認(rèn)WEB服務(wù)端口是80,所以其中一個(gè)必須修改其端口,一般改成8080
              修改IIS端口直接在IIS管理工具中就可以了??梢栽诳刂泼姘逯姓遥蛘咴谶\(yùn)行中輸入inetmgr
              修改Apache端口,通過開始-所有程序-Apache-Configure Apache Server打開httpd.conf文件,
              找到 #Listen 12.34.56.78:80   #是注釋符號
                  Listen 80  改成  Listen 8080
                  然后找到  ServerName localhost:80   改成  ServerName localhost:8080  即可
            6. 在瀏覽器中輸入localhost,如果修改了端口就輸入localhost:8080能夠看到apache頁面,就說明安裝成功了。

            ps[2005.9.29].利用apache的proxy模塊實(shí)現(xiàn)隱藏iis的端口

            1. 按照上面的方法,apache使用默認(rèn)端口80,修改iis使用端口為8080,當(dāng)然你也可以采用其他的合理端口。
            2. 修改apache的http.conf文件,去掉下面兩行代碼前的注釋符號#,啟動(dòng)代理模塊
              LoadModule proxy_module modules/mod_proxy.so
                  LoadModule proxy_http_module modules/mod_proxy_http.so
            3. 在該文件添加上如下兩行代碼,使輸入http://localhost/iis/轉(zhuǎn)向http://localhost:8080
              ProxyPass /iis/ http://127.0.0.1:8080/
                  ProxyPassReverse /iis http://127.0.0.1:8080

              這樣就可以在瀏覽器中輸入localhost訪問apache,輸入localhost/iis/訪問iis了而隱藏了8080端口

            4. 另外,可以通過設(shè)置虛擬主機(jī)來訪問apache或者iis
              <VirtualHost *:80>
                  ServerAdmin kavenyan@163.com
                  DocumentRoot E:/www/dancewithnet
                  ServerName www.dancewithnet.com
                  ServerAlias dancewithnet.com
                  DefaultLanguage zh-CN
                  AddDefaultCharset UTF-8
                  </VirtualHost>
                  <VirtualHost *:80>
                  ServerAdmin kavenyan@163.com
                  ServerName iis.dancewithnet.com
                  DefaultLanguage zh-CN
                  AddDefaultCharset GB2312
                  ProxyPass / http://127.0.0.1:8080/  or http://服務(wù)器ip:8080/
                  ProxyPassReverse / http://127.0.0.1:8080/   or http://服務(wù)器ip:8080/
                  </VirtualHost>

              這樣就可以使用www.dancewithnet.com訪問apache,iis.dancewithnet.com訪問iss,而隱藏了8080端口

              三、配置PHP環(huán)境

              1. www.php.net上下載php5的zip安裝包,將其文件解壓放到c:\web\php5中即可

                ps, Apache 2可采取2種方式來運(yùn)行PHP程序:通過一個(gè)CGI接口來運(yùn)行(外部調(diào)用Php.exe),或者使用PHP的DLL文件在Apache的內(nèi)部運(yùn)行。后一種方式的速度較快。所以,針對每個(gè)版本的PHP,都會(huì)提供2個(gè)Windows二進(jìn)制發(fā)行包。較小的是.msi包,它會(huì)安裝CGI可執(zhí)行程序Php.exe,但其中拿掉了通過Apache DLL來運(yùn)行PHP腳本所需的模塊。較大的.zip包則包含了所有這些東西

              2. 最好是無論使用何種接口(CGI 或者 SAPI)都確保 php5ts.dll 可用,因此必須將此文件放到 Windows 路徑中。最好的位置是 Windows 的 system 目錄(%windir%\System):
                c:\\winnt\\system32 for Windows NT/2000
                        或者
                        c:\\winnt40\\system32 for Windows NT/2000 服務(wù)器版
                        c:\\windows\\system32 for Windows XP

                ps,也有把php文件中所有的dll文件都拷到%windir%\System中的,那樣的配置和我介紹的方法稍微有點(diǎn)不同,但是我覺得那樣比較雜亂,就不再說明,有興趣的朋友可以自己研究。

              3. 接著實(shí)設(shè)定有效的PHP 配置文件,php.ini。壓縮包中包括兩個(gè) ini 文件,php.ini-dist 和 php.ini-recommended。建議使用 php.ini-recommended,因?yàn)榇宋募δJ(rèn)設(shè)置作了性能和安全上的優(yōu)化。將選擇的 ini 文件拷貝到 PHP 能夠找到的目錄下并改名為 php.ini。PHP 默認(rèn)在 Windows 目錄(%WINDIR% 或 %SYSTEMROOT% )下搜索 php.ini:
                c:\\winnt 或 c:\\winnt40  for Windows NT/2000 服務(wù)器版
                        c:\windows  for Windows XP
                        
              4. 停止Apache,打開httpd.conf進(jìn)行編輯。
                如果是使用CGI二進(jìn)制文件的形式來使用php,添入代碼如下(注意代碼間的空格):

                 

                ScriptAlias /php/ "c:/web/php5/"
                        AddType application/x-httpd-php .php
                        Action application/x-httpd-php "/php5/php.exe"
                        

                如果作為模塊(推薦這種方式),添加代碼如下:

                LoadModule php5_module "c:/web/php5/php5apache2.dll"
                        AddType application/x-httpd-php .php
                        
              5. 保存httpd.conf,啟動(dòng)Apache

              四、測試PHP

              1. 編寫文件index.php放入C:\web\Apache2\htdocs中,代碼如下:
                測試PHP安裝是否成功的代碼
              2. 在瀏覽中輸入http://localhost/index.php效果如下,則說明安裝成功:
                php安裝成功出現(xiàn)的頁面
            posted @ 2009-11-04 10:24 jimphei 閱讀(346) | 評論 (0)編輯 收藏

            這個(gè)是mysql版本不同的問題

            posted @ 2009-11-03 15:50 jimphei 閱讀(189) | 評論 (0)編輯 收藏

            1、后臺ajax在應(yīng)用(特別是提交中文時(shí)要用encodeURI(encodeURI(typename))提交,然后后臺用URLDecoder.decode(strtypename, "utf-8")取值。
            2、java-fckeditor在應(yīng)用與配置。
            3、jquery的應(yīng)用。
            4、二級目錄與多級目錄的學(xué)習(xí)。
            5、驗(yàn)證碼生成技術(shù)。
            posted @ 2009-11-03 09:35 jimphei 閱讀(148) | 評論 (0)編輯 收藏

            Struts2+JQuery+JSON集成


            細(xì)節(jié)部分我就不多講了,因?yàn)槲乙膊粫?huì),就講講我是如何調(diào)試出來我的第一個(gè)JSON使用的吧

            采用的框架有:Struts2 、 JQuery 、 JSON


            按著步驟來吧:


             1.新建一個(gè)Web工程


            導(dǎo)入包列表:

             


             目錄結(jié)構(gòu)如圖:

             


             2.建立實(shí)體類User

            package model;


            public class User


            private String name;

            private int age;

             //省略相應(yīng)的get和set方法
             


             3.建立Action JsonAction

            public class JsonAction extends ActionSupport{

            private static final long serialVersionUID =

             7044325217725864312L;


            private User user;

            //用于記錄返回結(jié)果

            private String result;


            //省略相應(yīng)的get和set方法


            @SuppressWarnings("static-access")


            public String execute() throws Exception {


            //將要返回的user實(shí)體對象進(jìn)行json處理

            JSONObject jo = JSONObject.fromObject(this.user);

            //打印一下,格式如下

            //{"name":"風(fēng)達(dá)","age":23}

            System.out.println(jo);


            //調(diào)用json對象的toString方法轉(zhuǎn)換為字符串然后賦值給result

            this.result = jo.toString();


            return this.SUCCESS;

            }


            }
             


             4.建立struts.xml文件

            <?xml version="1.0" encoding="UTF-8"?>

            <!DOCTYPE struts PUBLIC

                "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

                "http://struts.apache.org/dtds/struts-2.0.dtd">


            <struts>

            <constant name="struts.i18n.encoding" value="UTF-8"></constant>

            <package name="ttttt" extends="json-default">

            <action name="jsonAction" class="action.JsonAction">

            <result type="json" >

            <!-- 因?yàn)橐獙eslut的值返回給客戶端,所以這樣設(shè)置 -->

            <!-- root的值對應(yīng)要返回的值的屬性 -->

            <param name="root">

            result

            </param>

            </result>

            </action>

            </package>

            </struts>

             


             5.編寫index.jsp文件

            <%@ page language="java" pageEncoding="UTF-8"%>

            <%@ taglib prefix="s" uri="/struts-tags"%>

            <%

            String path = request.getContextPath();

            String basePath = request.getScheme() + "://"

            + request.getServerName() + ":" + request.getServerPort()

            + path + "/";

            %>


            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

            <html>

            <head>

            <base href="<%=basePath%>">


            <title>My JSP 'index.jsp' starting page</title>

            <meta http-equiv="pragma" content="no-cache">

            <meta http-equiv="cache-control" content="no-cache">

            <meta http-equiv="expires" content="0">

            <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

            <meta http-equiv="description" content="This is my page">


            <!-- basePath用來獲取js文件的絕對路徑 -->

            <script type="text/javascript" src="<%=basePath%>js/jquery.js"></script>

            <script type="text/javascript" src="<%=basePath%>js/index.js"></script>

            <s:head theme="ajax" />

            </head>


            <body>

            <div id="result">

            </div>

            <s:form name="userForm" action="" method="post">

            <s:textfield label="用戶名" name="user.name" />

            <s:textfield label="年齡" name="user.age" />

            <button>

            提交

            </button>

            </s:form>


            </body>

            </html>

             


             6.在WebRoot目錄下建立js文件件,將jquery.js文件放到文件夾下,然后再建立文件index.js


            $(document).ready(function() {


            // 直接把onclick事件寫在了JS中

            $("button").click(function() {

            // 序列化表單的值

            var params = $("input").serialize();


            $.ajax({


            // 后臺處理程序

            url : "jsonAction.action",


            // 數(shù)據(jù)發(fā)送方式

            type : "post",


            // 接受數(shù)據(jù)格式

            dataType : "json",


            // 要傳遞的數(shù)據(jù)

            data : params,


            // 回傳函數(shù)

            success : update_page


            });

            });


            });

            function update_page(result) {

            var json = eval( "("+result+")" );

            var str = "姓名:" + json.name + "<br />"; str += "年齡:"

            + json.age + "<br />";

            $("#result").html(str);


            }
             


             7.運(yùn)行前效果:

             

            要的是效果,布局就不整了

             


            運(yùn)行后效果:

             

             


            網(wǎng)上相關(guān)的信息太少了,很多Struts2+JQuery+JSON的教程,點(diǎn)開鏈接之后都是那幾篇文章轉(zhuǎn)了又轉(zhuǎn),遇到問題真的很想找到有用的信息,或許是我太笨了,找不到,或許就是網(wǎng)上相關(guān)的信息就很少。這個(gè)實(shí)例很簡單是不是,但是為了調(diào)試出這個(gè)程序,我費(fèi)了一天的時(shí)間。


            上面的實(shí)例成功了,但是問題又出來了

            視圖類型僅僅設(shè)置了json

            那么輸入校驗(yàn)出錯(cuò)的時(shí)候怎么顯示?


            本文來自CSDN博客,轉(zhuǎn)載請標(biāo)明出處:http://blog.csdn.net/fengda2870/archive/2009/04/06/4052527.aspx

            posted @ 2009-09-30 12:52 jimphei 閱讀(831) | 評論 (0)編輯 收藏

            今天看到某人寫的分頁類,結(jié)果發(fā)現(xiàn)批人家的人不少,沒有必要,好的東西吸收學(xué)習(xí),感覺不實(shí)用可以不用,何必發(fā)帖子挖苦人家。我前段時(shí)間也自己設(shè)計(jì)了一個(gè)分頁的方法,絕對是自己想到的,如果網(wǎng)上有一樣的,說明大家都思考了,有可取度,提供給大家參考。
            首先寫了一個(gè)分頁的類,其實(shí)只有主要屬性的setter和getter方法
            /**
            * 分頁類
            * @author qinglin876
            *
            */
            public class Pagination {
            private int start;
            //一次取得的數(shù)量
            private int size;
            //要取得頁數(shù)
            private int currentPage = 1;
            //總的記錄頁數(shù)
            private int totalPage = 0;
            //總的記錄條數(shù)
            private int totalRecord;
            public int getTotalRecord() {
            return totalRecord;
            }
            public void setTotalRecord(int totalRecord) {
            this.totalRecord = totalRecord;
            }
            public Pagination(){

            }
            public Pagination(int size){
            this.size = size;
            }
            public int getSize() {
            return size;
            }
            public void setSize(int size) {
            this.size = size;
            }
            public int getStart() {
            return start;
            }
            public void setStart(int start) {
            this.start = start;
            }
            public int getCurrentPage() {
            return currentPage;
            }
            public void setCurrentPage(int currentPage) {
            this.currentPage = currentPage;
            }
            public int getTotalPage() {
            return totalPage;
            }
            public void setTotalPage(int totalPage) {
            this.totalPage = totalPage;
            }

            }

            另外pagination.jsp由pagination類填充

            <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

            <%@ taglib prefix="s" uri="/struts-tags"%>
            <SCRIPT type="text/javascript">

                  function trim(str){
            return str.replace(/(^\s*)|(\s*$)/g, "");
            }

            function selectPage(input){

            var value = trim(input.value);
            if(value == ""){
            return;
            }

            if(/\d+/.test(value)){

            input.form.submit();
            return;
            }
            alert("請輸入正確的頁數(shù)");
            input.focus();

            }
               
            </SCRIPT>
            <div class="pagech">

            <s:if test="pagination.totalPage != 0">
            <s:url action="%{#request.url}" id="first">
            <s:param name="pagination.currentPage" value="1"></s:param>
            </s:url>
            <s:url action="%{#request.url}" id="next"  >
            <s:param name="pagination.currentPage"
            value="pagination.currentPage+1">
            </s:param>
            </s:url>
            <s:url action="%{#request.url}" id="prior" >
            <s:param name="pagination.currentPage"
            value="pagination.currentPage-1"></s:param>
            </s:url>
            <s:url action="%{#request.url}" id="last">
            <s:param name="pagination.currentPage" value="pagination.totalPage"></s:param>
            </s:url>
            <s:if test="pagination.currentPage == 1">
            <span class="current">首頁</span>
            <span class="current">上一頁</span>
            </s:if>
            <s:else>
            <s:a href="%{first}">首頁</s:a>
            <s:a href="%{prior}">上一頁</s:a>
            </s:else>
            <s:if
            test="pagination.currentPage == pagination.totalPage || pagination.totalPage == 0">
            <span class="current">下一頁</span>
            <span class="current">末頁</span>
            </s:if>
            <s:else>
            <s:a href="%{next}">下一頁</s:a>&nbsp;&nbsp;
                              <s:a href="%{last}">末頁</s:a>
            </s:else>
            <span class="jumplabel">跳轉(zhuǎn)到</span>
            <s:form action="%{#request.url}" theme="simple"
            cssStyle="display:inline">
            <s:hidden name="pagination.totalPage" value="%{pagination.totalPage}"></s:hidden>
            <input type="text" name="pagination.currentPage" size="2"
            onblur="selectPage(this)" />
            </s:form>

            <span class="jumplabel">頁</span>
            <span class="jumplabel">共<s:property
            value="pagination.totalRecord" />條</span>
            <span class="jumplabel">當(dāng)前是第<s:property
            value="pagination.currentPage" />/<s:property value="pagination.totalPage"/>頁</span>


            </s:if>

            </div>

            用的時(shí)候,在頁面include進(jìn)去,注意上面的"%{#request.url}",即是在struts2的action里面有一個(gè)setter和getter方法,下面看action中的某個(gè)方法
            public String showNotices() throws Exception{

            if(tip != null){
            tip = new String(tip.getBytes("iso8859-1"),"utf-8");
            }
            if(notices == null)
            this.notices = new ArrayList<Notice>();
            int size = Integer.valueOf(this.getText("per_page_notice_size"));
            if (pagination == null) {
            pagination = new Pagination(size);
            }
            pagination.setSize(size);
            if (pagination.getCurrentPage() <= 0) {
            pagination.setCurrentPage(1);
            }
            if (pagination.getTotalPage() != 0
            && pagination.getCurrentPage() > pagination.getTotalPage()) {
            pagination.setCurrentPage(pagination.getTotalPage());
            }
            url = "goto_showNotices.action"; this.notices.addAll(this.noticeDAO.showAll(pagination));
            if(this.notices.size() == 0 && pagination.getCurrentPage() != 1){
            pagination.setCurrentPage(pagination.getCurrentPage()-1);
            this.notices.addAll(this.noticeDAO.showAll(pagination));
            }
            return "success";
            }

            在上面的this.noticeDAO.showAll(pagination))中填充pagination,具體如下
            /*
            * 顯示所有的通告
            * @see com.qinglin.dao.NoticeDAO#showAll(com.qinglin.util.Pagination)
            */
            @SuppressWarnings("unchecked")
            public List<Notice> showAll(final Pagination pagination) {
            String hql = "from Notice as n";
            this.getHibernateTemplate().setCacheQueries(true);
            int totalRecord = ((Long) this.getSession().createQuery(
            "select count(*) " + hql).uniqueResult()).intValue();
            int totalPage = totalRecord % pagination.getSize() == 0 ? totalRecord
            / pagination.getSize() : totalRecord / pagination.getSize() + 1;
            pagination.setTotalRecord(totalRecord);
            pagination.setTotalPage(totalPage);
            hql += " order by n.add_date desc";
            final String hql1 = hql;

            return (List<Notice>) this.getHibernateTemplate().execute(
            new HibernateCallback() {
            public Object doInHibernate(Session session)
            throws HibernateException, SQLException {
            Query query = session.createQuery(hql1);
            query.setFirstResult((pagination.getCurrentPage() - 1)
            * pagination.getSize());
            query.setMaxResults(pagination.getSize());
            return query.list();
            }
            });
            }


            基本上就這些,當(dāng)然請求的action里面需要設(shè)置pagination的setter和getter方法
            這個(gè)分頁方法特點(diǎn)是簡單,只需在action中指明請求的url,用某種方法填充pagination,在顯示的頁面包含pagination.jsp即可。



            package com.shop.bean;

            import java.util.List;

            public class PageView <T> {

            private int currentPage = 1;

            private long totalPage = 1;

            private long totalRecord = 1;

            private List <T> records;

            private int firstIndex = 1;

            private PageIndex pageIndex;

            private int maxResult = 12;

            public PageView(int currentPage, int maxResult) {
            this.currentPage = currentPage;
            this.maxResult = maxResult;
            this.firstIndex = currentPage * maxResult;
            }

            public int getCurrentPage() {
            return currentPage;
            }

            public void setCurrentPage(int currentPage) {
            this.currentPage = currentPage;
            }

            public void setQueryResult(QueryResult <T> qr){
            setTotalRecord(qr.getTotal());
            setRecords(qr.getDatas());
            }

            public long getTotalPage() {
            return totalPage;
            }

            public void setTotalPage(long totalPage) {
            this.totalPage = totalPage;
            this.pageIndex = WebTool.getPageIndex(this.maxResult, this.currentPage, this.totalPage);
            }

            public long getTotalRecord() {
            return totalRecord;
            }

            public void setTotalRecord(long totalRecord) {
            this.totalRecord = totalRecord;
            setTotalPage(totalRecord / this.maxResult == 0 ? totalRecord / this.maxResult : totalRecord / this.maxResult + 1);
            }

            public List <T> getRecords() {
            return records;
            }

            public void setRecords(List <T> records) {
            this.records = records;
            }

            public int getFirstIndex() {
            return firstIndex;
            }
            public PageIndex getPageIndex() {
            return pageIndex;
            }

            public void setPageIndex(PageIndex pageIndex) {
            this.pageIndex = pageIndex;
            }

            public int getMaxResult() {
            return maxResult;
            }

            public void setMaxResult(int maxResult) {
            this.maxResult = maxResult;
            }

            public void setFirstIndex(int firstIndex) {
            this.firstIndex = firstIndex;
            }
            }


            畫面的代碼:
            <s:iterator value="#request.pageView.pageIndex.pageList">
                  <s:if test="#request.pageView.currentPage == 4"> <b> <font color="#FFFFFF">第 <s:property/>頁 </font> </b> </s:if>
                <s:if test="#request.pageView.currentPage != 4"> <a href="javascript:topage( <s:property/>)" class="a03">第 <s:property/>頁 </a> </s:if>
            </s:iterator>

            action中的代碼:
            Map <String, Object> request = (Map <String, Object>)ActionContext.getContext().get("request");
            request.put("pageView", pageView);




            <s:iterator value="#request.pageView.pageIndex.pageList">中="#request.pageView.pageIndex.pageList值能正常獲取,可是  <s:if test="#request.pageView.currentPage == 4"> 中的="#request.pageView.currentPage值獲取不到正確的值,這是什么原因???
            問題補(bǔ)充:
              <s:iterator value="#request.pageView.pageIndex.pageList">
                <s:if test="{#request.pageView.currentPage == 4}"><b><font color="#FFFFFF">第<s:property/>頁</font></b></s:if>
                <s:if test="{#request.pageView.currentPage != 4}"><a href="javascript:topage(<s:property/>)" class="a03">第<s:property/>頁</a></s:if>
            </s:iterator>
            posted @ 2009-09-22 12:03 jimphei 閱讀(211) | 評論 (0)編輯 收藏

            主站蜘蛛池模板: 织金县| 南和县| 沂水县| 准格尔旗| 商城县| 太原市| 清河县| 东乌| 通州区| 博野县| 甘泉县| 淄博市| 宝清县| 镇赉县| 岚皋县| 虎林市| 巫溪县| 博客| 万山特区| 四平市| 灵川县| 永清县| 高安市| 团风县| 同德县| 宁蒗| 康保县| 通道| 淮滨县| 聊城市| 获嘉县| 汶川县| 通城县| 竹溪县| 顺昌县| 含山县| 张家港市| SHOW| 东乡族自治县| 逊克县| 舒兰市|