Struts2.3+Spring3.2的整合 案例

原文转自: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] view plaincopy
package com.riyun.action; 
 
import com.opensymphony.xwork2.ActionSupport; 
public class LoginAction extends ActionSupport{ 
     
    private static final long serialVersionUID = 1L; 
     
         
    private String userName; 
    private String passWord; 
     
    public String getUserName() { 
        return userName; 
    } 
    public String getPassWord() { 
        return passWord; 
    } 
    public void setUserName(String userName) { 
        this.userName = userName; 
    } 
    public void setPassWord(String passWord) { 
        this.passWord = passWord; 
    } 
     
     
    public String   execute() throws Exception{ 
        if(userName.equals("riyun")&&passWord.equals("123")){ 
               return SUCCESS; 
          }else{ 
               return ERROR; 
            } 
[java] view plaincopy


至于该类为什么继承ActionSupport,相信网上讲述Struts1.X与Struts2.X的文章已经很多了,这里就不罗嗦了。
4、修改项目中的index.jsp代码,修改后的index.jsp代码如下:

[html] view plaincopy
<%@ page language="java" import="java.util.*" 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"> 
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    --> 
  </head> 
   
  <body> 
    <s:form action="login"> 
        <s:textfield name="userName" label="用户名" key="user"></s:textfield> 
        <s:password  name="passWord" label="密码" key="password"></s:password> 
        <s:submit key="login" value="提交"></s:submit> 
    </s:form> 
  </body> 
</html> 

[html] view plaincopy
 
新建两个success.jsp、error.jsp页面。后面action处理结果跳转有用,如果登陆成功则跳转到success.jsp,反之则跳转到error.jsp!
5、 新建一个以struts.xml为名的xml文件
  文件中的代码如下:

[html] view plaincopy
<?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> 
     <!-- struts的action配置文件 --> 
      
     <!-- 所有的action都应该放在对应的package下 --> 
     <package name="riyun" extends="struts-default"> 
        <action name="login" class="com.riyun.action.LoginAction"> 
            <!-- 定义逻辑视图和物理资源之间的映射 --> 
            <result name="success">/success.jsp</result> 
            <result name="error">/error.jsp</result> 
        </action> 
     </package> 
  </struts> 

6、在web.xml中添加struts拦截器。
    Web.xml的代码如下:

[html] view plaincopy
<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="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] view plaincopy
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"  
"http://www.springframework.org/dtd/spring-beans.dtd"> 
<beans> 
    <bean id="userDao" class="com.riyun.daoImpl.UserDaoImpl">  </bean>   
    <bean id="login" class="com.riyun.action.LoginAction">   
        <property name="userDao" ref="userDao" />   
    </bean>   
</beans> 


9、修改struts.xml文件,修改后的struts.xml文件中的代码如下
[html] view plaincopy
<?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> 
     <!-- struts的action配置文件 --> 
     <!-- 将action托管给spring --> 
     <constant name="struts.objectFactory" value="spring"></constant>   
     <!-- 所有的action都应该放在对应的package下 --> 
     <package name="riyun" extends="struts-default"> 
        <action name="login" class="com.riyun.action.LoginAction"> 
            <!-- 定义逻辑视图和物理资源之间的映射 --> 
            <result name="success">/success.jsp</result> 
            <result name="error">/error.jsp</result> 
        </action> 
     </package> 
  </struts> 


10、修改web.xml文件,修改后的web.xml文件中的代码如下:

[html] view plaincopy
<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="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] view plaincopy
package com.riyun.dao; 
 
public interface UserDao { 
     
    /*用户登录
     * pram:userName,passWord
     * return:boolean
     */ 
    public boolean login(String userName,String passWord); 
 


UserDaoImpl实现接口类的代码如下:

[java] view plaincopy
package com.riyun.daoImpl; 
 
import java.util.Map; 
 
 
import org.springframework.dao.EmptyResultDataAccessException; 
import org.springframework.jdbc.core.support.JdbcDaoSupport; 
 
import com.riyun.dao.UserDao; 
 
public class UserDaoImpl extends JdbcDaoSupport implements UserDao{ 
 
    //用户登录 
    public boolean login(String userName, String passWord) { 
        // TODO Auto-generated method stub 
        String sql="select job,ename from emp where ename=?"; 
        Map map=this.getJdbcTemplate().queryForMap(sql, new Object[] {userName}); 
        try{ 
            String pass=(String) map.get("job"); 
            if(passWord.equals(pass)){           
                return true; 
            }else{ 
                return false; 
            } 
        }catch(EmptyResultDataAccessException e){ 
            e.printStackTrace(); 
            return false; 
        }        
    } 

12、修改LoginAction类的代码,修改后的代码如下:


[java] view plaincopy
package com.riyun.action; 
 
import org.apache.log4j.Logger; 
 
import com.opensymphony.xwork2.ActionSupport; 
import com.riyun.dao.UserDao; 
 
public class LoginAction extends ActionSupport{ 
     
    private static final long serialVersionUID = 1L; 
     
         
    private UserDao userDao; 
    private String userName; 
    private String passWord; 
     
    public UserDao getUserDao() { 
        return userDao; 
    } 
    public void setUserDao(UserDao userDao) { 
        this.userDao = userDao; 
    } 
 
    public String getUserName() { 
        return userName; 
    } 
    public String getPassWord() { 
        return passWord; 
    } 
    public void setUserName(String userName) { 
        this.userName = userName; 
    } 
    public void setPassWord(String passWord) { 
        this.passWord = passWord; 
    } 
     
     
    public String   execute() throws Exception{ 
        if(userDao.login(userName, passWord)){ 
            return SUCCESS; 
        }else{ 
            return ERROR; 
        } 
    } 
     

13、修改applicationContext.xml文件,修改后的文件代码如下:
[html] view plaincopy
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"  
"http://www.springframework.org/dtd/spring-beans.dtd"> 
<beans> 
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  destroy-method="close" dependency-check="none"> 
            <property name="driverClass"> 
                <value>oracle.jdbc.driver.OracleDriver</value> 
            </property> 
            <property name="jdbcUrl"> 
                <value>jdbc:oracle:thin:@localhost:1521:orcl</value> 
            </property> 
            <property name="user"> 
                <value>scott</value> 
            </property> 
            <property name="password"> 
                <value>123</value> 
            </property> 
            <!-- <property name="acquireIncrement"> 
                <value>${c3p0.acquireIncrement}</value> 
            </property> 
            <property name="initialPoolSize"> 
                <value>${c3p0.initialPoolSize}</value> 
            </property> 
            <property name="minPoolSize"> 
                <value>${c3p0.minPoolSize}</value> 
            </property> 
            <property name="maxPoolSize"> 
                <value>${c3p0.maxPoolSize}</value> 
            </property> 
            <property name="maxIdleTime"> 
                <value>${c3p0.maxIdleTime}</value> 
            </property> 
            <property name="idleConnectionTestPeriod"> 
                <value>${c3p0.idleConnectionTestPeriod}</value> 
            </property> 
            <property name="maxStatements"> 
                <value>${c3p0.maxStatements}</value> 
            </property> 
            <property name="numHelperThreads"> 
                <value>${c3p0.numHelperThreads}</value> 
            </property>--> 
    </bean> 
    <bean id="transactionManager"  class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
        <property name="dataSource"> 
            <ref local="dataSource" /> 
        </property> 
    </bean> 
    <bean id="txManager" abstract="true" 
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> 
        <property name="transactionManager" ref="transactionManager" /> 
        <property name="transactionAttributes"> 
            <props> 
                <prop key="add*"> 
                    PROPAGATION_REQUIRED,-DataAccessException 
                </prop> 
                <prop key="save*"> 
                    PROPAGATION_REQUIRED,-DataAccessException 
                </prop> 
                <prop key="edit*"> 
                    PROPAGATION_REQUIRED,-DataAccessException 
                </prop> 
                <prop key="update*"> 
                    PROPAGATION_REQUIRED,-DataAccessException 
                </prop> 
                <prop key="del*"> 
                    PROPAGATION_REQUIRED,-DataAccessException 
                </prop> 
                <prop key="handle*"> 
                    PROPAGATION_REQUIRED,-DataAccessException 
                </prop> 
                <prop key="notify*"> 
                    PROPAGATION_REQUIRED,-DataAccessException 
                </prop> 
                <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> 
                <prop key="query*">PROPAGATION_REQUIRED,readOnly,-DataAccessException</prop> 
                <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> 
                <prop key="is*">PROPAGATION_REQUIRED,readOnly</prop> 
            </props> 
        </property> 
    </bean> 
     
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 
        <constructor-arg ref="dataSource" /> 
    </bean> 
    <bean id="userDao" class="com.riyun.daoImpl.UserDaoImpl">   
          <property name="jdbcTemplate" ref="jdbcTemplate"></property> 
    </bean>   
    <bean id="login" class="com.riyun.action.LoginAction">   
        <property name="userDao" ref="userDao" />   
    </bean>   
</beans> 
至此整个例子ok了。
在dao层连接数据库的时候还需要导入各个数据库所必须的jar包以及c3p0-0.9.1.2.jar这样的包。
总结:整合过程中 碰到许许多多的问题,相信大家看我这篇文章也会碰到许许多多不一样的问题,但是有问题不可怕,我们要做的就是分析问题的原因。我在整合过程碰到最多的问题就是classnotfound类的问题,其实这类的问题就是没有导入相关jar包导致的错误或者jar冲突导致的。

你可能感兴趣的:(spring,Hibernate,struts)