ssh整合

SSH整合前应该先熟悉各个框架的单独使用,至少要了解各自的xml配置。


环境:struts-2.3.15.1,spring-3.2.4,hibernate-4.2.3,myeclipse10,JDK-1.6,Mysql

Jar包:
struts-2.3.15.1:
sturts2空项目下的所有jar包    asm-3.3.jar
    asm-commons-3.3.jar
    asm-tree-3.3.jar
    commons-fileupload-1.2.2.jar
    commons-io-2.0.1.jar
    commons-lang3-3.1.jar
    freemarker-2.3.19.jar
    javassist-3.11.0.GA.jar
    ognl-3.0.5.jar
    struts2-core-2.3.4.1.jar
    xwork-core-2.3.4.1.jar
其他    struts2-spring-plugin-2.3.15.1
    commons-logging-1.1.3
    aopalliance-1.0


spring-3.2.4:
spring-aop-3.2.4.RELEASE.jar
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
spring-jdbc-3.2.4.RELEASE.jar
spring-orm-3.2.4.RELEASE.jar
spring-tx-3.2.4.RELEASE.jar
spring-web-3.2.4.RELEASE.jar

hibernate-4.2.3:
lib-required下的所有jar包
c3p0-0.9.2.1.jar
hibernate-c3p0-4.2.3.Final.jar
hibernate-entitymanager-4.2.3.Final.jar




1.    新建web项目
2.    以简单的登录验证为例
3.    建立login.jsp,login_success.jsp,login_error.jsp
 
4.    引入struts2
(1)    web.xml配置
<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>
(2)    src下的struts.xml配置
<package name="default" namespace="/" extends="struts-default">


        <action name="login" class="com.accp.action.LoginAction" method="login">
            <result name="success"> /login_success.jsp </result>
            <result name="error"> /login_error.jsp </result>
        </action>
       
</package>


(3)    测试struts2是否能够通过


5.    引入spring
(1)配置web.xml,添加listener
<listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- 告知spring config location 的存储位置 -->
    <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:beans.xml</param-value>
    </context-param>
(2)配置src下的beans.xml
将spring的ApplicationContext.xml拷贝至src下,删除里面的配置项,只保留下面内容
<?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.xsd"
          >
</beans>
    
6.    引入hibernate
    (1)配置beans.xml
<?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:jee="http://www.springframework.org/schema/jee"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:util="http://www.springframework.org/schema/util"
           xmlns:tool="http://www.springframework.org/schema/tool"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/jee
           http://www.springframework.org/schema/jee/spring-jee.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util.xsd
           http://www.springframework.org/schema/tool
           http://www.springframework.org/schema/tool/spring-tool.xsd"
           default-lazy-init="true" default-autowire="byName">

    <!--spring jdbc配置数据源 Mysql-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
         <property name="url" value="jdbc:mysql://localhost:3306/test" />
         <property name="username" value="user" />
         <property name="password" value="123456" />  
    </bean>    
    
    <!-- hibernate.cfg.xml Spring config -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        
        <!-- connection -->
        <property name="dataSource" >
            <ref local="dataSource"/>
        </property>
        
        <!-- hibernate自身属性  -->
        <property name="hibernateProperties">
            <props>
               <prop key="hibernate.show_sql">true</prop>
               <prop key="hibernate.format_sql">true</prop>
               <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
               <prop key="hibernate.current_session_context_class">thread</prop>
            </props>
        </property>
        
        <!-- 映射文件
        <property name="mappingResources">
            <list>
              <value>com/forwor/ssh/entity/xml/User.hbm.xml</value>
            </list>
        </property>
         -->
    </bean>
    
    <!-- 注入 -->
    <bean id="userDao" class="com.accp.dao.impl.UserDaoImpl">
        <property name="sessionFactory">
           <ref local="sessionFactory"/>
        </property>
    </bean>
      
    <!-- aop -->
    <!-- transaction -->
    <bean id="userManager" class="com.accp.service.impl.UserManagerImpl">
        <property name="userDao">
           <ref local="userDao"/>
        </property>
    </bean>
           
    <!-- advice -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory">
           <ref local="sessionFactory"/>
        </property>
    </bean>
    
    <!-- 事务处理 -->
    <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
        <property name="transactionManager">
           <ref local="transactionManager"/>
        </property>
        <property name="transactionAttributes">
           <props>
              <prop key="register">PROPAGATION_REQUIRED</prop>
              
              <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到-->
              <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
              <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
              <prop key="select*">PROPAGATION_REQUIRED,readOnly</prop>
              <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>
              
              <prop key="sync*">PROPAGATION_REQUIRED</prop>
              <prop key="finish*">PROPAGATION_REQUIRED</prop>
              <prop key="add*">PROPAGATION_REQUIRED</prop>
              <prop key="insert*">PROPAGATION_REQUIRED</prop>
              <prop key="edit*">PROPAGATION_REQUIRED</prop>
              <prop key="update*">PROPAGATION_REQUIRED</prop>
              <prop key="save*">PROPAGATION_REQUIRED</prop>
              <prop key="remove*">PROPAGATION_REQUIRED</prop>
              <prop key="delete*">PROPAGATION_REQUIRED</prop>
              <prop key="login*">PROPAGATION_REQUIRED</prop>
              <prop key="*">PROPAGATION_REQUIRED,-java.lang.Exception</prop>    
           </props>
        </property>
    </bean>
    
      <!-- autoproxy 自动创建代理-->
      <bean id="ProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
         <property name="beanNames">
             <list>
                <value>*Manager</value>
             </list>
         </property>
         <property name="interceptorNames">
             <list>
                <value>transactionInterceptor</value>
             </list>
         </property>
      </bean>
      
    <bean id="loginAction" class="com.accp.action.LoginAction" scope="prototype">
        <property name="userManager">
           <ref local="userManager"/>
        </property>
    </bean>
      
