struts2

[b]Struts2[/b]

Struts2是在WebWork2基础发展而来的。和struts1一样, Struts2也属于MVC框架。不过有一点大家需要注意的是:尽管Struts2和struts1在名字上的差别不是很大,但Struts2和struts1在代码编写风格上几乎是不一样的。那么既然有了struts1,为何还要推出struts2。主要是因为struts2有以下优点:
1 > 在软件设计上Struts2没有像struts1那样跟Servlet API和struts API有着紧密的耦合,Struts2的应用可以不依赖于Servlet API和struts API。 Struts2的这种设计属于无侵入式设计,而Struts1却属于侵入式设计。
public class OrderListAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
}
}

2> Struts2提供了拦截器,利用拦截器可以进行AOP编程,实现如权限拦截等功能。
3> Strut2提供了类型转换器,我们可以把特殊的请求参数转换成需要的类型。在Struts1中,如果我们要实现同样的功能,就必须向Struts1的底层实现BeanUtil注册类型转换器才行。
4> Struts2提供支持多种表现层技术,如:JSP、freeMarker、Velocity等
5> Struts2的输入校验可以对指定方法进行校验,解决了Struts1长久之痛。
6> 提供了全局范围、包范围和Action范围的国际化资源文件管理实现

[b]搭建Struts2开发环境[/b]
搭建Struts2环境时,我们一般需要做以下几个步骤的工作:
1》找到开发Struts2应用需要使用到的jar文件.
2》编写Struts2的配置文件
3》在web.xml中加入Struts2 MVC框架启动配置

[b]第一个Struts2应用--HelloWorld[/b]
在默认的配置文件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>
<package name="itcast" namespace="/test" extends="struts-default">
<action name="helloworld" class="cn.itcast.action.HelloWorldAction" method="execute" >
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>
</struts>


[b]Struts.xml配置中的包介绍[/b]
<package name="itcast" namespace="/test" extends="struts-default">
<action name="helloworld" class="cn.itcast.action.HelloWorldAction" method="execute" >
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>

在struts2框架中使用包来管理Action,包的作用和java中的类包是非常类似的,它主要用于管理一组业务功能相关的action。在实际应用中,我们应该把一组业务功能相关的Action放在同一个包下。

配置包时必须指定name属性,该name属性值可以任意取名,但必须唯一,他不对应java的类包,如果其他包要继承该包,必须通过该属性进行引用。包的namespace属性用于定义该包的命名空间,命名空间作为访问该包下Action的路径的一部分,如访问上面例子的Action,访问路径为:/test/helloworld.action。 namespace属性可以不配置,对本例而言,如果不指定该属性,默认的命名空间为“”(空字符串)。

通常每个包都应该继承struts-default包, 因为Struts2很多核心的功能都是拦截器来实现。如:从请求中把请求参数封装到action、文件上传和数据验证等等都是通过拦截器实现的。 struts-default定义了这些拦截器和Result类型。可以这么说:当包继承了struts-default才能使用struts2提供的核心功能。 struts-default包是在struts2-core-2.x.x.jar文件中的struts-default.xml中定义。 struts-default.xml也是Struts2默认配置文件。 Struts2每次都会自动加载 struts-default.xml文件。

包还可以通过abstract=“true”定义为抽象包,抽象包中不能包含action。

[b]第一个Struts2应用--HellWorld[/b]
例子中使用到的cn.itcast.action.HelloWorldAction类如下:
package cn.itcast.action;
public class HelloWorldAction{
private String message;

public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}

public String execute() {
this.message = "我的第一个struts2应用";
return "success";
}
}


例子中使用到的/WEB-INF/page/hello.jsp如下:
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>第一个struts2应用</title>
</head>
<body>
${message } <br>
</body>
</html>


可以使用EL表达式访问Action中的属性。

