尚硅谷 ssh 框架整合

一、 加入 Spring
1、 加入 jar 包(这个就不废话了)

2、配置 web.xml 文件

主要是配置ContextLoaderListener(快捷键art+/有提示,以免菜鸟手工出错)

<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>


<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

3、 加入 Spring 的配置文件. 

applicationContext.xml(暂时空着)

二、加入 Hibernate
1、 同时建立持久化类, 和其对应的 .hbm.xml 文件, 生成对应的数据表

Department.java

 
  1. package com.tian.ssh.entity;

  2.  
  3. public class Department {

  4.  
  5. private Integer id;

  6. private String departmentName;

  7. public Integer getId() {

  8. return id;

  9. }

  10. public void setId(Integer id) {

  11. this.id = id;

  12. }

  13. public String getDepartmentName() {

  14. return departmentName;

  15. }

  16. public void setDepartmentName(String departmentName) {

  17. this.departmentName = departmentName;

  18. }

  19.  
  20.  
  21. }


Employee.java

 
  1. package com.tian.ssh.entity;

  2.  
  3. import java.util.Date;

  4.  
  5. public class Employee {

  6.  
  7. private Integer id;

  8. private String lastName;

  9. private String email;

  10. private Date birth;

  11. private Date createTime;

  12. private Department department;

  13. public Integer getId() {

  14. return id;

  15. }

  16. public void setId(Integer id) {

  17. this.id = id;

  18. }

  19. public String getLastName() {

  20. return lastName;

  21. }

  22. public void setLastName(String lastName) {

  23. this.lastName = lastName;

  24. }

  25. public String getEmail() {

  26. return email;

  27. }

  28. public void setEmail(String email) {

  29. this.email = email;

  30. }

  31. public Date getBirth() {

  32. return birth;

  33. }

  34. public void setBirth(Date birth) {

  35. this.birth = birth;

  36. }

  37. public Date getCreateTime() {

  38. return createTime;

  39. }

  40. public void setCreateTime(Date createTime) {

  41. this.createTime = createTime;

  42. }

  43. public Department getDepartment() {

  44. return department;

  45. }

  46. public void setDepartment(Department department) {

  47. this.department = department;

  48. }

  49.  
  50.  
  51. }

Department.hbm.xml

 
  1. <?xml version="1.0"?>

  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  4. <!-- Generated 2015-8-15 11:45:30 by Hibernate Tools 3.4.0.CR1 -->

  5. <hibernate-mapping>

  6. <class name="com.tian.ssh.entity.Department" table="SSH_DEPARTMENT">

  7. <id name="id" type="java.lang.Integer">

  8. <column name="ID" />

  9. <generator class="native" />

  10. </id>

  11. <property name="departmentName" type="java.lang.String">

  12. <column name="DEPARTMENT_NAME" />

  13. </property>

  14. </class>

  15. </hibernate-mapping>


Employee.hbm.xml

 
  1. <?xml version="1.0"?>

  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  4. <!-- Generated 2015-8-15 11:45:30 by Hibernate Tools 3.4.0.CR1 -->

  5. <hibernate-mapping>

  6. <class name="com.tian.ssh.entity.Employee" table="SSH_EMPLOYEE">

  7. <id name="id" type="java.lang.Integer">

  8. <column name="ID" />

  9. <generator class="native" />

  10. </id>

  11. <property name="lastName" type="java.lang.String">

  12. <column name="LAST_NAME" />

  13. </property>

  14. <property name="email" type="java.lang.String">

  15. <column name="EMAIL" />

  16. </property>

  17. <property name="birth" type="java.util.Date">

  18. <column name="BIRTH" />

  19. </property>

  20. <property name="createTime" type="java.util.Date">

  21. <column name="CREATE_TIME" />

  22. </property>

  23. <many-to-one name="department" class="com.tian.ssh.entity.Department" >

  24. <column name="DEPARTMENT_ID" />

  25. </many-to-one>

  26. </class>

  27. </hibernate-mapping>


 

