daweihe 2014-05-04
原文转自:http://blog.csdn.net/riyunzhu/article/details/7887901
这两天都是一直在鼓捣Struts2.3如何整合Spring3.2以及dao层到底选用什么以及如何整合。下面就把自己这两天的一些小成果分享出来也以便自己以后在实际项目中快速搭建。
首先是Struts2.3整合Spring3.2
1、新建一个web工程(这个就不说了)
2、添加Struts2.3
把Struts开发所需的jar复制到工程的lib文件中。开发struts必须包如下:
3、创建action类
声明:整个示例只有一个简单的用户登录。
本例中的action类名为LoginAction,该类中的代码如下:
[java]viewplaincopy
packagecom.riyun.action;
importcom.opensymphony.xwork2.ActionSupport;
publicclassLoginActionextendsActionSupport{
privatestaticfinallongserialVersionUID=1L;
privateStringuserName;
privateStringpassWord;
publicStringgetUserName(){
returnuserName;
}
publicStringgetPassWord(){
returnpassWord;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicvoidsetPassWord(StringpassWord){
this.passWord=passWord;
}
publicStringexecute()throwsException{
if(userName.equals("riyun")&&passWord.equals("123")){
returnSUCCESS;
}else{
returnERROR;
}
[java]viewplaincopy
}
至于该类为什么继承ActionSupport,相信网上讲述Struts1.X与Struts2.X的文章已经很多了,这里就不罗嗦了。
4、修改项目中的index.jsp代码,修改后的index.jsp代码如下:
[html]viewplaincopy
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>MyJSP'index.jsp'startingpage</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="Thisismypage">
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
</head>
<body>
<s:formaction="login">
<s:textfieldname="userName"label="用户名"key="user"></s:textfield>
<s:passwordname="passWord"label="密码"key="password"></s:password>
<s:submitkey="login"value="提交"></s:submit>
</s:form>
</body>
</html>
[html]viewplaincopy
新建两个success.jsp、error.jsp页面。后面action处理结果跳转有用,如果登陆成功则跳转到success.jsp,反之则跳转到error.jsp!
5、新建一个以struts.xml为名的xml文件
文件中的代码如下:
[html]viewplaincopy
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstrutsPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!--struts的action配置文件-->
<!--所有的action都应该放在对应的package下-->
<packagename="riyun"extends="struts-default">
<actionname="login"class="com.riyun.action.LoginAction">
<!--定义逻辑视图和物理资源之间的映射-->
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
6、在web.xml中添加struts拦截器。
Web.xml的代码如下:
[html]viewplaincopy
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!--定义struts2的核心filter-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<!--让struts定义的核心filter拦截所有请求-->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--项目欢迎界面-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
至此Struts2.3整合成功,接下来继续整合Spring3.2。
7、导入所需spring的jar包如下;
对于Spring的jar包没有研究过,所以我这里把spring所有的jar都复制到了lib目录中去了。另外还需要导入struts2-spring-plugin-2.3.4.1.jar包。
8、在web-inf目录中新建一个applicationContext.xml为名的xml文件(该文件与web.xml是在同一级目录)
该applicationContext.xml文件中的代码如下:
[html]viewplaincopy
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEbeansPUBLIC"-//SPRING//DTDBEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<beanid="userDao"class="com.riyun.daoImpl.UserDaoImpl"></bean>
<beanid="login"class="com.riyun.action.LoginAction">
<propertyname="userDao"ref="userDao"/>
</bean>
</beans>
9、修改struts.xml文件,修改后的struts.xml文件中的代码如下
[html]viewplaincopy
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstrutsPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!--struts的action配置文件-->
<!--将action托管给spring-->
<constantname="struts.objectFactory"value="spring"></constant>
<!--所有的action都应该放在对应的package下-->
<packagename="riyun"extends="struts-default">
<actionname="login"class="com.riyun.action.LoginAction">
<!--定义逻辑视图和物理资源之间的映射-->
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
10、修改web.xml文件,修改后的web.xml文件中的代码如下:
[html]viewplaincopy
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!--初始化-->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--如果有多个文件,在文件之间用英文逗号隔开-->
<!--<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/applicationContext-db.xml
</param-value>-->
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!--监听器-->
<!--配置spring监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--定义struts2的核心filter-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<!--让struts定义的核心filter拦截所有请求-->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--项目欢迎界面-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
ok,到此为此Struts2.3整合Spring3.2就可以了。那实际项目中不可能不跟数据库打交道。常见的dao层用的是hibernate。但其实还有一些跟hibernate功能相似而且相对于hibernate来说配置更简单的dao层应用可以供我们选择。这里我就选用了JDBC。利用JDBC作为dao层的应用,每个dao层都要继承JDBCSupport类。
11、添加dao层,添加UserDao接口、添加UserDaoImpl实现接口类
UserDao接口的代码如下:
[java]viewplaincopy
packagecom.riyun.dao;
publicinterfaceUserDao{
/*用户登录
*pram:userName,passWord
*return:boolean
*/
publicbooleanlogin(StringuserName,StringpassWord);
}
UserDaoImpl实现接口类的代码如下:
[java]viewplaincopy
packagecom.riyun.daoImpl;
importjava.util.Map;
importorg.springframework.dao.EmptyResultDataAccessException;
importorg.springframework.jdbc.core.support.JdbcDaoSupport;
importcom.riyun.dao.UserDao;
publicclassUserDaoImplextendsJdbcDaoSupportimplementsUserDao{
//用户登录
publicbooleanlogin(StringuserName,StringpassWord){
//TODOAuto-generatedmethodstub
Stringsql="selectjob,enamefromempwhereename=?";
Mapmap=this.getJdbcTemplate().queryForMap(sql,newObject[]{userName});
try{
Stringpass=(String)map.get("job");
if(passWord.equals(pass)){
returntrue;
}else{
returnfalse;
}
}catch(EmptyResultDataAccessExceptione){
e.printStackTrace();
returnfalse;
}
}
}
12、修改LoginAction类的代码,修改后的代码如下:
[java]viewplaincopy
packagecom.riyun.action;
importorg.apache.log4j.Logger;
importcom.opensymphony.xwork2.ActionSupport;
importcom.riyun.dao.UserDao;
publicclassLoginActionextendsActionSupport{
privatestaticfinallongserialVersionUID=1L;
privateUserDaouserDao;
privateStringuserName;
privateStringpassWord;
publicUserDaogetUserDao(){
returnuserDao;
}
publicvoidsetUserDao(UserDaouserDao){
this.userDao=userDao;
}
publicStringgetUserName(){
returnuserName;
}
publicStringgetPassWord(){
returnpassWord;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicvoidsetPassWord(StringpassWord){
this.passWord=passWord;
}
publicStringexecute()throwsException{
if(userDao.login(userName,passWord)){
returnSUCCESS;
}else{
returnERROR;
}
}
}
13、修改applicationContext.xml文件,修改后的文件代码如下:
[html]viewplaincopy
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEbeansPUBLIC"-//SPRING//DTDBEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close"dependency-check="none">
<propertyname="driverClass">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<propertyname="jdbcUrl">
<value>jdbc:oracle:thin:@localhost:1521:orcl</value>
</property>
<propertyname="user">
<value>scott</value>
</property>
<propertyname="password">
<value>123</value>
</property>
<!--<propertyname="acquireIncrement">
<value>${c3p0.acquireIncrement}</value>
</property>
<propertyname="initialPoolSize">
<value>${c3p0.initialPoolSize}</value>
</property>
<propertyname="minPoolSize">
<value>${c3p0.minPoolSize}</value>
</property>
<propertyname="maxPoolSize">
<value>${c3p0.maxPoolSize}</value>
</property>
<propertyname="maxIdleTime">
<value>${c3p0.maxIdleTime}</value>
</property>
<propertyname="idleConnectionTestPeriod">
<value>${c3p0.idleConnectionTestPeriod}</value>
</property>
<propertyname="maxStatements">
<value>${c3p0.maxStatements}</value>
</property>
<propertyname="numHelperThreads">
<value>${c3p0.numHelperThreads}</value>
</property>-->
</bean>
<beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource">
<reflocal="dataSource"/>
</property>
</bean>
<beanid="txManager"abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<propertyname="transactionManager"ref="transactionManager"/>
<propertyname="transactionAttributes">
<props>
<propkey="add*">
PROPAGATION_REQUIRED,-DataAccessException
</prop>
<propkey="save*">
PROPAGATION_REQUIRED,-DataAccessException
</prop>
<propkey="edit*">
PROPAGATION_REQUIRED,-DataAccessException
</prop>
<propkey="update*">
PROPAGATION_REQUIRED,-DataAccessException
</prop>
<propkey="del*">
PROPAGATION_REQUIRED,-DataAccessException
</prop>
<propkey="handle*">
PROPAGATION_REQUIRED,-DataAccessException
</prop>
<propkey="notify*">
PROPAGATION_REQUIRED,-DataAccessException
</prop>
<propkey="get*">PROPAGATION_REQUIRED,readOnly</prop>
<propkey="query*">PROPAGATION_REQUIRED,readOnly,-DataAccessException</prop>
<propkey="find*">PROPAGATION_REQUIRED,readOnly</prop>
<propkey="is*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-argref="dataSource"/>
</bean>
<beanid="userDao"class="com.riyun.daoImpl.UserDaoImpl">
<propertyname="jdbcTemplate"ref="jdbcTemplate"></property>
</bean>
<beanid="login"class="com.riyun.action.LoginAction">
<propertyname="userDao"ref="userDao"/>
</bean>
</beans>
至此整个例子ok了。
在dao层连接数据库的时候还需要导入各个数据库所必须的jar包以及c3p0-0.9.1.2.jar这样的包。
总结:整合过程中碰到许许多多的问题,相信大家看我这篇文章也会碰到许许多多不一样的问题,但是有问题不可怕,我们要做的就是分析问题的原因。我在整合过程碰到最多的问题就是classnotfound类的问题,其实这类的问题就是没有导入相关jar包导致的错误或者jar冲突导致的。