ITeye博客

转载:Spring和Hibernate的整合

tpglzu2015 · 2015-04-27 17:39 · SSH搭建 · 企业架构 · Markdown

转载自: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的启动项

[html] view plaincopyprint?

 

  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. <!-- Spring configuration -->
  9. <context-param>
  10. <param-name>contextConfigLocation</param-name>
  11. <param-value>classpath:applicationContext*.xml</param-value>
  12. </context-param>
  13. <listener>
  14. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  15. </listener>
  16. <!-- Struts2 configuration -->
  17. <filter>
  18. <filter-name>struts2</filter-name>
  19. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  20. </filter>
  21. <filter-mapping>
  22. <filter-name>struts2</filter-name>
  23. <url-pattern>/*</url-pattern>
  24. </filter-mapping>
  25. </web-app>

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

 

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

applicationContext.xml

[html] view plaincopyprint?

 

  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. <!-- Hibernate configuration -->
  15. <import resource="classpath:database.xml"/>
  16. </beans>

database.xml

[html] view plaincopyprint?

 

  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. <bean id="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  15. <property name="location">
  16. <value>classpath:dataSource.properties</value>
  17. </property>
  18. </bean>
  19. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  20. <property name="driverClassName" value="${dataSource.driverClassName}" />
  21. <property name="url" value="${dataSource.url}" />
  22. <property name="username" value="${dataSource.username}" />
  23. <property name="password" value="${dataSource.password}" />
  24. </bean>
  25. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  26. <property name="dataSource" ref="dataSource" />
  27. <property name="hibernateProperties">
  28. <props>
  29. <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
  30. <prop key="hibernate.show_sql">true</prop>
  31. </props>
  32. </property>
  33. <property name="mappingResources">
  34. <list>
  35. <value>com/test/bean/User.hbm.xml</value>
  36. </list>
  37. </property>
  38. </bean>
  39. </beans>

dataSource.properties

[html] view plaincopyprint?

 

  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对应的映射文件.

[java] view plaincopyprint?

 

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

User.hbm.xml

[java] view plaincopyprint?

 

  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实现

[java] view plaincopyprint?

 

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

 

[java] view plaincopyprint?

 

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

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

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

[java] view plaincopyprint?

 

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

UserService实现类

[java] view plaincopyprint?

 

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

6. 在applicatonContext.xml中配置bean

[html] view plaincopyprint?

 

  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. <!-- Hibernate configuration -->
  15. <import resource="classpath:database.xml"/>
  16. <!-- struts beans -->
  17. <bean id="LoginAction" class="com.test.action.LoginAction" scope="prototype">
  18. <property name="userService" ref="userService" />
  19. </bean>
  20. <bean id="userDao" class="com.test.daoImpl.UserDaoImpl">
  21. <property name="sessionFactory" ref="sessionFactory"></property>
  22. </bean>
  23. <bean id="userService" class="com.test.serviceImpl.UserServiceImpl">
  24. <property name="userDao" ref="userDao"></property>
  25. </bean>
  26. </beans>

7. 增加jsp页面

[html] view plaincopyprint?

 

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

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

[html] view plaincopyprint?

 

  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. <package name="struts2" extends="struts-default">
  10. <action name="login" class="LoginAction">
  11. <result name="success" >loginresult.jsp</result>
  12. <result name="input">login.jsp</result>
  13. <result name="error">login.jsp</result>
  14. </action>
  15. </package>
  16. </struts>

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

[java] view plaincopyprint?

 

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

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/

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。