</beans>
    

7.    类图
    以用户登录验证为基础的测试    

包    类或接口    方法或属性
com.accp.action    LoginAction    User user
UserManager userManager
String login()
com.accp.model    User    int id
String username
String password
com.accp.dao    UserDao    boolean exist()
com.accp.dao.impl    UserDaoImpl    SessionFactory sessionFactory
boolean exist()
com.accp.service    UserManager    String login()
com.accp.service.impl    UserManagerImpl    UserDao userDao
String login()


流程控制
 

8.    注意事项
(1)    login.jsp 输入内容的name为user.username user.password时,LoginAction中应该为user生成相应的get/set方法。
(2)    通过spring注入的属性,应该生成相应的get/set方法。
(3)    如果登录时网页出现错误nested transactions not supported,一般错误出在UserDaoImpl的exist()方法的session.beginTransaction()这一行。这是因为getCurrentSession()没有获得session。先检查beans.xml中事务管理配置,看看是否在UserManager中login方法或者UserDao的exist()方法上开启事务。然后检查UserDaoImpl的属性sessionFactory有没有get/set方法。检查session执行对应的数据库操作后,有没有提交事务(session.getTransaction.commit())。如果会报以上错误,在beans.xml的hibernate配置中加入<prop key="hibernate.current_session_context_class">thread</prop>。如果还是不能解决问题,请google或baidu一下。
(4)    当前测试的代码只是完成了用户登录验证功能,只是将hibernate的SessionFactory通过spring注入,数据库操作使用的是原生的sql语句,没有使用实体。如果需要测试,请自己完成实体类xml或者使用HibernateAnnotation。
(5)    如果操作中出现其他错误,请google或baidu一下。

9.    主要代码
(1)    login.jsp
<form action="login.action" method="post">
    用户名:<input type="text" name="user.username" /> <br>
    密码:<input type="password" name="user.password" /> <br>
    <input type="submit" value="提交" />  <input type="reset" value="重置" />
    </form>

(2)    web.xml
<?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">
  <display-name></display-name>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 


  <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>
    
     <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- 告知spring config location 的存储位置 -->
    <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:beans.xml</param-value>
    </context-param>
    
 
</web-app>


(3)    struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    
    <!-- 开发模式,设置为true时,改动strust.xml会自动更新server,而不用重新启动server -->
    <constant name="struts.devMode" value="true" />
    



    <!-- Add packages here -->
    
    <package name="default" namespace="/" extends="struts-default">


        <action name="login" class="com.accp.action.LoginAction" method="login">
            <result name="success"> /login_success.jsp </result>
            <result name="error"> /login_error.jsp </result>
        </action>
       
    </package>

</struts>


