zoukankan      html  css  js  c++  java
  • Struts2.3.1Hibernate3.5.3Spring2.5.6整合

    RegisterAction.java

    View Code
     1 package com.xiong.ssh.register.action;
     2 
     3 import javax.annotation.Resource;
     4 
     5 import org.springframework.context.annotation.Scope;
     6 import org.springframework.stereotype.Component;
     7 
     8 import com.opensymphony.xwork2.ActionSupport;
     9 import com.opensymphony.xwork2.ModelDriven;
    10 import com.xiong.ssh.register.model.RegisterUser;
    11 import com.xiong.ssh.register.service.dao.RegisterUserServiceDao;
    12 import com.xiong.ssh.register.vo.RegisterCompleteInfo;
    13 
    14 //@Component("registerUserAction")
    15 //@Scope("prototype")
    16 public class RegisterAction extends ActionSupport implements
    17         ModelDriven<RegisterCompleteInfo>
    18 {
    19 
    20     /**
    21      * 
    22      */
    23     private static final long serialVersionUID = 1L;
    24     private RegisterUserServiceDao rusd;
    25     private RegisterCompleteInfo rc = new RegisterCompleteInfo();
    26 
    27     public RegisterCompleteInfo getRc()
    28     {
    29         return rc;
    30     }
    31 
    32     public void setRc(RegisterCompleteInfo rc)
    33     {
    34         this.rc = rc;
    35     }
    36 
    37     public RegisterUserServiceDao getRusd()
    38     {
    39         return rusd;
    40     }
    41 
    42     @Resource(name = "registerUserServiceImpl")
    43     public void setRusd(RegisterUserServiceDao rusd)
    44     {
    45         this.rusd = rusd;
    46     }
    47 
    48     @Override
    49     public String execute()
    50     {
    51         RegisterUser registerUser = new RegisterUser();
    52         if (!this.rusd.findRegisterUserByName(this.rc.getUsername()))
    53         {
    54             registerUser.setUsername(this.rc.getUsername());
    55             registerUser.setPassword(this.rc.getPassword());
    56             registerUser.setEmail(this.rc.getEmail());
    57             registerUser.setCity(this.rc.getCity());
    58 
    59             this.rusd.saveRegisterUser(registerUser);
    60             return SUCCESS;
    61         }
    62         return "failure";
    63     }
    64 
    65     @Override
    66     public RegisterCompleteInfo getModel()
    67     {
    68         // TODO Auto-generated method stub
    69         return this.rc;
    70     }
    71 
    72 }

    注意:

       Action里面不需要写@Component、@Scope以及@Resource注入相关的属性。因为Action中的属性是通过AutoWire 自动入的,默认按照名字。WebApplication启动时,Spring的的容器就启动了(通过web.xml中配置的istener,并读取了 applicationcontext.xml产生相关的Bean如:ServiceDaoImpl、RegisterUserDaoImpl)但是 Action的产生是通过Struts的Struts-Spring-plugin的插件产生的,产生Action以后,它会自动在Spring的的容器 寻找(默认按名字找)自己所需要的属性并注入。当然也可以通过配置Struts.xml中Action的Class(把class指定为 @Component所指定的名字,让Spring容器来生成Action,但需要特别注意的是要在Action中指定 @Scope("prototype"),默认是sington)

    IDAO.java

    View Code
     1 package com.xiong.ssh.register.dao;
     2 
     3 import java.util.List;
     4 
     5 public interface IDAO<T, K>
     6 {
     7     public boolean doInsert(T po);
     8 
     9     public boolean doUpdate(T po);
    10 
    11     public boolean doDelete(T po);
    12 
    13     public T findByName(String username);
    14 
    15     public List<T> findAll(String keyword);
    16 
    17     public List<T> findAll(String keyword, int currentRowIndex, int lineSize);
    18 
    19     public long getAllCount(String keyword);
    20 
    21 }

    RegisterUserDao.java

    View Code
    1 package com.xiong.ssh.register.dao;
    2 
    3 import com.xiong.ssh.register.model.RegisterUser;
    4 
    5 public interface RegisterUserDao extends IDAO<RegisterUser, Integer>
    6 {
    7     
    8 }

    RegisterUserDaoImpl.java

    View Code
      1 package com.xiong.ssh.register.dao.impl;
      2 
      3 import java.sql.SQLException;
      4 import java.util.Iterator;
      5 import java.util.List;
      6 
      7 import javax.annotation.Resource;
      8 
      9 import org.hibernate.HibernateException;
     10 import org.hibernate.Query;
     11 import org.hibernate.Session;
     12 import org.springframework.orm.hibernate3.HibernateCallback;
     13 import org.springframework.orm.hibernate3.HibernateTemplate;
     14 import org.springframework.stereotype.Component;
     15 
     16 import com.xiong.ssh.register.dao.RegisterUserDao;
     17 import com.xiong.ssh.register.model.RegisterUser;
     18 
     19 @Component("registerUserDaoImpl")
     20 public class RegisterUserDaoImpl implements RegisterUserDao
     21 {
     22 
     23     private HibernateTemplate hibernateTemplate;
     24 
     25     public HibernateTemplate getHibernateTemplate()
     26     {
     27         return hibernateTemplate;
     28     }
     29 
     30     @Resource
     31     public void setHibernateTemplate(HibernateTemplate hibernateTemplate)
     32     {
     33         this.hibernateTemplate = hibernateTemplate;
     34     }
     35 
     36     @Override
     37     public boolean doInsert(RegisterUser po)
     38     {
     39         boolean flag = true;
     40         try
     41         {
     42             this.hibernateTemplate.save(po);
     43         }
     44         catch (Exception e)
     45         {
     46             flag = false;
     47         }
     48         return flag;
     49     }
     50 
     51     @Override
     52     public boolean doUpdate(RegisterUser po)
     53     {
     54         boolean flag = true;
     55         try
     56         {
     57             this.hibernateTemplate.update(po);
     58         }
     59         catch (Exception e)
     60         {
     61             flag = false;
     62         }
     63         return flag;
     64     }
     65 
     66     @Override
     67     public boolean doDelete(RegisterUser po)
     68     {
     69         boolean flag = true;
     70         try
     71         {
     72             this.hibernateTemplate.delete(po);
     73         }
     74         catch (Exception e)
     75         {
     76             flag = false;
     77         }
     78         return flag;
     79     }
     80 
     81     @Override
     82     public RegisterUser findByName(String username)
     83     {
     84         RegisterUser registerUser = null;
     85         List<RegisterUser> users = this.hibernateTemplate
     86                 .find("from RegisterUser r where r.username='" + username + "'");
     87 
     88         if (users != null && users.size() > 0)
     89         {
     90             registerUser = users.get(0);
     91         }
     92         return registerUser;
     93     }
     94 
     95     @Override
     96     public List<RegisterUser> findAll(String keyword)
     97     {
     98         List<RegisterUser> users = this.hibernateTemplate
     99                 .find("from RegisterUser where (username like '%" + keyword
    100                         + "%' OR  email like '%" + keyword
    101                         + "% 'OR  city like '%" + keyword + "%')");
    102         return users;
    103     }
    104 
    105     @Override
    106     public List<RegisterUser> findAll(String keyword, final int currentRowIndex,
    107             final int lineSize)
    108     {
    109         final String hql = "from RegisterUser where (username like '%"
    110                 + keyword + "%' OR  email like '%" + keyword
    111                 + "% 'OR  city like '%" + keyword + "%') order by id desc";
    112         List<RegisterUser> users = this.hibernateTemplate
    113                 .executeFind(new HibernateCallback()
    114                 {
    115 
    116                     @Override
    117                     public Object doInHibernate(Session session)
    118                             throws HibernateException, SQLException
    119                     {
    120                         Query query = session.createQuery(hql);
    121                         query.setFirstResult(currentRowIndex);
    122                         query.setMaxResults(lineSize);
    123                         return query.list();
    124                     }
    125                 });
    126         return users;
    127     }
    128 
    129     @Override
    130     public long getAllCount(String keyword)
    131     {
    132         long count = (Long) this.hibernateTemplate
    133                 .find("select count(*) from RegisterUser where (username like '%"
    134                         + keyword
    135                         + "%' OR  email like '%"
    136                         + keyword
    137                         + "% 'OR  city like '%" + keyword + "%')").iterator()
    138                 .next();
    139         return count;
    140     }
    141 }

    RegisterUserDaoImplTest-context.xml

    View Code
    1 <?xml version="1.0" encoding="UTF-8" ?>
    2 <beans xmlns="http://www.springframework.org/schema/beans"
    3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4 xsi:schemaLocation="http://www.springframework.org/schema/beans 
    5 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    6 
    7 <import resource="classpath:/applicationContext.xml"/>
    8 
    9 </beans>

    注意:

        1、Hibernate4中不能再注入HibernateTemplate了,可以通过注入SessionFactory完成DAO的操作。

          2、当调用HibernateTemplate的save方法的时候,在save()方法内部调用了HibernateTemplate的 executeWithNativeSession(),该方法要传一个实现了HibernateCallBack接口的对象,于是,在 executeWithNativeSession()方法的内部创建了一个实现HibernateCallBack接口的匿名对象,然后调用了 HibernateCallBack接口doInHibernate()方法,该方法通过传进来的session完成了真实的逻辑,然后再返回。

        3、RegisterUserDaoImplTest-context.xml用户JUINT测试。

    RegisterUserServiceDao.java

    View Code
     1 package com.xiong.ssh.register.service.dao;
     2 
     3 import com.xiong.ssh.register.model.RegisterUser;
     4 
     5 public interface RegisterUserServiceDao
     6 {
     7     public boolean saveRegisterUser(RegisterUser registerUser);
     8 
     9     public boolean findRegisterUserByName(String username);
    10 
    11 }

    RegisterUserServiceImpl.java

    View Code
     1 package com.xiong.ssh.register.service.impl;
     2 
     3 import javax.annotation.Resource;
     4 
     5 import org.springframework.stereotype.Component;
     6 
     7 import com.xiong.ssh.register.dao.IDAO;
     8 import com.xiong.ssh.register.model.RegisterUser;
     9 import com.xiong.ssh.register.service.dao.RegisterUserServiceDao;
    10 
    11 @Component("registerUserServiceImpl")
    12 public class RegisterUserServiceImpl implements RegisterUserServiceDao
    13 {
    14     private IDAO<RegisterUser, Integer> dao;
    15 
    16     public IDAO<RegisterUser, Integer> getDao()
    17     {
    18         return dao;
    19     }
    20 
    21     @Resource(name = "registerUserDaoImpl")
    22     public void setDao(IDAO<RegisterUser, Integer> dao)
    23     {
    24         this.dao = dao;
    25     }
    26 
    27     @Override
    28     public boolean saveRegisterUser(RegisterUser registerUser)
    29     {
    30         boolean flag = false;
    31         try
    32         {
    33             flag = this.dao.doInsert(registerUser);
    34         }
    35         catch (Exception e)
    36         {
    37             e.printStackTrace();
    38         }
    39         return flag;
    40     }
    41 
    42     @Override
    43     public boolean findRegisterUserByName(String username)
    44     {
    45         boolean flag = false;
    46         RegisterUser user = null;
    47         try
    48         {
    49             user = this.dao.findByName(username);
    50             if (user != null)
    51             {
    52                 flag = true;
    53             }
    54         }
    55         catch (Exception e)
    56         {
    57             e.printStackTrace();
    58         }
    59         return flag;
    60     }
    61 
    62 }

    RegisterUser.java

    View Code
     1 package com.xiong.ssh.register.model;
     2 
     3 import javax.persistence.Entity;
     4 import javax.persistence.GeneratedValue;
     5 import javax.persistence.Id;
     6 
     7 @Entity
     8 public class RegisterUser
     9 {
    10     private int id;
    11     private String username;
    12     private String password;
    13     private String email;
    14     private String city;
    15 
    16     @Id
    17     @GeneratedValue
    18     public int getId()
    19     {
    20         return id;
    21     }
    22 
    23     public void setId(int id)
    24     {
    25         this.id = id;
    26     }
    27 
    28     public String getUsername()
    29     {
    30         return username;
    31     }
    32 
    33     public void setUsername(String username)
    34     {
    35         this.username = username;
    36     }
    37 
    38     public String getPassword()
    39     {
    40         return password;
    41     }
    42 
    43     public void setPassword(String password)
    44     {
    45         this.password = password;
    46     }
    47 
    48     public String getEmail()
    49     {
    50         return email;
    51     }
    52 
    53     public void setEmail(String email)
    54     {
    55         this.email = email;
    56     }
    57 
    58     public String getCity()
    59     {
    60         return city;
    61     }
    62 
    63     public void setCity(String city)
    64     {
    65         this.city = city;
    66     }
    67 
    68 }

    RegisterCompleteInfo.java

    View Code
     1 package com.xiong.ssh.register.vo;
     2 
     3 public class RegisterCompleteInfo
     4 {
     5     private int id;
     6     private String username;
     7     private String password;
     8     private String passwordRepeat;
     9     private String email;
    10     private String city;
    11 
    12     public int getId()
    13     {
    14         return id;
    15     }
    16 
    17     public void setId(int id)
    18     {
    19         this.id = id;
    20     }
    21 
    22     public String getUsername()
    23     {
    24         return username;
    25     }
    26 
    27     public void setUsername(String username)
    28     {
    29         this.username = username;
    30     }
    31 
    32     public String getPassword()
    33     {
    34         return password;
    35     }
    36 
    37     public void setPassword(String password)
    38     {
    39         this.password = password;
    40     }
    41 
    42     public String getPasswordRepeat()
    43     {
    44         return passwordRepeat;
    45     }
    46 
    47     public void setPasswordRepeat(String passwordRepeat)
    48     {
    49         this.passwordRepeat = passwordRepeat;
    50     }
    51 
    52     public String getEmail()
    53     {
    54         return email;
    55     }
    56 
    57     public void setEmail(String email)
    58     {
    59         this.email = email;
    60     }
    61 
    62     public String getCity()
    63     {
    64         return city;
    65     }
    66 
    67     public void setCity(String city)
    68     {
    69         this.city = city;
    70     }
    71 }

    struts.xml

    View Code
     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
     3 <struts>
     4     <constant name="struts.configuration.xm.reload" value="true"></constant>
     5     <constant name="struts.devMode" value="true"></constant>
     6     <constant name="struts.multipart.maxSize" value="10*1024*1024"></constant>    
     7     <constant name="struts.ui.theme" value="simple"></constant>
     8     <constant name="struts.i18n.encoding" value="GBK"></constant> 
     9     
    10     <package name="register" extends="struts-default" namespace="/Register" >
    11         
    12         <default-action-ref name="login"></default-action-ref>    
    13             
    14         <!-- <action name="registerUserAction" class="registerUserAction" >     可以通过这种方法把Action交给Spring管理-->        
    15         <action name="registerUserAction" class="com.xiong.ssh.register.action.RegisterAction" >            
    16             <result name="success">/Register/RegisterSuccess.jsp</result>
    17             <result name="failure">/Register/Register.jsp</result>
    18         </action>        
    19         
    20     </package>
    21 </struts>    

    applicationContext.xml

    View Code
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans
     3     xmlns="http://www.springframework.org/schema/beans"
     4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
     5     xmlns:context="http://www.springframework.org/schema/context"
     6     xmlns:tx="http://www.springframework.org/schema/tx"
     7     xmlns:aop="http://www.springframework.org/schema/aop"
     8     xmlns:p="http://www.springframework.org/schema/p"
     9     xsi:schemaLocation="http://www.springframework.org/schema/beans 
    10                         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    11                         http://www.springframework.org/schema/context 
    12                         http://www.springframework.org/schema/context/spring-context-2.5.xsd
    13                         http://www.springframework.org/schema/tx 
    14                          http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    15                         http://www.springframework.org/schema/aop 
    16                         http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    17         
    18     <context:annotation-config/>
    19     <context:component-scan base-package="com.xiong"></context:component-scan>
    20     
    21     <!-- DataSource -->    
    22     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"    destroy-method="close">
    23         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    24         <property name="url" value="jdbc:oracle:thin:@localhost:1521:study" />
    25         <property name="username" value="scott" />
    26         <property name="password" value="tiger" />
    27     </bean>
    28     
    29     <!-- SessionFactory -->
    30     <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">    
    31         <property name="dataSource" ref="myDataSource"/>
    32         <property name="packagesToScan">
    33             <list>
    34                 <value>com.xiong.ssh.register.model</value>
    35             </list>
    36         </property>      
    37         <property name="hibernateProperties">
    38             <props>
    39               <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
    40               <prop key="hibernate.show_sql">true</prop>
    41               <prop key="hibernate.format_sql">true</prop>
    42               <prop key="hibernate.hbm2ddl.auto">update</prop>
    43               <prop key="javax.persistence.validation.mode">none</prop>
    44              </props>
    45         </property>
    46       </bean>     
    47       
    48       <!-- HibernateTemplate -->
    49       <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    50          <property name="sessionFactory" ref="mySessionFactory"></property>
    51      </bean> 
    52      
    53     <!-- TransactionManager -->
    54     <bean id="transactionManager"
    55         class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    56         <property name="sessionFactory" ref="mySessionFactory" />
    57     </bean>
    58 
    59     <aop:config>
    60         <aop:pointcut
    61             expression="execution(public * com.xiong.ssh.register.service.impl..*.*(..))"
    62             id="servicePoinitcut" />
    63         <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePoinitcut" />
    64     </aop:config>    
    65      <tx:advice id="txAdvice" transaction-manager="transactionManager">
    66         <tx:attributes>
    67           <tx:method name="find*" read-only="true"/>
    68           <tx:method name="save*" propagation="REQUIRED"/>
    69         </tx:attributes>
    70       </tx:advice>        
    71 </beans>

    web.xml

    View Code
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     
     5     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
     6 
     7     <!-- Struts To Spring Listener -->
     8     <listener>
     9         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    10     </listener>
    11     <context-param>
    12         <param-name>contextConfigLocation</param-name>
    13         <!-- <param-value>/WEB-INF/applicationContext.xml</param-value> -->
    14         <param-value>classpath:applicationContext.xml</param-value>
    15     </context-param>
    16     
    17     <!-- Filter有先后顺序的 -->
    18     <filter>
    19         <filter-name>openSessionInView</filter-name>
    20         <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    21         <init-param>
    22             <param-name>sessionFactoryBeanName</param-name>
    23             <param-value>mySessionFactory</param-value>
    24         </init-param>
    25     </filter>
    26     <filter-mapping>
    27         <filter-name>openSessionInView</filter-name>
    28         <url-pattern>/*</url-pattern>
    29     </filter-mapping>    
    30     
    31     <!-- 更改字符集 -->
    32 <!--     <filter>
    33         <filter-name>encode</filter-name>
    34         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    35         <init-param>
    36             <param-name>encoding</param-name>
    37             <param-value>GBK</param-value>
    38         </init-param>        
    39     </filter>
    40     <filter-mapping>
    41         <filter-name>encode</filter-name>
    42         <url-pattern>/*</url-pattern>
    43     </filter-mapping> -->
    44     
    45     
    46     <filter>
    47         <filter-name>struts2</filter-name>
    48         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    49     </filter>
    50     <filter-mapping>
    51         <filter-name>struts2</filter-name>
    52         <url-pattern>/*</url-pattern>
    53     </filter-mapping>
    54 
    55     <welcome-file-list>
    56         <welcome-file>index.jsp</welcome-file>
    57     </welcome-file-list>
    58 
    59 </web-app>

    注意:

        OpenSessionInViewFilter把一个Session和一次完整的请求过程对应的线程相绑定,这样就延迟了Session关闭的时 间。如果applicationcontext.xml配置文件里面没有配置事务边界,OpenSessionInViewFilter的拦截到任何调用 session的方法,都会把事务当作"Read-Only"处理,这样情况下是不允许写入数据的。如果是这样的话,在 RegisterUserDaoImpl.java中调用通过hibernateTemplate调用save()或者其他修改数据库操作的方法时会抛出 异常.

    Register.jsp

    View Code
     1 <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
     2 <%@ taglib prefix="s" uri="/struts-tags" %>
     3 <%
     4 String path = request.getContextPath();
     5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     6 %>
     7 
     8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     9 <html>
    10   <head>
    11     <base href="<%=basePath%>">
    12     
    13     <title>用户注册</title>
    14     
    15     <meta http-equiv="pragma" content="no-cache">
    16     <meta http-equiv="cache-control" content="no-cache">
    17     <meta http-equiv="expires" content="0">    
    18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    19     <meta http-equiv="description" content="This is my page">
    20   </head>
    21   
    22   <body>
    23        <form action="<%=basePath%>Register/registerUserAction.action" method="POST">
    24            用户名:<input type="text" name="username" /><br />
    25            密码:<input type="password" name="password" /><br />
    26            再次输入密码:<input type="password" name="passwordRepeat" /><br />
    27            E-Mail:<input type="text" name="email" /><br />
    28            来自:<input type="text" name="city" /><br />
    29            <input type="submit" value="注册">
    30        </form>
    31        <s:debug></s:debug>
    32   </body>
    33 </html>

    所需要的jar包如下:

  • 相关阅读:
    SpringBoot之Banner介绍
    SpringBoot事件监听机制
    SpringBoot 启动流程图
    ApplicationContextInitializer的理解和使用
    SpringFactoriesLoader解析
    计时器之StopWatch
    ftp上下载文件
    打印两个函数的返回值
    关闭所有已打开的文件和关闭应用
    TypeError: include() got an unexpected keyword argument 'app_name'
  • 原文地址:https://www.cnblogs.com/xiongyu/p/2497726.html
Copyright © 2011-2022 走看看