Struts2、Spring和Hibernate实例3

 
七、       Web页面
 
在这一节中,主要使用到了Struts2的标签库。在这里, 会对所用到的主要标签做一个初步的介绍。更多的知识请读者访问Struts的官方网站做更多的学习。在编写 Web页面之前,先从总体上,对Struts 1.x与Struts 2.0的标志库(Tag Library)作比较。
 
Struts 1.x
Struts 2.0
分类
将标志库按功能分成HTML、Tiles、Logic和Bean等几部分
严格上来说,没有分类,所有标志都在URI为“/struts-tags”命名空间 下,不过,我们可以从功能上将其分为两大类:非UI标志和UI标志
表达式语言(expression languages)
不支持嵌入语言(EL)
OGNL、JSTL、Groovy和Velcity
 
1、 主页面:index.jsp,其代码如下:
 
 
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" % > <%@ taglib prefix="s" uri="/struts-tags" % > <html> <head> <meta http-equiv="Content- Type" content="text/html; charset=GBK"/> <title>图书管 理系统</title> </head> <body> <p><a href="<s:url action="list" />">进入图书管理系统</a></p> </body> </html>
WebRoot/index.jsp
要在JSP中使用Struts 2.0标志,先要指明标志的引入。 通过在JSP的代码的顶部加入以下代码可以做到这点。<%@taglib prefix="s" uri="/struts-tags" % >
1<s:url>标签:该标签用 于创建url,可以通过"param"标签提供request参数。当includeParams的值时'all'或者'get', param标签中定 义的参数将有优先权,也就是说其会覆盖其他同名参数的值。
 
2、 列表页面:list.jsp
 
  
  