2、 Spring 整合 Hibernate
3、步骤:
①. 加入 jar 包(把解压后的lib/requied加入,lib/optional/c3p0中的c3p0-0.9.2.1.jar,mchange-commons-java-0.2.3.4.jar加入)
②. 在类路径下加入 hibernate.cfg.xml 文件, 在其中配置 hibernate 的基本属性

 
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <!DOCTYPE hibernate-configuration PUBLIC

  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

  5. <hibernate-configuration>

  6. <session-factory>

  7. <!-- 配置hibernate的基本属性 -->

  8.  
  9. <!-- 方言 -->

  10. <property name="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>

  11.  
  12. <!-- 是否显示及格式化sql语句 -->

  13. <property name="hibernate.show_sql">true</property>

  14. <property name="hibernate.format_sql">true</property>

  15.  
  16. <!-- 生成数据表的策略 -->

  17. <property name="hibernate.hbm2ddl.auto">update</property>

  18.  
  19. <!-- 二级缓存 -->

  20.  
  21. <!-- ======================================================= -->

  22. <property name="hibernate.current_session_context_class">thread</property>

  23.  
  24. </session-factory>

  25. </hibernate-configuration>

注意:各个版本方言版本可能不一样,crtl +alt+T快捷键查下
<property name="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>

③. 建立持久化类, 和其对应的 .hbm.xml 文件

如上面所示,已建好。
④. 和 Spring 进行整合
i.  加入 c3p0 和 MySQL 的驱动
ii. 在 Spring 的配置文件中配置: 数据源, SessionFactory, 声明式事务

我就把整合好后的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"

  4. xmlns:aop="http://www.springframework.org/schema/aop"

  5. xmlns:context="http://www.springframework.org/schema/context"

  6. xmlns:tx="http://www.springframework.org/schema/tx"

  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

  8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd

  9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd

  10. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

  11.  
  12. <!-- 导入资源文件 -->

  13. <context:property-placeholder location="classpath:db.properties"/>

  14.  
  15. <!-- 配置C3P0数据源 -->

  16. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

  17. <property name="user" value="${jdbc.user}"></property>

  18. <property name="password" value="${jdbc.password}"></property>

  19. <property name="driverClass" value="${jdbc.driverClass}"></property>

  20. <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>

  21. <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>

  22. <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>

  23. </bean>

  24.  
  25. <!-- 配置sessionFactory -->

  26. <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

  27. <property name="dataSource" ref="dataSource"></property>

  28. <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>

  29. <property name="mappingLocations" value="classpath:com/tian/ssh/entity/*.hbm.xml"></property>

  30. </bean>

  31.  
  32. <!-- ========================================================================================== -->

  33.  
  34.  
  35.  
  36. </beans>

db.properties文件如下:

 
  1. jdbc.user=root

  2. jdbc.password=123

  3. jdbc.driverClass=com.mysql.jdbc.Driver

  4. jdbc.jdbcUrl=jdbc:mysql:///ssh2

  5.  
  6. jdbc.initPoolSize=5

  7. jdbc.maxPoolSize=10


 

⑤. 启动项目, 会看到生成对应的数据表(在数据库hibernate会自动帮我们生成)



