`

转载:Spring和Hibernate的整合

阅读更多

转载自:SSH2 Step by Step- Step 4 - Struts2、Spring和Hibernate的整合

 

折腾了好几天,终于把SSH2的框架搭起来,期间经历的兴奋,痛苦,犹豫...最终是领悟:太完美的要求,其实就是拖延...所以在以下的jar包的选择上,跟前面几篇的原则有了很大的区别:

  1. Struts包保持原样。
  2. Spring 和hibernate的包按最大的导入,因为少了个jar文件导致的错误查找,实在是这两天最痛苦的事情。
  3. Hibernate从4.0降到3.6.8,原因是Hibernate4改变太大,我又不想在期初用Maven来更新Jar包.


上一篇中提到怎么整合Struts2和hibernate,接下来,到了最最最关键的时刻,要把Spring融合进来...
Spring在MVC中的作用应该是C的功能,提供了一个对象的容器...

言归正传. 我们需要开始引入几个Spring的包.

1. 下载Hibernate3.6.8的包,解压后copy requred目录下的所有的文件到lib目录下,注意这里有一个antlr2.7.7.jar的, 要替换掉原先struts引入的那个低版本(2.7.2)的jar文件。保险一点把jpa目录下的那个jpa的jar包也copy(hibernate-jpa-2.0-api-1.0.1.Final.jar)
2.  导入struts2-spring-plugin-2.2.3.1.jar  (这个在Struts2的包里面找),copy到WEB-INF/lib目录下
3. 导入Spring的一些Jar包 : 导入spring 的dist 目录下的所有的jar文件

 

接下来我们比较一下加入Spring有什么变化:

  1. 配置web.xml, -- 一些Struts和Spring的启动项会在这里配置 
  2. 配置ApplicationContext.xml -- 删除hibernate.cfg.xml, 将配置挪到这里来做(增加SessionFactory和dataSource的设置),也就是由Spring来接管
  3. 增加POJO类和Hibernate的ORM映射文件(xxx.hbm.xml)  -- 个人建议,如果Table间的关系比较简单,用annotation来避免重复维护ORM映射文件. 但是这里还是按照传统的做法。
  4. 编写DAO接口和DAO实现类 -- 将接口和实现类分离的好处就不用我讲了,(OO设计原则:将类的行为和实现分离,面向接口编程)
  5. 将DAO的实现类的配置增加到ApplicationContext.xml中 -- 注意,Application中的Bean都是class,而不是interface.
  6. 增加业务类接口和实现类 -- (个人理解:DAO类只对应一个Table,但是业务类对应的可能是一个业务流程...欢迎扔砖)
  7. 增加Client端Jsp页面
  8. 增加Action类,将jsp的请求转发给业务处理类(其实这里是转给业务接口类)
  9. 修改struts.xml, 增加action的调用,这里用了struts的伪调用,实际上action的请求和转发由spring接管了 --- (struts2-spring-plugin-2.2.3.1.jar  )会干这个活。
  10. 修改applicationContext.xml, 增加action bean

马上开始:
1. 先把需要的jar包列一下:

2. web.xml文件的配置,增加struts2和spring的启动项

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app   
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.         xmlns="http://java.sun.com/xml/ns/javaee"   
  5.         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
  6.         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
  7.         id="WebApp_ID" version="2.5">  
  8.       
  9.     <!-- Spring configuration -->  
  10.     <context-param>  
  11.         <param-name>contextConfigLocation</param-name>  
  12.         <param-value>classpath:applicationContext*.xml</param-value>  
  13.     </context-param>  
  14.     <listener>  
  15.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  16.     </listener>  
  17.       
  18.     <!-- Struts2 configuration -->  
  19.     <filter>   
  20.          <filter-name>struts2</filter-name>   
  21.          <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>   
  22.      </filter>   
  23.      <filter-mapping>   
  24.          <filter-name>struts2</filter-name>   
  25.          <url-pattern>/*</url-pattern>   
  26.      </filter-mapping>   
  27.        
  28. </web-app>  


3. 配置ApplicationContext.xml -- 删除hibernate.cfg.xml, 将配置挪到这里来做(增加SessionFactory和dataSource的设置),也就是由Spring来接管,该文件放在src目录下:
注意这里我将一个applicationContext.xml分成了3部分,

 

  • 数据库的连接串单独放一个文件(dataSource.properties)
  • 平时不大会动的数据库配置放到database.xml中
  • applicationContext.xml会导入上面的内容,我们可以集中在bean的设置上


applicationContext.xml

  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" xmlns:context="http://www.springframework.org/schema/context"  
  4. xmlns:aop="http://www.springframework.org/schema/aop"  
  5. xmlns:tx="http://www.springframework.org/schema/tx"  
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  8.            http://www.springframework.org/schema/aop   
  9.            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  10.            http://www.springframework.org/schema/context  
  11.            http://www.springframework.org/schema/context/spring-context-2.5.xsd    
  12.            http://www.springframework.org/schema/tx   
  13.            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  14.   
  15.     <!-- Hibernate configuration -->  
  16.     <import resource="classpath:database.xml"/>  
  17.       
  18. </beans>  

database.xml

  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" xmlns:context="http://www.springframework.org/schema/context"  
  4. xmlns:aop="http://www.springframework.org/schema/aop"  
  5. xmlns:tx="http://www.springframework.org/schema/tx"  
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  8.            http://www.springframework.org/schema/aop   
  9.            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  10.            http://www.springframework.org/schema/context  
  11.            http://www.springframework.org/schema/context/spring-context-2.5.xsd    
  12.            http://www.springframework.org/schema/tx   
  13.            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  14.       
  15.     <bean id="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  16.         <property name="location">  
  17.             <value>classpath:dataSource.properties</value>  
  18.         </property>  
  19.     </bean>  
  20.     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  21.         <property name="driverClassName" value="${dataSource.driverClassName}" />  
  22.         <property name="url" value="${dataSource.url}" />  
  23.         <property name="username" value="${dataSource.username}" />  
  24.         <property name="password" value="${dataSource.password}" />  
  25.     </bean>  
  26.     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  27.         <property name="dataSource" ref="dataSource" />  
  28.         <property name="hibernateProperties">  
  29.             <props>  
  30.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
  31.                 <prop key="hibernate.show_sql">true</prop>  
  32.             </props>  
  33.         </property>  
  34.         <property name="mappingResources">  
  35.             <list>  
  36.                 <value>com/test/bean/User.hbm.xml</value>  
  37.             </list>  
  38.         </property>  
  39.     </bean>  
  40.   
  41.       
  42. </beans>      


dataSource.properties

  1. dataSource.driverClassName=com.mysql.jdbc.Driver  
  2. dataSource.url=jdbc:mysql://localhost/test?characterEncoding=utf-8  
  3. dataSource.username=root  
  4. dataSource.password=root  

4. 增加一个User的POJO类和Hibernate对应的映射文件.

  1. package com.test.bean;  
  2.   
  3. public class User {  
  4.     private Integer id;  
  5.     public Integer getId() {  
  6.         return id;  
  7.     }  
  8.     public void setId(Integer id) {  
  9.         this.id = id;  
  10.     }  
  11.     private String name;  
  12.     private String password;  
  13.     public String getName() {  
  14.         return name;  
  15.     }  
  16.     public void setName(String name) {  
  17.         this.name = name;  
  18.     }  
  19.     public String getPassword() {  
  20.         return password;  
  21.     }  
  22.     public void setPassword(String password) {  
  23.         this.password = password;  
  24.     }  
  25.       
  26. }  


User.hbm.xml

  1. <?xml version="1.0"?>    
  2. <!DOCTYPE hibernate-mapping PUBLIC     
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">    
  5. <hibernate-mapping>    
  6.     <class name="com.test.bean.User" table="User" catalog="test">  
  7.         <id name="id" type="java.lang.Integer">  
  8.             <column name="id" />  
  9.             <generator class="native" />  
  10.         </id>  
  11.         <property name="name" type="java.lang.String">  
  12.             <column name="name" length="40" />  
  13.         </property>  
  14.         <property name="password" type="java.lang.String">  
  15.             <column name="password" length="40" />  
  16.         </property>  
  17.     </class>  
  18. </hibernate-mapping>  


5. 编写DAO接口和DAO实现

  1. package com.test.dao;  
  2.   
  3. import com.test.bean.User;  
  4.   
  5. public interface UserDao {  
  6.     public User find(String name, String password);  
  7.     public User find(User user);  
  8. }  

 

  1. package com.test.daoImpl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Query;  
  6. import org.hibernate.Session;  
  7. import org.hibernate.SessionFactory;  
  8.   
  9. import com.test.bean.User;  
  10. import com.test.dao.UserDao;  
  11.   
  12. public class UserDaoImpl implements UserDao {  
  13.       
  14.     private SessionFactory sessionFactory;  
  15.       
  16.     @Override  
  17.     public User find(String name, String password) {  
  18.         Session session = sessionFactory.openSession();  
  19.         String hql = "FROM User AS u WHERE u.name = :name AND u.password = :password";  
  20.         Query q = session.createQuery(hql);  
  21.         q.setString("name", name);  
  22.         q.setString("password", password);        
  23.         List<User> list = q.list();  
  24.         session.close();  
  25.         if (list.size()==0)  
  26.             return null;  
  27.         else  
  28.             return list.get(0);  
  29.     }  
  30.   
  31.     public SessionFactory getSessionFactory() {  
  32.         return sessionFactory;  
  33.     }  
  34.   
  35.     public void setSessionFactory(SessionFactory sessionFactory) {  
  36.         this.sessionFactory = sessionFactory;  
  37.     }  
  38.   
  39.   
  40.     public User find(User user) {  
  41.         return find(user.getName(),user.getPassword());  
  42.     }  
  43.   
  44. }  

注意上面的sessionFactory是由Spring来负责注入和管理的,因此一定要有一个set的方法来加载sessionFactory对象。

6, 编写业务接口和实现类
UserService接口

  1. package com.test.service;  
  2.   
  3. import com.test.bean.User;  
  4.   
  5. public interface UserService {  
  6.   
  7.     public boolean isLogin(User user);  
  8.     public boolean isLogin(String name, String password);  
  9. }  

UserService实现类

  1. package com.test.serviceImpl;  
  2.   
  3. import com.test.bean.User;  
  4. import com.test.dao.UserDao;  
  5. import com.test.service.UserService;  
  6.   
  7. public class UserServiceImpl implements UserService {  
  8.     private UserDao userDao;  
  9.       
  10.     public boolean isLogin(User user) {  
  11.         return isLogin(user.getName(),user.getPassword());  
  12.     }  
  13.   
  14.     public UserDao getUserDao() {  
  15.         return userDao;  
  16.     }  
  17.   
  18.     public void setUserDao(UserDao userDao) {  
  19.         this.userDao = userDao;  
  20.     }  
  21.   
  22.     @Override  
  23.     public boolean isLogin(String name, String password) {  
  24.         boolean isLogin = false;  
  25.         try  
  26.             {  
  27.             User u = userDao.find(name, password);  
  28.             if (u != null)  
  29.                 {  
  30.                 isLogin = true;  
  31.                 }  
  32.             }  
  33.         catch (Exception e)  
  34.             {  
  35.             System.out.println("isLogin error\n" + e.getMessage());  
  36.             }  
  37.         return isLogin;  
  38.     }  
  39.   
  40. }  


6. 在applicatonContext.xml中配置bean

  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" xmlns:context="http://www.springframework.org/schema/context"  
  4. xmlns:aop="http://www.springframework.org/schema/aop"  
  5. xmlns:tx="http://www.springframework.org/schema/tx"  
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  8.            http://www.springframework.org/schema/aop   
  9.            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  10.            http://www.springframework.org/schema/context  
  11.            http://www.springframework.org/schema/context/spring-context-2.5.xsd    
  12.            http://www.springframework.org/schema/tx   
  13.            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  14.   
  15.     <!-- Hibernate configuration -->  
  16.     <import resource="classpath:database.xml"/>  
  17.       
  18.     <!-- struts beans -->  
  19.     <bean id="LoginAction" class="com.test.action.LoginAction" scope="prototype">  
  20.         <property name="userService" ref="userService" />  
  21.     </bean>  
  22.       
  23.     <bean id="userDao" class="com.test.daoImpl.UserDaoImpl">  
  24.         <property name="sessionFactory" ref="sessionFactory"></property>  
  25.     </bean>  
  26.       
  27.     <bean id="userService" class="com.test.serviceImpl.UserServiceImpl">  
  28.         <property name="userDao" ref="userDao"></property>  
  29.     </bean>  
  30.   
  31. </beans>  


7. 增加jsp页面

  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <%@ taglib uri="/struts-tags" prefix="s" %>  
  3.       
  4. <%  
  5. String path = request.getContextPath();  
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  7. %>  
  8. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  9. <html>  
  10. <head>  
  11.     <base href="<%=basePath%>">  
  12.     <title><s:text name="home.title" /></title>  
  13.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="easyTalk">  
  18.     <meta http-equiv="description" content="This is my page">  
  19. </head>  
  20. <body>  
  21.     <s:form name="loginFrm" action="login">  
  22.         <s:textfield name="username" key="username"></s:textfield>  
  23.         <s:textfield name="password" key="password"></s:textfield>  
  24.         <s:submit label="submit"></s:submit>  
  25.     </s:form>  
  26.     <s:actionerror/>  
  27. </body>  
  28. </html>  


8. 配置struts.xml, 注意这里有两个改动,a. 增加了一个常量,声明objectFactory由Spring接管. b. action 的class属性中,维护的是Spring的bean对象,而不是具体的class.

  1. <?xml version="1.0" encoding="UTF-8" ?>   
  2. <!DOCTYPE struts PUBLIC   
  3.      "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"   
  4.      "http://struts.apache.org/dtds/struts-2.0.dtd">   
  5. <struts>   
  6.     <constant name="struts.custom.i18n.resources" value="message"></constant>  
  7.     <constant name="struts.objectFactory" value="spring"></constant>  
  8.     <constant name="struts.devMode" value="true" />  
  9.       
  10.     <package name="struts2" extends="struts-default">  
  11.         <action name="login" class="LoginAction">  
  12.             <result name="success" >loginresult.jsp</result>  
  13.             <result name="input">login.jsp</result>  
  14.             <result name="error">login.jsp</result>  
  15.         </action>  
  16.     </package>  
  17.       
  18. </struts>  


9. 增加action类,接受客户端的响应

  1. package com.test.action;  
  2.   
  3. import com.opensymphony.xwork2.ActionContext;  
  4. import com.opensymphony.xwork2.ActionSupport;  
  5. import com.test.service.UserService;  
  6.   
  7. public class LoginAction extends ActionSupport {  
  8.   
  9.         public String username;  
  10.         public String password;  
  11.         private UserService userService;  
  12.           
  13.         public LoginAction()  
  14.         {  
  15.             System.out.println("initialize LoginAction......");  
  16.         }  
  17.         public void setUserService(UserService userService)  
  18.         {  
  19.             this.userService = userService;  
  20.         }  
  21.           
  22.         public String execute()  
  23.         {  
  24.             if (true == this.userService.isLogin(username, password))  
  25.             {  
  26.                 ActionContext.getContext().getSession().put("username", username);  
  27.                 return SUCCESS;  
  28.             }else{  
  29.                 super.addActionError(super.getText("loginfailed"));  
  30.                 return ERROR;  
  31.             }  
  32.         }  
  33.           
  34.         public void validate()  
  35.         {  
  36.             if ((null == username) || (0==username.length()))  
  37.             {  
  38.                 super.addActionError(super.getText("warning.empty",new String[] {getText("username")}));  
  39.             }  
  40.               
  41.             if ((null == password) || (0 == password.length()))  
  42.             {  
  43.                 super.addActionError(super.getText("warning.empty",new String[] {getText("password")}));  
  44.                   
  45.             }  
  46.         }  
  47. }  

10. 在applicationContext.xml中增加action的bean,请参考上面的xml文件,这里略过。
11. 最后整个代码的架构如下:



12. 测试登录功能
Login 页面:

登录成功:

系统日志:


测试通过............................................................

12. 总结:

  • 初期阶段不要过分追求jar包的最小配置,否则会出现很多意料之外的错误.
  • Jar包的版本要小心,最后我无奈将Hibernate从4.0降回3.6.8, 因为差异太大.
  • spring中bean的配置要小心,注入的时候是实现类,不是接口,名字也要注意,property name是引用对象的名字,而不是类的名字,这里我就吃了一次亏,login的时候怎么都说LoginAction对象找不到,其实是配置文件写得有问题,结果Spring无法生成bean实例,这个错误很像Struts无法调用Spring的容器...但是其实是Spring容器无法生成Bean对象。


源代码已上传,请点击此处下载

 

 不相关链接:http://gravehistory-daipeng.rhcloud.com/

分享到:
评论

相关推荐

    s2sh整合实例 Struts2.0 Spring2.6 Hibernate3.2

    s2sh整合实例 Struts2.0 Spring2.6 Hibernate3.2 转载于iteye

    用Maven整合SpringMVC+Spring+Hibernate 案例

    该资源是我参照别人的博客来搭建的环境,myeclipse 10.6+maven3+srping+srpingmvc+hibernate4.1+mysql5.5,博客地址:http://blog.csdn.net/liu1220356497/article/details/47701565,该博客是我转载原来的博客主的,...

    Spring2.5.3+Struts2.0.11.1+Hibernate3.2.6整合备忘 (转载)

    Spring2.5.3+Struts2.0.11.1+Hibernate3.2.6整合备忘 (转载)

    虚拟数据层 Struts2、Hibernate、Spring整合的泛型DAO Version 2010.9.27

    Struts2、Hibernate、Spring整合的泛型DAO (本人评价: 代码开发效率提高30% 代码出错率减少70%) 对于大多数开发人员,系统中的每个 DAO 编写几乎相同的代码到目前为止已经成为一种习惯。虽然所有人都将这种重复...

    Spring-activiti:转载测试通过--被人的SSM和ACTIVITI整合框架

    项目技术架构(Spring+SpringMVC+Mybatis)MavenSpring(IOC DI AOP 声明式事务处理)SpringMVC(支持Restful风格)Hibernate Validator(参数校验)Mybatis(最少配置方案)shiro权限控制,结合ajax实现了异步认证与...

    springmybatis

    其实还有更简单的方法,而且是更好的方法,使用合理描述参数和SQL语句返回值的接口(比如IUserOperation.class),这样现在就可以至此那个更简单,更安全的代码,没有容易发生的字符串文字和转换的错误.下面是详细...

    后台管理系统

    adminstore整合了spring,hibernate,shiro,discover等框架。不用担心每次那样麻烦的拷贝了。后台管理系统集成模板修改,菜单管理,用户管理,角色管理,友情链接,插件管理管理等功能。站在巨人的肩膀上,让我们看得...

    SSH2完美整合流程

    本教程做简单的账号注册演示,所用工具:Myeclipse-6.5、Struts-2.2.3、Hibernate-3.2、Spring-2.0、MySql,本教程出自北大青鸟成都锦江校区(原文链接http://www.scbdqn.com/course/netjava/3172.html),转载请...

    SSH系统初级入门代码

    本系统采用目前java爱好者业界领先的struts hibernate spring 三套框架整合开发的程序,界面层采用ajax技术实实现,目前有公司已经交付给客户正常使用维护中,请社友下载后勿转载,只可用于研究,商业用途请绕行。...

    泛型dao 泛型dao 泛型dao

    Struts2、Hibernate、Spring整合的泛型DAO (本人评价: 代码开发效率提高30% 代码出错率减少70%) 对于大多数开发人员,系统中的每个 DAO 编写几乎相同的代码到目前为止已经成为一种习惯。虽然所有人都将这种重复...

Global site tag (gtag.js) - Google Analytics