<%@page pageEncoding="gb2312" contentType="text/html; charset=UTF-8" % > <%@ taglib prefix="s" uri="/struts-tags" % > <html> <head><title>图书管 理系统</title></head> <style type="text/css"> table { border : 1px solid black; border-collapse : collapse; } table thead tr th { border : 1px solid black; padding : 3px; background-color : #cccccc; background-color : expression(this.rowIndex % 2 == 0 ? "#FFFFFF" : "#EEEEEE"); } table tbody tr td { border : 1px solid black; padding : 3px; } .trs { background-color : expression(this.rowIndex % 2 == 0 ? "#FFFFFF" : "#EEEEEE"); } </style> <script language="JavaScript"> function doSearch(){ if(document.all.searchValue.value=="" ) { alert("请输入查询关键字!" ); }else { window.location.href="bookAdmin/list.action?queryName="+document.all.searchName.value+"&&queryValue="+ document.all.searchValue.value; } } </script> <body> <table align="center"> <tr align="center"> <td> <select name="searchName"> <option value="bookName">书名</option> <option value="bookAuthor">作者</option> <option value="bookPublish">出版社</option> <option value="bookDate">出版日期</option> <option value="bookIsbn">ISNB</option> <option value="bookPage">页数</option> </select> <input type="text" name="searchValue" value="" size="10"/> <input type="button" value="查询" onClick="doSearch();"> </td> </tr> <tr align="center"> <td> <a href="<s:url action="list" includeParams="none"/>">全部</a> <a href='<s:url action="edit" ></s:url>'> 增加</a> </td> </tr> <tr> <td> <table cellspacing="0" align="center"> <thead> <tr> <th>书名</th> <th>作者</th> <th>出版社</th> <th>出版日期</th> <th>ISNB</th> <th>页数</th> <th>价格</th> <th>内容提要</th> <th>删除</th> </tr> </thead> <tbody> <s:iterator value="availableItems"> <tr class="trs"> <td> <a href='<s:url action="edit" ><s:param name="bookId" value="bookId" /></s:url> '> <s:property value="bookName"/> </a> </td> <td><s:property value="bookAuthor"/></td> <td><s:property value="bookPublish"/></td> <td><s:text name="format.date"><s:param value="bookDate"/></s:text></td> <td><s:property value="bookIsbn" /></td> <td><s:property value="bookPage" /></td> <td><s:property value="bookPrice"/></td> <td><s:property value="bookContent"/></td> <td><a href='<s:url action="delete"><s:param name="bookId" value="bookId" /></s:url>'>删除</a></td> </tr> </s:iterator> <tr align="right"> <td colspan="9"> <s:property value="totalRows"/>&nbsp; <s:property value="currentPage"/>&nbsp; <s:property value="pager.getTotalPages()"/>&nbsp; <a href="<s:url value="list.action"> <s:param name="currentPage" value="currentPage"/> <s:param name="pagerMethod" value="'first'"/> </s:url>"> 首页</a> <a href="<s:url value="list.action"> <s:param name="currentPage" value="currentPage"/> <s:param name="pagerMethod" value="'previous'"/> </s:url>">上一页</a> <a href="<s:url value="list.action"> <s:param name="currentPage" value="currentPage"/> <s:param name="pagerMethod" value="'next'"/> </s:url>">下一页</a> <a href="<s:url value="list.action"> <s:param name="currentPage" value="currentPage"/> <s:param name="pagerMethod" value="'last'"/> </s:url>">尾页</a> </td> </tr> </tbody> </table> </td> </tr> </table> </body> </html>
/WebRoot/list.jsp
(1)、<s:property> :得到'value'的属性,如果 value没提供,默认为堆栈顶端的元素。其相关的参数及使用如下表所示:
名称
必需
默认
类型
描述
default
 
String
如果属性是null则显示的default值
escape
true
Booelean
是否escape HTML
value
栈顶
Object
要显示的值
id
 
Object/String
用来标识元素的id。在UI和表单中为HTML的id属性
 
(2)、<s:Iterator>:用于遍历集合 (java.util.Collection)或枚举值(java.util.Iterator)。其相关的参数及使用如下表所示:  
名称
必需
默认
类型
描述
status
 
String
如果设置此参数,一个IteratorStatus的实例将会压入 每个遍历的堆栈
value
 
Object/String
要遍历的可枚举的(iteratable)数据源,或者将放入 新列表(List)的对象
id
 
Object/String
用来标识元素的id。在UI和表单中为HTML的id属性
 
(3)、<s:param>:为其他标签提供参数,比如 include标签和bean标签. 参数的name属性是可选的,如果提供,会调用Component的方法addParameter (String, Object), 如果不提供,则外层嵌套标签必须实现UnnamedParametric接口(如TextTag)。 value的提供有两种方式,通过value属性或者标签中间的text,不同之处我们看一下例 子:
<param name="color">blue</param><! -- (A) -->
<param name="color" value="blue"/><!-- (B) -->
(A)参数值会以String的格式放入statck.
(B)该值会以java.lang.Object的格式放入 statck.
其相关的参数及使用如下表所示:
名称
必需
默认
类型
描述
name
 
String
参数名
value
 
String
value表达式
id
 
Object/String
用来标识元素的id。在UI和表单中为HTML的id属性
(4)、国际化是商业系统 中不可或缺的一部分,所以无论您学习的是什么Web框架,它都是必须掌握的技能。其实,Struts 1.x在此部分已经做得相当不错了。它极大地简化了我们程序员在做国 际化时所需的工作,例如,如果您要输出一条国际化的信息,只需在代码包中加入FILE-NAME_xx_XX.properties(其中 FILE-NAME为默认资源文件的文 件名),然后在struts-config.xml中指明其路径,再在页面用<bean:message>标志输出即可。
不过,所谓没有最好,只有更好Struts 2.0并没有在这部分止步,而是在原有的简单易用的基 础上,将其做得更灵活、更强大。
(5)、list.jsp文件中:
,为了正确的输出出版日期的格式,采用在资源文件中定义输出的格式,并在页面上调用。format.date就是在资源文件 com.sterning.books.web.actions.BooksAction.properties中定义。当然也可以别的文件 ,放在别的路径下,但此时需要在web.xml中注册才可以使用它。
正如读者所见,在 pojo(本例为Books.java)中将日期字段设置为 java.util.Date,在映射文件中 (books.hbm.xml)设置为 timestamp(包括日期和时间) 。为了便于管理,将日期格式保存在国际化资源文件中。如:globalMessagesglobalMessages_zh_CN文件。
其内容为:
format.date= {0,date,yyyy-MM-dd}
在页面显示日期时间时: <s:text name="format.date"><s:param value="bookDate"/></s:text> 。这 样就解决了日期(时间)的显示格式化问题。

3、 增加/修改页面:editBook.jsp 

 
 
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" % > <%@ taglib prefix="s" uri="/struts-tags" % > <html> <head> <title>编辑图书</title> <s:head/> </head> <body> <h2> <s:if test="null == book"> 增加图书 </s:if> <s:else> 编辑图书 </s:else> </h2> <s:form name="editForm" action="save" validate="true"> <s:textfield label="书名" name="book.bookName"/> <s:textfield label="作者" name="book.bookAuthor"/> <s:textfield label="出版社" name="book.bookPublish"/> <s:datetimepicker label="出版日期" name="book.bookDate"></s:datetimepicker> <s:textfield label="ISBN" name="book.bookIsbn"/> <s:textfield label="页数" name="book.bookPage"/> <s:textfield label="价格(元)" name="book.bookPrice"/> <s:textfield label="内容摘要" name="book.bookContent"/> <s:if test="null == book"> <s:hidden name="book.bookId" value="%{bookId}"/> </s:if> <s:else> <s:hidden name="book.bookId" /> </s:else> <s:hidden name="queryName" /> <s:hidden name="queryValue" /> <s:submit value="%{getText('保存')}" /> </s:form> <p><a href="<s:url action="list"/>">返回</a></p> </body> </html>
WebRoot/editBook.jsp
(1)、<s:if>、<s:elseif>和<s:else> :执行基本 的条件流转。 其相关的参数及使用如下表所示:
名称
必需
默认
类型
描述
备注
test
 
Boolean
决定标志里内容是否显示的表达式
else标志没有这个参数
id
 
Object/String
用来标识元素的id。在UI和表单中为HTML的id属性
 
 
(2)、<s:text>:支持国际化信息的标签。国际化信息必须放在一 个和当前action同名的resource bundle中,如果没有找到相应message,tag body将被当作默认message,如果没 有tag body,message的name会被作为默认message。 其相关的参数及使用如下表所示:
名称
必需
默认
类型
描述
name
 
String
资源属性的名字
id
 
Object/String
用来标识元素的id。在UI和表单中为HTML的id属性

 

八、 配 置Struts2
 
Struts的配置文件都会在web.xml中注册的。

a)         Struts的配置文件如下:

 
 