三、加入 Struts2
1、 加入 jar 包: 若有重复的 jar 包, 则需要删除版本较低的. javassist-3.11.0.GA.jar(这个选择app里面的blank,不需要lib下的)
2、在 web.xml 文件中配置 Struts2 的 Filter

 
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  3. xmlns="http://xmlns.jcp.org/xml/ns/javaee"

  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

  5. id="WebApp_ID" version="3.1">

  6.  
  7. <!-- needed for ContextLoaderListener -->

  8. <context-param>

  9. <param-name>contextConfigLocation</param-name>

  10. <param-value>classpath:applicationContext*.xml</param-value>

  11. </context-param>

  12.  
  13. <!-- Bootstraps the root web application context before servlet initialization -->

  14. <listener>

  15. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  16. </listener>

  17.  
  18. <!-- struts2 filter的配置 -->

  19. <filter>

  20. <filter-name>struts2</filter-name>

  21. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

  22. </filter>

  23.  
  24. <filter-mapping>

  25. <filter-name>struts2</filter-name>

  26. <url-pattern>/*</url-pattern>

  27. </filter-mapping>

  28.  
  29.  
  30. <filter>

  31. <filter-name>SpringOpenSessionInViewFilter</filter-name>

  32. <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>

  33. </filter>

  34. <filter-mapping>

  35. <filter-name>SpringOpenSessionInViewFilter</filter-name>

  36. <url-pattern>/*</url-pattern>

  37. </filter-mapping>

  38.  
  39. </web-app>

3、 加入 Struts2 的配置文件Struts.xml

 
  1. <?xml version="1.0" encoding="UTF-8" ?>

  2. <!DOCTYPE struts PUBLIC

  3. "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

  4. "http://struts.apache.org/dtds/struts-2.3.dtd">

  5.  
  6. <struts>

  7.  
  8. <constant name="struts.enable.DynamicMethodInvocation" value="false" />

  9. <constant name="struts.devMode" value="true" />

  10.  
  11. <package name="default" namespace="/" extends="struts-default">

  12. <action name="emp-*" class="employeeAction"

  13. method="{1}">

  14. <result name="list">/WEB-INF/views/emp-list.jsp</result>

  15. </action>

  16.  
  17.  
  18. </package>

  19.  
  20.  
  21. </struts>

4、 整合 Spring
①. 加入 Struts2 的 Spring 插件的 jar 包(在lib下)

②. 在 Spring 的配置文件中正常配置 Action, 注意 Action 的 scope 为 prototype

③. 在 Struts2 的配置文件中配置 Action 时, class 属性指向该 Action 在 IOC 中的 id

struts的bean文件:applicationContext-beans.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"

  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  5.  
  6. <bean id="employeeDao" class="com.tian.ssh.dao.EmployeeDao">

  7. <property name="sessionFactory" ref="sessionFactory"></property>

  8. </bean>

  9.  
  10. <bean id="employeeService" class="com.tian.ssh.service.EmployeeService">

  11. <property name="employeeDao" ref="employeeDao"></property>

  12. </bean>

  13.  
  14. <bean id="employeeAction" class="com.tian.ssh.actions.EmployeeAction"

  15. scope="prototype">

  16. <property name="employeeService" ref="employeeService"></property>

  17. </bean>

  18.  
  19. </beans>

四、补充。

如走来结构图所示的,其他几个类和页面的显示:

EmployeeAction.java

 
  1. package com.tian.ssh.actions;

  2.  
  3. import java.util.Map;

  4.  
  5. import org.apache.struts2.interceptor.RequestAware;

  6.  
  7. import com.opensymphony.xwork2.ActionSupport;

  8. import com.tian.ssh.service.EmployeeService;

  9.  
  10. public class EmployeeAction extends ActionSupport implements RequestAware {

  11.  
  12. private EmployeeService employeeService;

  13.  
  14. public void setEmployeeService(EmployeeService employeeService) {

  15. this.employeeService = employeeService;

  16. }

  17.  
  18.  
  19. public String list(){

  20. request.put("employees", employeeService.getAll());

  21. return "list";

  22. }

  23.  
  24.  
  25. private Map<String, Object> request;

  26. @Override

  27. public void setRequest(Map<String, Object> arg0) {

  28. // TODO Auto-generated method stub

  29. this.request = arg0;

  30. }

  31. }

EmployeeDao.java

 
  1. package com.tian.ssh.dao;

  2.  
  3. import java.util.List;

  4.  
  5. import org.hibernate.Session;

  6. import org.hibernate.SessionFactory;

  7. import org.hibernate.Transaction;

  8.  
  9. import com.tian.ssh.entity.Employee;

  10.  
  11. public class EmployeeDao {

  12.  
  13. private SessionFactory sessionFactory;

  14.  
  15. public void setSessionFactory(SessionFactory sessionFactory) {

  16. this.sessionFactory = sessionFactory;

  17. }

  18.  
  19. public Session getSession() {

  20. return this.sessionFactory.getCurrentSession();

  21. }

  22.  
  23. public List<Employee> getAll() {

  24.  
  25. String hql = "FROM Employee e LEFT OUTER JOIN FETCH e.department";

  26.  
  27. List<Employee> list1 = null;

  28.  
  29. try {

  30. Transaction transaction = null;

  31. transaction = getSession().beginTransaction();

  32. list1 = getSession().createQuery(hql).list();

  33.  
  34. } catch (Exception e) {

  35. // TODO: handle exception

  36. e.printStackTrace();

  37. }

  38.  
  39. return list1;

  40. }

  41.  
  42. }


EmployeeService.java

 
  1. package com.tian.ssh.service;

  2.  
  3. import java.util.List;

  4.  
  5. import com.tian.ssh.dao.EmployeeDao;

  6. import com.tian.ssh.entity.Employee;

  7.  
  8. public class EmployeeService {

  9.  
  10. private EmployeeDao employeeDao;

  11.  
  12. public void setEmployeeDao(EmployeeDao employeeDao) {

  13. this.employeeDao = employeeDao;

  14. }

  15.  
  16. public List<Employee> getAll(){

  17. return employeeDao.getAll();

  18. }

  19.  
  20. }



emp-list.jsp

 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"

  2. pageEncoding="UTF-8"%>

  3. <%@ taglib uri="/struts-tags" prefix="s"%>

  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  5. <html>

  6. <head>

  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  8. <title>Insert title here</title>

  9. </head>

  10. <body>

  11.  
  12. <h4>Employee list page</h4>

  13.  
  14. <s:if test="#request.employees == null || #request.employees.size() == 0">

  15. 没有任何员工信息!

  16. </s:if>

  17. <s:else>

  18. <table border="1" cellpadding="10" cellspacing="0">

  19. <tr>

  20. <td>ID</td>

  21. <td>LASTNAME</td>

  22. <td>EMAIL</td>

  23. <td>BIRTH</td>

  24. <td>CREATETIME</td>

  25. <td>DEPARTMENT</td>

  26. </tr>

  27. <s:iterator value="#request.employees">

  28. <tr>

  29. <td>${id }</td>

  30. <td>${lastName }</td>

  31. <td>${email }</td>

  32. <td>${birth }</td>

  33. <td>${createTime }</td>

  34. <td>${department.departmentName }</td>

  35. </tr>

  36. </s:iterator>

  37. </table>

  38. </s:else>

  39. </body>

  40. </html>



index.jsp

 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"

  2. pageEncoding="UTF-8"%>

  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  4. <html>

  5. <head>

  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  7. <title>Insert title here</title>

  8. </head>

  9. <body>

  10.  
  11. <a href="emp-list"></a>

  12. </body>

  13. </html>


 

最最后,要补充的是,这个东西折磨我很久了,会一直提示“Could not obtain transaction-synchronized Session for current thread“在hibernate.cfg.xml中添加

<property name="hibernate.current_session_context_class">thread</property>,这样你以为好了吗结果又提示你:

“createQuery is not valid without active transaction”,好这是你一改知道了,是没有激活事务,在你的基础数据操作功能中加上这:

Transaction transaction = null;
transaction = getSession().beginTransaction();

本例子中就是在EmployeeDao.java的getAll()方法中添加即可。

最后我们来看下我耗时很长调处来的结果:

猜你喜欢

转载自blog.csdn.net/lailai186/article/details/81184100
今日推荐