jimphei学习工作室

jimphei学习工作室

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  23 随笔 :: 0 文章 :: 1 评论 :: 0 Trackbacks

2009年11月26日 #

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 阅读(1133) | 评论 (0)编辑 收藏

2009年11月23日 #

引用自: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 阅读(271) | 评论 (0)编辑 收藏

2009年11月22日 #

 sitemesh应用Decorator模式,用filter截取request和response,把页面组件head,content,banner结合为一个完整的视图。通常我们都是用include标签在每个jsp页面中来不断的包含各种header, stylesheet, scripts and footer,现在,在sitemesh的帮助下,我们可以开心的删掉他们了。如下图,你想轻松的达到复合视图模式,那末看完本文吧。

一、在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>

  上面配置文件指定了装饰器页面所在的路径,并指定了一个名为main的装饰器,该装饰器默认装饰web应用根路径下的所有页面。

四、
建立装饰器页面 /decorators/main.jsp

  • <%@ 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>
     

    五、建立一个的被装饰页面 /index.jsp(内容页面)

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

      最后访问index.jsp,将生成如下页面:

          而且,所有的页面也会如同index.jsp一样,被sitemesh的filter使用装饰模式修改成如上图般模样,却不用再使用include标签。



    1. 装饰器     decorator概念
          为了建立可复用的web应用程序,一个通用的方法是建立一个分层系统,如同下面一个普通的web应用:
      • 前端:JSP和Servlets,或jakarta的velocity 。。。
      • 控制层框架 Controller : (Struts/Webwork)
      • 业务逻辑 Business :主要业务逻辑
      • 持久化框架 :hibernate/jdo

          可糟糕的是前端的页面逻辑很难被复用,当你在每一个页面中用数之不尽的include来复用公共的header, stylesheet, scripts,footer时,一个问题出现了-重复的代码,每个页面必须用copy来复用页面结构,而当你需要创意性的改变页面结构时,灾难就爱上了你。

           sitemesh通过filter截取request和response,并给原始的页面加入一定的装饰(可能为header,footer...),然后把结果返回给客户端,并且被装饰的原始页面并不知道sitemesh的装饰,这也就达到了脱耦的目的。

           据说即将新出台的Portlet规范会帮助我们标准的实现比这些更多更cool的想法,但可怜的我还不懂它到底是一个什末东东,有兴趣的人可以研究
      jetspeed,或JSR (Java Specification Request) 168,但我想sitemesh如此简单,我们不妨先用着。

       

      让我们看看怎样配置环境
          除了要copy到WEB-INF/lib中的sitemesh.jar外,还有2个文件要建立到WEB-INF/:
      • sitemesh.xml (可选)  
      • decorators.xml

      sitemesh.xml 可以设置2种信息:

      Page Parsers :负责读取stream的数据到一个Page对象中以被SiteMesh解析和操作。(不太常用,默认即可)

      Decorator Mappers : 不同的装饰器种类,我发现2种比较有用都列在下面。一种通用的mapper,可以指定装饰器的配置文件名,另一种可打印的装饰器,可以允许你当用http://localhost/aaa/a.html?printable=true方式访问时给出原始页面以供打印(免得把header,footer等的花哨的图片也搭上)

      (但一般不用建立它,默认设置足够了: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 :定义构成复合视图的所有页面构件的描述(主要结构页面,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 : 匹配的路径,可以用*,那些被访问的页面需要被装饰。

       

      最重要的是写出装饰器本身(也就是那些要复用页面,和结构页面)。
          其实,重要的工作就是制作装饰器页面本身(也就是包含结构和规则的页面),然后把他们描述到decorators.xml中。

          让我们来先看一看最简单的用法:其实最常用也最简单的用法就是我们的hello例子,面对如此众多的技术,我想只要达到功能点到为止即可,没必要去研究太深(除非您有更深的需求)。

      <%@ 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个标签:

      <decorator:title default="装饰器页面..." />       : 把请求的原始页面的title内容插入到<title></title>中间。

      <decorator:body /> : 把请求的原始页面的body内的全部内容插入到相应位置。

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

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

      这样,请求的所有页面都会被重新处理,并按照main.jsp的格式重新展现在你面前。

       

      让我们看看更多的用法。(抄袭sitemesh文档)
      以下列着全部标签:
      Decorator Tags Page Tags
      被用于建立装饰器页面. 被用于从原始内容页面访问装饰器.
      <decorator:head />
      <decorator:body />
      <decorator:title />
      <decorator:getProperty />
      <decorator:usePage />
      <page:applyDecorator />
      <page:param
       

      <decorator:head />

      插入原始页面(被包装页面)的head标签中的内容(不包括head标签本身)。

      <decorator:body />

      插入原始页面(被包装页面)的body标签中的内容。

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

      插入原始页面(被包装页面)的title标签中的内容,还可以添加一个缺省值。

      例:

      /decorator/main.jsp中 (装饰器页面): <title><decorator:title default="却省title-hello"     /> - 附加标题</title>

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

      访问/aaa.jsp的结果:<title>aaa页面 - 附加标题</title>

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

      在标签处插入原始页面(被包装页面)的原有的标签的属性中的内容,还可以添加一个缺省值。

      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"会在插入内容前加入一个空格。

      <decorator:usePage id="..." />
      象jsp页面中的<jsp:useBean>标签一样,可以使用被包装为一个Page对象的页面。 (懒的用)

      例:可用<decorator:usePage id="page" /><%=page.getTitle()%>达到<decorator:title/>的访问结果。

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

      应用包装器到指定的页面上,一般用于被包装页面中主动应用包装器。这个标签有点不好理解,我们来看一个例子:

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

      一个公共页面,即将被panel包装:/public/date.jsp:  
           ... <%=new java.util.Date()%>     ...<decorator:getProperty property="myEmail" />

      被包装页面 /page.jsp :
           <title>page的应用</title>
           .....  

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

      最后会是什末结果呢?除了/page.jsp会被默认的包装页面包装上header,footer外,page.jsp页面中还内嵌了date.jsp页面,并且此date.jsp页面还会被panel.jsp包装为一个title加body的有2段的页面,第1段是date.jsp的title,第2段是date.jsp的body内容。

      另外,page:applyDecorator中包含的page:param标签所声明的属性值还可以在包装页面中用decorator:getProperty标签访问到。


      可打印的界面装饰
           前面说过有1种可打印的装饰器,可以允许你当用http://localhost/aaa/a.html?printable=true方式访问时,应用其他的装饰器(自己指定),给出原始页面以供打印(免得把header,footer等的花哨的图片也搭上)。

      让我们来看一看怎样实现他:

      1.首先在WEB-INFO/sitemesh.xml中设置:
           <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中定义相应的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>

      这样就可以让一个原始页面通过?printable=true开关来切换不同的装饰器页面。

       

      中文问题
      由于sitemesh内部所使用的缺省字符集为iso-8859-1,直接使用会产生乱码,我们可以通过以下方法纠正之:
      • 方法1:可以在您所用的application server的配置文件中找一找,有没有设置encoding或charset的项目,然后设成gbk或gb2312即可
      • 方法2:这也是我们一直使用的方法。
        1.在每一个jsp页里设置: <%@ page contentType="text/html; charset=gbk"%> 来告诉server你所要求的字符集。
        2.在每个jsp页的head中定义:<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=gbk"> 来告诉浏览器你所用的字符集。
      总结:使用sitemesh最通常的途径:

      1.配置好环境,

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

      3.开发在decroators.xml中描述的包装器,最好存放在/_decorators目录下

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

      posted @ 2009-11-22 09:55 jimphei 阅读(184) | 评论 (0)编辑 收藏

      2009年11月10日 #

      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 阅读(531) | 评论 (0)编辑 收藏

      2009年11月4日 #

      Linux+Apache+PHP+MySQL是一个低成本效率高而又稳定的WEB Server,但是我们绝大部分开发都是在Windows环境下完成开发,然后移植到Linux或者Unix下。现在依据个人体验来说明一下Windows XP+IIS下安装Apache2+PHP 5。没有IIS安装就更加简单,除去IIS相关步骤就可以了。

      一、关闭IIS,如果不关闭IIS安装Apache会出错。apache整合tomcat配置

      关闭IIS有两种方法,任意一种都可以:

      1. 控制面板--性能和维护--管理工具--服务中,关闭IIS Admin服务。
        控制面板--性能和维护--管理工具--服务中,关闭IIS Admin服务
      2. 在开始--运行中直接输入如下代码,或者先输入cmd,在弹出的窗口中输入也行net stop iisadmin上述命令关闭了iis相关的所有服务器,比如web sites 、smtp等。net stop iisadmin /y避免输入上面那个命令后需要在输入y如果用net stop w3svc只是关闭一个站点3w服务器,但是如果是多个web站点就不行。

      如果开启IIS可以在控制面板中找到interet信息服务打开网站服务的方法,也可以用命名,net start w3svc都可以。注意如果直接在服务中打开IIS Admin服务或者运动net start iisadmin,是可以打开IIS Admin服务,但是3w服务没有打开,所以依旧需要用上面的方法打开3w服务,因为在打开IIS Admin服务没有打开3w服务,但是打开3w服务肯定就打开了IIS Admin服务。

      二、安装Apache2。

      ps,Apache 2不能在Windows 95上运行;在Windows 98上勉强能够运行,但不能作为服务使用。从4.3版本开始,PHP也不再支持Windows 95。所以,你的Windows操作系统必须是Windows NT、2000或者XP。

      1. Apache可以到http://www.apache.org/dyn/closer.cgi/httpd/binaries/win32/下载
      2. 对于本机开发Network Domain,ServerName都填入localhost就可以了,填入email地址即可。
        安装apache时需要填入的信息
      3. 上图中的单项选择,对于初学者来说,不管Apache的服务是否使用80单口,建议都选第一个,这样就直接把Apache注册为系统服务,稳定方便。然后下一步选择Typical。
      4. 安装路径一般会默认为c:\Programme Files\Apache Group改成c:\web或者其他符合8.3格式的名称,这样以来以后每次输入Apache安装路径不用加引号,并且Apache安装时会自动生成Apache2文件夹,所以文件会安装到c:\web\apache2,这样以后也可以把PHP,MySQL都安装到web下便于几种管理。
      5. 由于Apache&IIS都默认WEB服务端口是80,所以其中一个必须修改其端口,一般改成8080
        修改IIS端口直接在IIS管理工具中就可以了。可以在控制面板中找,或者在运行中输入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模块实现隐藏iis的端口

      1. 按照上面的方法,apache使用默认端口80,修改iis使用端口为8080,当然你也可以采用其他的合理端口。
      2. 修改apache的http.conf文件,去掉下面两行代码前的注释符号#,启动代理模块
        LoadModule proxy_module modules/mod_proxy.so
            LoadModule proxy_http_module modules/mod_proxy_http.so
      3. 在该文件添加上如下两行代码,使输入http://localhost/iis/转向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. 另外,可以通过设置虚拟主机来访问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://服务器ip:8080/
            ProxyPassReverse / http://127.0.0.1:8080/   or http://服务器ip:8080/
            </VirtualHost>

        这样就可以使用www.dancewithnet.com访问apache,iis.dancewithnet.com访问iss,而隐藏了8080端口

        三、配置PHP环境

        1. www.php.net上下载php5的zip安装包,将其文件解压放到c:\web\php5中即可

          ps, Apache 2可采取2种方式来运行PHP程序:通过一个CGI接口来运行(外部调用Php.exe),或者使用PHP的DLL文件在Apache的内部运行。后一种方式的速度较快。所以,针对每个版本的PHP,都会提供2个Windows二进制发行包。较小的是.msi包,它会安装CGI可执行程序Php.exe,但其中拿掉了通过Apache DLL来运行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 服务器版
                  c:\\windows\\system32 for Windows XP

          ps,也有把php文件中所有的dll文件都拷到%windir%\System中的,那样的配置和我介绍的方法稍微有点不同,但是我觉得那样比较杂乱,就不再说明,有兴趣的朋友可以自己研究。

        3. 接着实设定有效的PHP 配置文件,php.ini。压缩包中包括两个 ini 文件,php.ini-dist 和 php.ini-recommended。建议使用 php.ini-recommended,因为此文件对默认设置作了性能和安全上的优化。将选择的 ini 文件拷贝到 PHP 能够找到的目录下并改名为 php.ini。PHP 默认在 Windows 目录(%WINDIR% 或 %SYSTEMROOT% )下搜索 php.ini:
          c:\\winnt 或 c:\\winnt40  for Windows NT/2000 服务器版
                  c:\windows  for Windows XP
                  
        4. 停止Apache,打开httpd.conf进行编辑。
          如果是使用CGI二进制文件的形式来使用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,启动Apache

        四、测试PHP

        1. 编写文件index.php放入C:\web\Apache2\htdocs中,代码如下:
          测试PHP安装是否成功的代码
        2. 在浏览中输入http://localhost/index.php效果如下,则说明安装成功:
          php安装成功出现的页面
      posted @ 2009-11-04 10:24 jimphei 阅读(334) | 评论 (0)编辑 收藏

      2009年11月3日 #

      这个是mysql版本不同的问题

      posted @ 2009-11-03 15:50 jimphei 阅读(175) | 评论 (0)编辑 收藏

      1、后台ajax在应用(特别是提交中文时要用encodeURI(encodeURI(typename))提交,然后后台用URLDecoder.decode(strtypename, "utf-8")取值。
      2、java-fckeditor在应用与配置。
      3、jquery的应用。
      4、二级目录与多级目录的学习。
      5、验证码生成技术。
      posted @ 2009-11-03 09:35 jimphei 阅读(138) | 评论 (0)编辑 收藏

      2009年9月30日 #

      Struts2+JQuery+JSON集成


      细节部分我就不多讲了,因为我也不会,就讲讲我是如何调试出来我的第一个JSON使用的吧

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


      按着步骤来吧:


       1.新建一个Web工程


      导入包列表:

       


       目录结构如图:

       


       2.建立实体类User

      package model;


      public class User


      private String name;

      private int age;

       //省略相应的get和set方法
       


       3.建立Action JsonAction

      public class JsonAction extends ActionSupport{

      private static final long serialVersionUID =

       7044325217725864312L;


      private User user;

      //用于记录返回结果

      private String result;


      //省略相应的get和set方法


      @SuppressWarnings("static-access")


      public String execute() throws Exception {


      //将要返回的user实体对象进行json处理

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

      //打印一下,格式如下

      //{"name":"风达","age":23}

      System.out.println(jo);


      //调用json对象的toString方法转换为字符串然后赋值给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" >

      <!-- 因为要将reslut的值返回给客户端,所以这样设置 -->

      <!-- root的值对应要返回的值的属性 -->

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


      // 数据发送方式

      type : "post",


      // 接受数据格式

      dataType : "json",


      // 要传递的数据

      data : params,


      // 回传函数

      success : update_page


      });

      });


      });

      function update_page(result) {

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

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

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

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


      }
       


       7.运行前效果:

       

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

       


      运行后效果:

       

       


      网上相关的信息太少了,很多Struts2+JQuery+JSON的教程,点开链接之后都是那几篇文章转了又转,遇到问题真的很想找到有用的信息,或许是我太笨了,找不到,或许就是网上相关的信息就很少。这个实例很简单是不是,但是为了调试出这个程序,我费了一天的时间。


      上面的实例成功了,但是问题又出来了

      视图类型仅仅设置了json

      那么输入校验出错的时候怎么显示?


      本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/fengda2870/archive/2009/04/06/4052527.aspx

      posted @ 2009-09-30 12:52 jimphei 阅读(813) | 评论 (0)编辑 收藏

      2009年9月22日 #

      今天看到某人写的分页类,结果发现批人家的人不少,没有必要,好的东西吸收学习,感觉不实用可以不用,何必发帖子挖苦人家。我前段时间也自己设计了一个分页的方法,绝对是自己想到的,如果网上有一样的,说明大家都思考了,有可取度,提供给大家参考。
      首先写了一个分页的类,其实只有主要属性的setter和getter方法
      /**
      * 分页类
      * @author qinglin876
      *
      */
      public class Pagination {
      private int start;
      //一次取得的数量
      private int size;
      //要取得页数
      private int currentPage = 1;
      //总的记录页数
      private int totalPage = 0;
      //总的记录条数
      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("请输入正确的页数");
      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">跳转到</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">当前是第<s:property
      value="pagination.currentPage" />/<s:property value="pagination.totalPage"/>页</span>


      </s:if>

      </div>

      用的时候,在页面include进去,注意上面的"%{#request.url}",即是在struts2的action里面有一个setter和getter方法,下面看action中的某个方法
      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();
      }
      });
      }


      基本上就这些,当然请求的action里面需要设置pagination的setter和getter方法
      这个分页方法特点是简单,只需在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值获取不到正确的值,这是什么原因啊?
      问题补充:
        <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 阅读(199) | 评论 (0)编辑 收藏

      2009年9月5日 #

      在地址栏输入javascript:document.body.contentEditable='true'; document.designMode='on'; void 0就可以编辑网页了,哈哈
      posted @ 2009-09-05 21:01 jimphei 阅读(119) | 评论 (0)编辑 收藏

      仅列出标题  下一页