<? 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.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <constant name="struts.i18n.encoding" value="GBK" /> <!-- Add packages here --> </struts> Src/struts.xml b) struts_book.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> <package name="products" extends="struts-default"> <!-- default-interceptor-ref name="validation"/ --> <!-- Add actions here -- > <action name="list" class="bookAction" method="list"> <result>/list.jsp</result> </action> <action name="delete" class="bookAction" method="delete"> <result type="redirect">list.action?queryMap=${queryMap} </result> </action> <action name="*" class="com.sterning.commons.AbstractAction"> <result>/{1}.jsp</result> </action> <action name="edit" class="bookAction" method="load"> <result>/editBook.jsp</result> </action> <action name="save" class="bookAction" method="save"> <interceptor-ref name="params"/> <interceptor-ref name="validation"/> <result name="input">/editBook.jsp</result> <result type="redirect">list.action?queryMap=${queryMap}</result> </action> </package> </struts>


    文件中的<interceptor-ref name="params"/>,使 用 了struts2自己的拦截器,拦截器在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问 之 前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。

    Struts 2已经提供了丰富多样的,功能齐全的拦截器实现 。大家可以到struts2-all -2.0.6.jar或struts2-core-2.0.6.jar包的struts-default.xml查看关于默认的拦 截器与拦截器链的配置。
在struts-default.xml中已经配置了大量的拦截器。如果 您想要使用这些已有的拦截器,只需要在应 用程序struts.xml文件中通过“<include file="struts- default.xml" />”将struts-default.xml文 件包含进来,并继承其中的struts-default包
(package), 最后在定义Action时,使用 “<interceptor-ref name="xx" />”引用拦截器或拦截器栈(interceptor stack)。一旦您继承了 struts-default包(package),所有Action都会调用拦截器栈 ——defaultStack。 当然,在Action配置中 加入“<interceptor-ref name="xx" />”可以覆盖defaultStack。

    作为 “框架(framework)”,可扩展性是不可或缺的,因为世上没有放之四海而 皆准的东西。虽然, Struts 2为我们提供如此丰富的拦截器实现,但是这并不意味我们失去创建自定义拦截器的能力,恰恰相反, 在Struts 2自定义拦 截器是相当容易的一件事。所有的Struts 2的拦截器都直接或间接实现接口 com.opensymphony.xwork2.interceptor.Interceptor。 除此之外,大家可能更喜欢继承类 com.opensymphony.xwork2.interceptor.AbstractInterceptor。

 