(4)    beans.xml
<?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:jee="http://www.springframework.org/schema/jee"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:util="http://www.springframework.org/schema/util"
           xmlns:tool="http://www.springframework.org/schema/tool"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/jee
           http://www.springframework.org/schema/jee/spring-jee.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util.xsd
           http://www.springframework.org/schema/tool
           http://www.springframework.org/schema/tool/spring-tool.xsd"
           default-lazy-init="true" default-autowire="byName">

    <!--spring jdbc配置数据源 Mysql-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
         <property name="url" value="jdbc:mysql://localhost:3306/test" />
         <property name="username" value="user" />
         <property name="password" value="123456" />  
    </bean>    
    
    <!-- hibernate.cfg.xml Spring config -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        
        <!-- connection -->
        <property name="dataSource" >
            <ref local="dataSource"/>
        </property>
        
        <!-- hibernate自身属性  -->
        <property name="hibernateProperties">
            <props>
               <prop key="hibernate.show_sql">true</prop>
               <prop key="hibernate.format_sql">true</prop>
               <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
               <prop key="hibernate.current_session_context_class">thread</prop>
            </props>
        </property>
        
        <!-- 映射文件
        <property name="mappingResources">
            <list>
              <value>com/forwor/ssh/entity/xml/User.hbm.xml</value>
            </list>
        </property>
         -->
    </bean>
    
    <!-- 注入 -->
    <bean id="userDao" class="com.accp.dao.impl.UserDaoImpl">
        <property name="sessionFactory">
           <ref local="sessionFactory"/>
        </property>
    </bean>
      
    <!-- aop -->
    <!-- transaction -->
    <bean id="userManager" class="com.accp.service.impl.UserManagerImpl">
        <property name="userDao">
           <ref local="userDao"/>
        </property>
    </bean>
           
    <!-- advice -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory">
           <ref local="sessionFactory"/>
        </property>
    </bean>
    
    <!-- 事务处理 -->
    <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
        <property name="transactionManager">
           <ref local="transactionManager"/>
        </property>
        <property name="transactionAttributes">
           <props>
              <prop key="register">PROPAGATION_REQUIRED</prop>
              
              <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到-->
              <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
              <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
              <prop key="select*">PROPAGATION_REQUIRED,readOnly</prop>
              <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>
              
              <prop key="sync*">PROPAGATION_REQUIRED</prop>
              <prop key="finish*">PROPAGATION_REQUIRED</prop>
              <prop key="add*">PROPAGATION_REQUIRED</prop>
              <prop key="insert*">PROPAGATION_REQUIRED</prop>
              <prop key="edit*">PROPAGATION_REQUIRED</prop>
              <prop key="update*">PROPAGATION_REQUIRED</prop>
              <prop key="save*">PROPAGATION_REQUIRED</prop>
              <prop key="remove*">PROPAGATION_REQUIRED</prop>
              <prop key="delete*">PROPAGATION_REQUIRED</prop>
              <prop key="login*">PROPAGATION_REQUIRED</prop>
              <prop key="*">PROPAGATION_REQUIRED,-java.lang.Exception</prop>    
           </props>
        </property>
    </bean>
    
      <!-- autoproxy 自动创建代理-->
      <bean id="ProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
         <property name="beanNames">
             <list>
                <value>*Manager</value>
             </list>
         </property>
         <property name="interceptorNames">
             <list>
                <value>transactionInterceptor</value>
             </list>
         </property>
      </bean>
      
    <bean id="loginAction" class="com.accp.action.LoginAction" scope="prototype">
        <property name="userManager">
           <ref local="userManager"/>
        </property>
    </bean>
      
</beans>
    


(5)    LoginAction
package com.accp.action;

import com.accp.model.User;
import com.accp.service.UserManager;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{
    
    User user=new User();
    UserManager userManager;
    
    public String login(){
        return userManager.login(user);
        
    }


    public User getUser() {
        return user;
    }


    public void setUser(User user) {
        this.user = user;
    }


    public UserManager getUserManager() {
        return userManager;
    }


    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }
    
    
}

(6)    UserDaoImpl
package com.accp.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.accp.dao.UserDao;
import com.accp.model.User;

public class UserDaoImpl implements UserDao{
    
    private SessionFactory sessionFactory;

    public void add(User user) {
        
        
    }

    public void delete(User user) {
        
        
    }

    public void update(User user) {
        
        
    }

    public List<User> queryAll() {
        return null;
    }

    public User queryByName(String name) {
        
        return null;
    }

    public User queryById(int id) {
        
        return null;
    }

    public boolean exist(User user) {
        Session session=sessionFactory.getCurrentSession();
        
        session.getTransaction().begin();
        Query query = session.createSQLQuery("select * from user where username='"+user.getUsername()+"' and password='"+user.getPassword()+"'");
        
        List list = query.list();
        session.getTransaction().commit();
        if(list.size()>0){
            return true;
        }else{
            return false;
        }
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

}

(7)    UserManagerImpl
package com.accp.service.impl;

import java.util.List;

import org.hibernate.SessionFactory;

import com.accp.dao.UserDao;
import com.accp.model.User;
import com.accp.service.UserManager;

public class UserManagerImpl implements UserManager{

    private UserDao userDao;
    
    public void add(User user) {
        
        
    }

    public void delete(User user) {
        
        
    }

    public void update(User user) {
        
        
    }

    public List<User> queryAll() {
        
        return null;
    }

    public User queryByName(String name) {
        
        return null;
    }

    public User queryById(int id) {
        
        return null;
    }

    /**
     * 检查是否存在用户
     * 数据库有匹配的用户名与密码,返回true
     * 否则返回false
     */
    public boolean exist(User user) {
        return userDao.exist(user);
        
    }

    /**
     * 用户登录
     * 用户名和密码都匹配上时返回"success"
     * 否则返回"error"
     */
    public String login(User user) {
        if(exist(user)){
            return "success";
        }else{
            return "error";
        }
    }


    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值