[b]访问HelloWorld应用[/b]
在struts1中,通过<action path=“/test/helloworld”>节点的path属性指定访问该action的URL路径。在struts2中,情况就不是这样了,访问struts2中action的URL路径由两部份组成:包的命名空间+action的名称,例如访问本例子HelloWorldAction的URL路径为:/test/helloworld (注意:完整路径为:http://localhost:端口/内容路径/test/helloworld)。另外我们也可以加上.action后缀访问此Action。

 <package name="itcast" namespace="/test" extends="struts-default">
<action name="helloworld" class="cn.itcast.action.HelloWorldAction" method="execute" >
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>


[b]Action配置中的各项默认值[/b]
<package name="itcast" namespace="/test" extends="struts-default">
<action name="helloworld" class="cn.itcast.action.HelloWorldAction" method="execute" >
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>

1>如果没有为action指定class,默认是ActionSupport。
2>如果没有为action指定method,默认执行action中的execute() 方法。
3>如果没有指定result的name属性,默认值为success。

[b]Action中result的各种转发类型[/b]
<action name="helloworld" class="cn.itcast.action.HelloWorldAction">
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>

result配置类似于struts1中的forward,但struts2中提供了多种结果类型,常用的类型有: dispatcher(默认值)、 redirect 、 redirectAction 、 plainText。

在result中还可以使用${属性名}表达式访问action中的属性,表达式里的属性名对应action中的属性。如下:
<result type="redirect">/view.jsp?id=${id}</result>


下面是redirectAction 结果类型的例子,如果重定向的action中同一个包下:
<result type="redirectAction">helloworld</result>
如果重定向的action在别的命名空间下:
<result type="redirectAction">
<param name="actionName">helloworld</param>
<param name="namespace">/test</param>
</result>

plaintext:显示原始文件内容,例如:当我们需要原样显示jsp文件源代码 的时候,我们可以使用此类型。
<result name="source" type="plainText ">
<param name="location">/xxx.jsp</param>
<param name="charSet">UTF-8</param><!-- 指定读取文件的编码 -->
</result>


多个Action共享一个视图--全局result配置

当多个action中都使用到了相同视图,这时我们应该把result定义为全局视图。struts1中提供了全局forward,struts2中也提供了相似功能:
<package ....>
<global-results>
<result name="message">/message.jsp</result>
</global-results>
</package>


[b]为Action的属性注入值[/b]
Struts2为Action中的属性提供了依赖注入功能,在struts2的配置文件中,我们可以很方便地为Action中的属性注入值。注意:属性必须提供setter方法。
public class HelloWorldAction{
private String savePath;

public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
......
}

<package name="itcast" namespace="/test" extends="struts-default">
<action name="helloworld" class="cn.itcast.action.HelloWorldAction" >
<param name="savePath">/images</param>
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>

上面通过<param>节点为action的savePath属性注入“/images”

指定需要Struts 2处理的请求后缀

前面我们都是默认使用.action后缀访问Action。其实默认后缀是可以通过常量”struts.action.extension“进行修改的,例如:我们可以配置Struts 2只处理以.do为后缀的请求路径:

<?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.action.extension" value="do"/>
</struts>


如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。如:
<constant name="struts.action.extension" value="do,go"/>

[b]Struts2的处理流程[/b]

StrutsPrepareAndExecuteFilter是Struts 2框架的核心控制器,它负责拦截由<url-pattern>/*</url-pattern>指定的所有用户请求,当用户请求到达时,该Filter会过滤用户的请求。默认情况下,如果用户请求的路径不带后缀或者后缀以.action结尾,这时请求将被转入Struts 2框架处理,否则Struts 2框架将略过该请求的处理。当请求转入Struts 2框架处理时会先经过一系列的拦截器,然后再到Action。与Struts1不同,Struts2对用户的每一次请求都会创建一个Action,所以Struts2中的Action是线程安全的。

[b]接收请求参数[/b]
采用基本类型接收请求参数(get/post)
在Action类中定义与请求参数同名的属性,struts2便能自动接收请求参数并赋予给同名属性。
请求路径: http://localhost:8080/test/view.action?id=78
public class ProductAction {
private Integer id;
public void setId(Integer id) {//struts2通过反射技术调用与请求参数同名的属性的setter方法来获取请求参数值
this.id = id;
}
public Integer getId() {return id;}
}
采用复合类型接收请求参数
请求路径: http://localhost:8080/test/view.action?product.id=78
public class ProductAction {
private Product product;
public void setProduct(Product product) { this.product = product; }
public Product getProduct() {return product;}
}
Struts2首先通过反射技术调用Product的默认构造器创建product对象,然后再通过反射技术调用product中与请求参数同名的属性的setter方法来获取请求参数值。

[b]访问或添加request/session/application属性[/b]
public String scope() throws Exception{
ActionContext ctx = ActionContext.getContext();
ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app
ctx.getSession().put("ses", "session范围");//往session里放入ses
ctx.put("req", "request范围");//往request里放入req
return "scope";
}


JSP:
 <body>
${applicationScope.app} <br>
${sessionScope.ses}<br>
${requestScope.req}<br>
</body>


[b]获取HttpServletRequest / HttpSession / ServletContext / HttpServletResponse对象[/b]
方法一,通过ServletActionContext.类直接获取:
public String rsa() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContext = ServletActionContext.getServletContext();
request.getSession()
HttpServletResponse response = ServletActionContext.getResponse();
return "scope";
}

方法二,实现指定接口,由struts框架运行时注入:
public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse response;
public void setServletRequest(HttpServletRequest req) {
this.request=req;
}
public void setServletResponse(HttpServletResponse res) {
this.response=res;
}
public void setServletContext(ServletContext ser) {
this.servletContext=ser;
}
}


[b]文件上传[/b]
第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。
第二步:把form表的enctype设置为:“multipart/form-data“,如下:
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
<input type="file" name="uploadImage">
</form>

第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
public class HelloWorldAction{
private File uploadImage;//得到上传的文件
private String uploadImageContentType;//得到文件的类型
private String uploadImageFileName;//得到文件的名称
//这里略省了属性的getter/setter方法
public String upload() throws Exception{
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(realpath);
if(!file.exists()) file.mkdirs();
FileUtils.copyFile(uploadImage, new File(file, uploadImageFileName));
return "success";
}
}


[b]多文件上传[/b]
第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。
第二步:把form表的enctype设置为:“multipart/form-data“,如下:
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
<input type="file" name="uploadImages">
<input type="file" name="uploadImages">
</form>

第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
public class HelloWorldAction{
private File[] uploadImages;//得到上传的文件
private String[] uploadImagesContentType;//得到文件的类型
private String[] uploadImagesFileName;//得到文件的名称
//这里略省了属性的getter/setter方法
public String upload() throws Exception{
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(realpath);
if(!file.exists()) file.mkdirs();
for(int i=0 ;i<uploadImages.length; i++){ File uploadImage = uploadImages[i];
FileUtils.copyFile(uploadImage, new File(file, uploadImagesFileName[i]));
}
return "success";
}}


[b]OGNL表达式语言[/b]
Struts 2中的OGNL Context实现者为ActionContext,它结构示意图如下:
当Struts2接受一个请求时,会迅速创建ActionContext,ValueStack,action 。然后把action存放进ValueStack,所以action的实例变量可以被OGNL访问。

访问上下文(Context)中的对象需要使用#符号标注命名空间,如#application、#session

另外OGNL会设定一个根对象(root对象),在Struts2中根对象就是ValueStack(值栈) 。如果要访问根对象(即ValueStack)中对象的属性,则可以省略#命名空间,直接访问该对象的属性即可。

在struts2中,根对象ValueStack的实现类为OgnlValueStack,该对象不是我们想像的只存放单个值,而是存放一组对象。在OgnlValueStack类里有一个List类型的root变量,就是使用他存放一组对象
|--request
|--application
context ------|--OgnlValueStack root变量[action, OgnlUtil, ... ]
|--session
|--attr
|--parameters

在root变量中处于第一位的对象叫栈顶对象。通常我们在OGNL表达式里直接写上属性的名称即可访问root变量里对象的属性,搜索顺序是从栈顶对象开始寻找,如果栈顶对象不存在该属性,就会从第二个对象寻找,如果没有找到就从第三个对象寻找,依次往下访问,直到找到为止。
大家注意: Struts2中,OGNL表达式需要配合Struts标签才可以使用。如:<s:property value="name"/>

由于ValueStack(值栈)是Struts 2中OGNL的根对象,如果用户需要访问值栈中的对象,在JSP页面可以直接通过下面的EL表达式访问ValueStack(值栈)中对象的属性:
${foo} //获得值栈中某个对象的foo属性

如果访问其他Context中的对象,由于他们不是根对象,所以在访问时,需要添加#前缀。
application对象:用于访问ServletContext,例如#application.userName或者#application['userName'],相当于调用ServletContext的getAttribute("username")。

session对象:用来访问HttpSession,例如#session.userName或者#session['userName'],相当于调用session.getAttribute("userName")。

request对象:用来访问HttpServletRequest属性(attribute)的Map,例如#request.userName或者#request['userName'],相当于调用request.getAttribute("userName")。

parameters对象:用于访问HTTP的请求参数,例如#parameters.userName或者#parameters['userName'],相当于调用request.getParameter("username")。

attr对象:用于按page->request->session->application顺序访问其属性。


[b]采用OGNL表达式创建List/Map集合对象[/b]
如果需要一个集合元素的时候(例如List对象或者Map对象),可以使用OGNL中同集合相关的表达式。
使用如下代码直接生成一个List对象:
<s:set name="list" value="{'zhangming','xiaoi','liming'}" />
<s:iterator value="#list" id="n">
<s:property value="n"/><br>
</s:iterator>

生成一个Map对象:
<s:set name="foobar" value="#{'foo1':'bar1', 'foo2':'bar2'}" />
<s:iterator value="#foobar" >
<s:property value="key"/>=<s:property value="value"/><br>
</s:iterator>

Set标签用于将某个值放入指定范围。
scope:指定变量被放置的范围,该属性可以接受application、session、request、 page或action。如果没有设置该属性,则默认放置在OGNL Context中。
value:赋给变量的值.如果没有设置该属性,则将ValueStack栈顶的值赋给变量。

[b]采用OGNL表达式判断对象是否存在于集合中[/b]
对于集合类型,OGNL表达式可以使用in和not in两个元素符号。其中,in表达式用来判断某个元素是否在指定的集合对象中;not in判断某个元素是否不在指定的集合对象中,如下所示。
in表达式:
<s:if test="'foo' in {'foo','bar'}">

</s:if>
<s:else>
不在
</s:else>

not in表达式:
<s:if test="'foo' not in {'foo','bar'}">
不在
</s:if>
<s:else>

</s:else>


[b]property标签[/b]
property标签用于输出指定值:
<s:set name="name" value="'kk'" />
<s:property value="#name"/>
default:可选属性,如果需要输出的属性值为null,则显示该属性指定的值
escape:可选属性,指定是否格式化HTML代码。
value:可选属性,指定需要输出的属性值,如果没有指定该属性,则默认输出ValueStack栈顶的值。
id:可选属性,指定该元素的标识

[b]iterator标签[/b]
iterator标签用于对集合进行迭代,这里的集合包含List、Set和数组。
<s:set name="list" value="{'zhangming','xiaoi','liming'}" />
<s:iterator value="#list" status="st">
<font color=<s:if test="#st.odd">red</s:if><s:else>blue</s:else>>
<s:property /></font><br>
</s:iterator>
value:可选属性,指定被迭代的集合,如果没有设置该属性,则使用ValueStack栈顶的集合。
id:可选属性,指定集合里元素的id。
status:可选属性,该属性指定迭代时的IteratorStatus实例。该实例包含如下几个方法:
int getCount(),返回当前迭代了几个元素。
int getIndex(),返回当前迭代元素的索引。
boolean isEven(),返回当前被迭代元素的索引是否是偶数
boolean isOdd(),返回当前被迭代元素的索引是否是奇数
boolean isFirst(),返回当前被迭代元素是否是第一个元素。
boolean isLast(),返回当前被迭代元素是否是最后一个元素。

[b]if/elseif/else标签[/b]
<s:set name="age" value="21" />
<s:if test="#age==23">
23
</s:if>
<s:elseif test="#age==21">
21
</s:elseif>
<s:else>
都不等
</s:else>


[b]url标签[/b]
<s:url action="helloworld_add" namespace="/test"><s:param name="personid" value="23"/></s:url>

生成类似如下路径:
/struts/test/helloworld_add.action?personid=23
红色部分为内容路径。

当标签的属性值作为字符串类型处理时, “%”符号的用途是计算OGNL表达式的值。
 <s:set name="myurl" value="'http://www.foshanshop.net'"/>
<s:url value="#myurl" /><br>
<s:url value="%{#myurl}" />

输出结果:
#myurl
http://www.foshanshop.net


[b]表单标签_checkboxlist复选框[/b]
如果集合为list
<s:checkboxlist name="list" list="{'Java','.Net','RoR','PHP'}" value="{'Java','.Net'}"/>

生成如下html代码:
<input type="checkbox" name="list" value="Java" checked="checked"/><label>Java</label>
<input type="checkbox" name="list" value=".Net" checked="checked"/><label>.Net</label>
<input type="checkbox" name="list" value="RoR"/><label>RoR</label>
<input type="checkbox" name="list" value="PHP"/><label>PHP</label>


如果集合为MAP
<s:checkboxlist name="map" list="#{1:'瑜珈用品',2:'户外用品',3:'球类',4:'自行车'}" listKey="key" listValue="value" value="{1,2,3}"/>

生成如下html代码:
<input type="checkbox" name="map" value="1" checked="checked"/><label>瑜珈用品</label>
<input type="checkbox" name="map" value="2" checked="checked"/><label>户外用品</label>
<input type="checkbox" name="map" value="3" checked="checked"/><label>球类</label>
<input type="checkbox" name="map" value="4"/><label>自行车</label>


如果集合里存放的是javabean
 <%
Person person1 = new Person(1,"第一个");
Person person2 = new Person(2,"第二个");
List<Person> list = new ArrayList<Person>();
list.add(person1);
list.add(person2);
request.setAttribute("persons",list);
%>
<s:checkboxlist name="beans" list="#request.persons" listKey="personid" listValue="name"/>

Personid和name为Person的属性

生成如下html代码:
<input type="checkbox" name=“beans" value="1"/><label>第一个</label>
<input type="checkbox" name=“beans" value="2"/><label>第二个</label>


[b]表单标签_radio单选框[/b]
该标签的使用和checkboxlist复选框相同。
如果集合里存放的是javabean(personid和name为Person的属性)
< s:radio name="beans" list="#request.persons" listKey="personid" listValue="name"/>

生成如下html代码:
<input type="radio" name="beans" id="beans1" value="1"/><label>第一个</label>
<input type="radio" name="beans" id="beans2" value="2"/><label>第二个</label>

如果集合为MAP
<s:radio name="map" list="#{1:'瑜珈用品',2:'户外用品',3:'球类',4:'自行车'}" listKey="key" listValue="value“ value="1"/>

生成如下html代码:
<input type="radio" name="map" id="map1" value="1"/><label for="map1">瑜珈用品</label>
<input type="radio" name="map" id="map2" value="2"/><label for="map2">户外用品</label>
<input type="radio" name="map" id="map3" value="3"/><label for="map3">球类</label>
<input type="radio" name="map" id="map4" value="4"/><label for="map4">自行车</label>

如果集合为list
<s:radio name="list" list="{'Java','.Net'}" value="'Java'"/>

生成如下html代码:
<input type="radio" name="list" checked="checked" value="Java"/><label>Java</label>
<input type="radio" name="list" value=".Net"/><label>.Net</label>


[b]Struts2+Spring2.5+Hibernate3.3整合开发[/b]
[b]下面给出整合开发时Struts 2、 Hibernate、Spring需要的JAR。[/b]
struts2-core-2.x.x.jar :Struts 2框架的核心类库
Xwork-core-2.x.x.jar :XWork类库,Struts 2在其上构建
ognl-2.6.x.jar :对象图导航语言(Object Graph Navigation Language),struts2框架通过其读写对象的属性
freemarker-2.3.x.jar :Struts 2的UI标签的模板使用FreeMarker编写
commons-fileupload-1.2.x.jar 文件上传组件,2.1.6版本后需要加入此文件
struts2-spring-plugin-2.x.x.jar :用于struts2集成Spring的插件
hibernate核心安装包下的(下载路径:http://www.hibernate.org/,点击“Hibernate Core”右边的“Downloads”):
hibernate3.jar
lib\bytecode\cglib\hibernate-cglib-repack-2.1_3.jar
lib\required\*.jar
hibernate 注解安装包下的(下载路径:www.hibernate.org,点击“Hibernate Annotations”右边的“Downloads”):
hibernate-annotations.jar
lib\ejb3-persistence.jar、hibernate-commons-annotations.jar
Hibernate针对JPA的实现包(下载路径:www.hibernate.org,点击“Hibernate Entitymanager”右边的“Downloads”):
hibernate-entitymanager.jar
lib\test\log4j.jar、slf4j-log4j12.jar
Spring安装包下的
dist\spring.jar
lib\c3p0\c3p0-0.9.1.2.jar lib\aspectj\aspectjweaver.jar、aspectjrt.jar lib\cglib\cglib-nodep-2.1_3.jar
lib\j2ee\common-annotations.jar lib\log4j\log4j-1.2.15.jar lib\jakarta-commons\commons-logging.jar
MYSQL数据库驱动jar

[b]Spring的配置模版:[/b]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
</beans>


第一步在Spring中配置数据源:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="org.gjt.mm.mysql.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="1"/>
<!--连接池中保留的最小连接数。-->
<property name="minPoolSize" value="1"/>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="300"/>
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="60"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="5"/>
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60"/>
</bean>


第二步集成进hibernate :
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>cn/itcast/bean/buyer.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=false
</value>
</property>
</bean>


第三步使用Spring容器管理事务服务:
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

<!--使用基于注解方式配置事务 -->
<tx:annotation-driven transaction-manager="txManager"/>

[b]配置hibernate实体映射文件buyer.hbm.xml:[/b]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.bean">
<class name=“Buyer" table=“buyer">
<id name="username" length="20"/>
<property name="password" length="20" not-null="true"/>
<property name="gender" not-null="true" length="5">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">cn.itcast.bean.Gender</param>
<!-- 12为java.sql.Types.VARCHAR常量值,即保存枚举的字面值到数据库。如果不指定type参数,保存枚举的索引值(从0开始)到数据库-->
<param name="type">12</param>
</type>
</property>
</class>
</hibernate-mapping>


[b]在web容器中使用Listener实例化spring容器和配置struts2[/b]
<!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>

<!-- 对Spring容器进行实例化 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
配置struts2
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


struts2的配置文件模版struts.xml如下。常量struts.objectFactory=spring明确指出将由Spring负责创建Action实例。
<?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.ui.theme" value="simple" />
<constant name="struts.objectFactory" value="spring" />
<package name="person" namespace="/person" extends="struts-default">
<global-results>
<result name="message">/WEB-INF/page/message.jsp</result>
</global-results>
<action name="action_*" class="personList" method="{1}">
<result name="list">/WEB-INF/page/persons.jsp</result> </action>
</package>
</struts>

为了能从spring容器中寻找到Action bean,要求action配置的class属性值和spring中bean的名称相同。

使用spring解决struts2乱码问题。
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


使用spring解决hibernate因session关闭导致的延迟加载例外问题。
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<!-- 指定org.springframework.orm.hibernate3.LocalSessionFactoryBean在spring配置文件中的名称,默认值为sessionFactory.如果LocalSessionFactoryBean在spring中的名称不是sessionFactory,该参数一定要指定,否则会出现找不到sessionFactory的例外 -->
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


struts2的标签
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>

<s:form action="action_edit" method="post" namespace="/person">
<s:hidden name="person.id"/>
姓名:<s:textfield name="person.name"/><br>
<input type="submit" value="发送"/>
</s:form>

<s:iterator value="persons" >
<s:property value="id"/>, <s:property value="name"/>
<a href='<s:url action="action_editUI" namespace="/person"><s:param name="person.id" value="id"/></s:url>'>修改</a>
</s:iterator>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值