九、 配置Spring

1、Spring的配置文件如下:

  
  
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- dataSource config --> <bean id ="dataSource" class ="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/game" /> <property name="username" value="root" /> <property name="password" value="root"/> </bean> <!-- SessionFactory --> <bean id="sessionFactory" class ="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="configLocation"> <value>classpath:com/sterning/bean/hibernate/hibernate.cfg.xml</value> </property> </bean> <!-- TransactionManager 不过这里暂时没注入--> <bean id="transactionManager" class ="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref local="sessionFactory"/> </property> </bean> <!-- DAO --> <bean id="booksDao" class="com.sterning.books.dao.hibernate.BooksMapDao"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <!-- Services --> <bean id="booksService" class="com.sterning.books.services.BooksService"> <property name="booksDao"> <ref bean="booksDao"/> </property> </bean> <bean id="pagerService" class="com.sterning.commons.PagerService"/> <!-- view --> <bean id="bookAction" class="com.sterning.books.web.actions.BooksAction" singleton="false"> <property name="booksService"> <ref bean="booksService"/> </property> <property name="pagerService"> <ref bean="pagerService"/> </property> </bean> </beans>
WebRoot/WEB-INF/srping-content/applicationContent.xml
2、Struts.properties.xml
本来此文件应该写在struts 配置一节,但主要是考虑这体现了集成spring的配置,所以放在spring的配置这里来讲。
struts.objectFactory = spring 
struts.locale=zh_CN
struts.i18n.encoding = GBK
struts.objectFactory:ObjectFactory 实现了 com.opensymphony.xwork2.ObjectFactory接口(spring)。struts.objectFactory=spring,主要是告知Struts 2运行时使用Spring来创建对象(如Action等)。当然,Spring的ContextLoaderListener监听器,会在web.xml文件中编写,负责Spring与Web容器交互。
struts.locale:The default locale for the Struts application。 默认的国际化地区信息。
struts.i18n.encoding:国际化信息内码。
 
十、    Web.xml配置

   
   
<?xml version="1.0" encoding="GB2312"?> <! DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>图书管理系统</display-name> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> <!-- ContextConfigLocation --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-context/applicationContext.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class>com.sterning.commons.SetCharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> <init-param> <param-name>config</param-name> <param-value>struts-default.xml,struts-plugin.xml,struts.xml,struts_books.xml</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Listener contextConfigLocation --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Listener log4jConfigLocation --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- The Welcome File List --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
在Struts 2中,配置有少许改变,最明显的是分发器(dispatcher)已由Servlet转为Servlet Filter, 其配置和Servlet一样简单。和Servlet配置一样,Filter配置中定义了Filter的名称(作为引用)和类名。Filter Mapping通过URI和名称匹配来调用相应的Filter。默认情况下,扩展名为“.action”,这是在default.properties文件(在Struts 2 JAR文件里)的“struts.action.extension”属性定义的。
 
1、主页面



2、图书列表页面



3、增加页面



4、修改页面



十二、        总结
 
从上面的struts2.0.6+spring2.0.6+hibernate3.1的示例 代码可以看出,从struts1过渡到Struts2的时候,发现非常方便,标签变得更加的简洁,从而使代码量简缩了 ,同时整个体系沿用了 webwork 的精华和struts1的精髓,Struts2的Action不再依耐于Servlet容器,从而可以进行单独的测试。另 外对于表达式语言方面,不仅支持原有的JSTL,还支持OGNL(全称是Object Graph Notation Language)。在 校验方面,没有再直接使用Common-validator,用的是xwork框架校验。其实说这些,主要把webwork2的特性 简单描述一下而已,话说回来,发现struts2跟 ajax 的某些框架结合得不好,比如流行的 dwr ,连最简单的页面theme都用不 了ajax,这个问题主要出在模版上面,具体位置在Struts2-core-2.0.6.jar包的template/ajax里面的form- close.ftl等几个文件的代码有bug,比如dojo.widget.html.Tooltip问题,是没有这个属性的,应为 dojo.widget.Tooltip,这个已经在官方的bug跟踪系统提出了,官方说会在2.1版本时解决(其实在 Struts2.0.8中已经有解决的痕迹了)。当然,还有 其他 一系列的bug,不过大体沿用了webwork2的东西,拿官方说: struts2 = webwork2 + struts
 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值