SSH架构的原始配置
准备工作:新建一个纯的JavaWeb项目(命名为ssh)
(1)新建resources资源目录,新建webapp目录(webapp下新建lib目录,classes目录,以及web.xml文件)
(2)对项目ssh做buildpath,选择classes为字节码文件存放目录
(3)resources资源目录下复制db.properties文件和applicationContext.xml文件
1 #key-value 2 jdbc.driverClassName=com.mysql.jdbc.Driver 3 jdbc.url=jdbc:mysql://localhost:3306/springDemo 4 jdbc.username=root 5 jdbc.password=admin 6 jdbc.maxActive=5
第一部分:Spring与Hibernate集成:
1.导入相关jar包
(1)导入Hibernate相关的jar包:如下图所示,出去红色方框外的都为hibernate-release-4.3.5.Finallib equired下的所有包
(2)导入spring相关jar包:包括libs中的包和依赖包
(3)导入mysql驱动包和阿里巴巴的数据库连接池包druid包
(4)以及其他工具包如lombok(之前在eclipse中配置过的话,直接添加user librart)、juit等
2.准备实体类和映射文件(映射文件模板去搜user.hbm.xml)
3.准备DAO接口及其实现类 、测试类
1 package com.wanglei.ssh.domain; 2 3 import lombok.Getter; 4 import lombok.Setter; 5 6 @Setter@Getter 7 public class Employee { 8 private Long id; 9 private String name; 10 private Integer age; 11 private Department dept; 12 }
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 6 <!-- 7 8 --> 9 10 <hibernate-mapping package="com.wanglei.ssh.domain"> 11 <class name="Employee" table="employee"> 12 <id name="id"> 13 <generator class="native"></generator> 14 </id> 15 <property name="name"></property> 16 <property name="age"></property> 17 </class> 18 </hibernate-mapping>
1 package com.wanglei.ssh.dao; 2 3 import java.util.List; 4 5 import com.wanglei.ssh.domain.Employee; 6 7 public interface IEmployeeDAO { 8 void save(Employee e); 9 void update(Employee e); 10 void delete(Employee e); 11 Employee get(Long id); 12 List<Employee> listAll(); 13 14 }
1 package com.wanglei.ssh.dao.impl; 2 3 import java.util.List; 4 5 import org.hibernate.Session; 6 import org.hibernate.SessionFactory; 7 8 import com.wanglei.ssh.dao.IEmployeeDAO; 9 import com.wanglei.ssh.domain.Employee; 10 11 public class EmployeeDAOImpl implements IEmployeeDAO { 12 13 private SessionFactory sessionFactory; 14 //注入属性:sessionFactory 15 public void setSessionFactory(SessionFactory sessionFactory){ 16 this.sessionFactory = sessionFactory; 17 } 18 @Override 19 public void save(Employee e) { 20 Session session = sessionFactory.getCurrentSession();//此方法需要配置事务管理器 21 session.save(e); 22 } 23 @Override 24 public void update(Employee e) { 25 Session session = sessionFactory.getCurrentSession();//此方法需要配置事务管理器 26 session.update(e); 27 } 28 @Override 29 public void delete(Employee e) { 30 Session session = sessionFactory.getCurrentSession();//此方法需要配置事务管理器 31 session.delete(e); 32 } 33 @Override 34 public Employee get(Long id) { 35 Session session = sessionFactory.getCurrentSession();//此方法需要配置事务管理器 36 return (Employee) session.get(Employee.class, id); 37 } 38 @Override 39 public List<Employee> listAll() { 40 Session session = sessionFactory.getCurrentSession();//此方法需要配置事务管理器 41 return session.createCriteria(Employee.class).list();//没有查询条件时,用此方法更简单 42 //return session.createQuery("SELECT e FROM Employee e").list(); 43 } 44 }
4.开始正式整合spring和hibernate
(1)新建applicationContext.xml文件 配置连接池(使用属性占位符)
(2)配置SessionFactory(此处的session和HttpSession完全不一样,前者是hibernate操作数据库的对象,后者是指HTTP会话中的session)
其中:a.配置dataSource属性,把连接池关联起来
b.配置hibernateProperties属性,即hibernate的属性配置,(方言,是否打印sql,格式化sql等)
c.配置映射文件的位置,mappingLocations属性
d.配置DAO
(3)编写Service接口及其实现类
1 package com.wanglei.ssh.service; 2 3 import java.util.List; 4 5 import com.wanglei.ssh.domain.Employee; 6 7 public interface IEmployeeService { 8 void save(Employee e); 9 void update(Employee e); 10 void delete(Employee e); 11 Employee get(Long id); 12 List<Employee> listAll(); 13 14 }
1 package com.wanglei.ssh.service.impl; 2 3 import java.util.List; 4 5 import lombok.Setter; 6 7 import com.wanglei.ssh.dao.IEmployeeDAO; 8 import com.wanglei.ssh.domain.Employee; 9 import com.wanglei.ssh.service.IEmployeeService; 10 11 public class EmployeeServiceImpl implements IEmployeeService{ 12 @Setter 13 private IEmployeeDAO employeeDAO; 14 15 @Override 16 public void save(Employee e) { 17 employeeDAO.save(e); 18 //throw new RuntimeException("故意加的,测试事务"); 19 } 20 21 @Override 22 public void update(Employee e) { 23 employeeDAO.update(e); 24 } 25 26 @Override 27 public void delete(Employee e) { 28 employeeDAO.delete(e); 29 } 30 31 @Override 32 public Employee get(Long id) { 33 return employeeDAO.get(id); 34 } 35 36 @Override 37 public List<Employee> listAll() { 38 return employeeDAO.listAll(); 39 } 40 41 }
(4)继续完成applicationContext.xml文件
e.配置事务管理器
f.配置Service
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:p="http://www.springframework.org/schema/p" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xmlns:tx="http://www.springframework.org/schema/tx" 8 xsi:schemaLocation=" 9 http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx.xsd 15 http://www.springframework.org/schema/context 16 http://www.springframework.org/schema/context/spring-context.xsd"> 17 <!-- 属性占位符 --> 18 <context:property-placeholder location="classpath:db.properties"/> 19 <!-- 配置连接池 --> 20 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 21 <property name="driverClassName" value="${jdbc.driverClassName}" /> 22 <property name="url" value="${jdbc.url}" ></property> 23 <property name="username" value="${jdbc.username}" ></property> 24 <property name="password" value="${jdbc.password}" /> 25 </bean> 26 <!-- 配置SessionFactory --> 27 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 28 <!-- 管理连接池 --> 29 <property name="dataSource" ref="dataSource"></property> 30 <!-- hibernate属性配置 --> 31 <property name="hibernateProperties"> 32 <value> 33 hibernate.dialect = org.hibernate.dialect.MySQLDialect 34 hibernate.show_sql = true 35 hibernate.hbm2ddl.auto = update 36 </value> 37 </property> 38 <!-- 映射文件的位置 --> 39 <property name="mappingLocations" value="classpath:com/wanglei/ssh/domain/*.hbm.xml"></property> 40 </bean> 41 <!--what 配置事务管理器 --> 42 <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 43 <property name="sessionFactory" ref="sessionFactory"></property> 44 </bean> 45 <!--when 通用的crud增强 --> 46 <tx:advice id="cruidAdvice" transaction-manager="txManager"> 47 <tx:attributes> 48 <tx:method name="get*" read-only="true"/> 49 <tx:method name="list*" read-only="true"/> 50 <tx:method name="query*" read-only="true"/> 51 <tx:method name="*" propagation="REQUIRED"/> 52 </tx:attributes> 53 </tx:advice> 54 <!--where 切入点语法 --> 55 <aop:config> 56 <aop:pointcut expression="execution(* com.wanglei.ssh.service.*Service.*(..))" id="crudPoint"/> 57 <aop:advisor advice-ref="cruidAdvice" pointcut-ref="crudPoint"/> 58 </aop:config> 59 60 <!-- 配置DAO --> 61 <bean id="employeeDAO" class="com.wanglei.ssh.dao.impl.EmployeeDAOImpl"> 62 <property name="sessionFactory" ref="sessionFactory"></property> 63 </bean> 64 <!-- 配置Service --> 65 <bean id="employeeService" class="com.wanglei.ssh.service.impl.EmployeeServiceImpl"> 66 <property name="employeeDAO" ref="employeeDAO"></property> 67 </bean> 68 </beans> 69
(5)编写一个测试类
1 package com.wanglei.ssh.test; 2 3 import java.util.List; 4 import java.util.Map; 5 6 import org.junit.Test; 7 import org.junit.runner.RunWith; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.test.context.ContextConfiguration; 10 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 11 12 import com.wanglei.ssh.domain.Employee; 13 import com.wanglei.ssh.service.IEmployeeService; 14 15 @RunWith(SpringJUnit4ClassRunner.class) 16 @ContextConfiguration("classpath:applicationContext.xml") 17 public class EmployeeServiceTest { 18 19 @Autowired 20 private IEmployeeService service; 21 22 @Test 23 public void testSave() { 24 Employee emp = new Employee(); 25 emp.setName("小明"); 26 emp.setAge(21); 27 service.save(emp); 28 } 29 30 @Test 31 public void testUpdate() { 32 Employee emp = new Employee(); 33 emp.setName("小莉"); 34 emp.setAge(17); 35 emp.setId(3L); 36 service.update(emp); 37 } 38 39 @Test 40 public void testDelete() { 41 Employee emp = new Employee(); 42 emp.setId(3L); 43 service.delete(emp); 44 } 45 46 @Test 47 public void testGet() { 48 Employee emp = new Employee(); 49 emp.setId(1L); 50 Employee result = service.get(1L); 51 System.out.println(result); 52 } 53 54 @Test 55 public void testListAll() { 56 List<Employee> es = service.listAll(); 57 for (Employee e : es) { 58 System.out.println(e); 59 } 60 } 61 62 }
第二部分:Spring与Struts2集成:
准备工作,集成Struts2:
拷贝jar包
导入struts-2.3.24appsstruts2-blankWEB-INFlib下的所有jar包
导入struts-2.3.24lib下名为struts2-spring-plugin-2.3.24的jar包、
导入开发web的Servlet-api.jar
并作buildpath。
注意:其中appsstruts2-blankWEB-INFlib下的javassist-3.11.0.GA.jar与Hibernate中的重复,所以去掉这个jar包。
2.配置前端控制器(web.xml)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app 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 version="3.0"> 7 8 <!-- 配置加载文件的路径,告诉监听器去哪里找Spring的配置文件 --> 9 <context-param> 10 <param-name>contextConfigLocation</param-name> 11 <param-value>classpath:applicationContext.xml</param-value> 12 </context-param> 13 14 <!-- 配置监听器,Tomcat启动,就开始启动并初始化Spring容器 --> 15 <listener> 16 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 17 </listener> 18 19 <!-- 前端控制器 --> 20 <filter> 21 <filter-name>struts2</filter-name> 22 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 23 </filter> 24 <filter-mapping> 25 <filter-name>struts2</filter-name> 26 <url-pattern>/*</url-pattern> 27 </filter-mapping> 28 </web-app>
3.编写Action和配置Action(Struts.xml文件)
1 package com.wanglei.ssh.web.action; 2 3 import lombok.Setter; 4 import com.opensymphony.xwork2.ActionContext; 5 import com.opensymphony.xwork2.ActionSupport; 6 import com.wanglei.ssh.service.IEmployeeService; 7 8 public class EmployeeAction extends ActionSupport{ 9 private static final long serialVersionUID = 1L; 10 11 @Setter 12 private IEmployeeService employeeService; 13 14 public String execute() throws Exception { 15 ActionContext.getContext().put("employee",employeeService.listAll()); 16 return "list"; 17 } 18 19 }
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.devMode" value="true" /> 9 10 <package name="default" namespace="/" extends="struts-default"> 11 <action name="employee" class="employeeAction"> 12 <result name="list">/WEB-INF/views/employee/list.jsp</result> 13 </action> 14 </package> 15 </struts>
4.在applicationContext.xml中增加配置Action(配好之后,在struts.xml文件中改为<action name="employee" class="employeeAction">)
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:p="http://www.springframework.org/schema/p" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xmlns:tx="http://www.springframework.org/schema/tx" 8 xsi:schemaLocation=" 9 http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx.xsd 15 http://www.springframework.org/schema/context 16 http://www.springframework.org/schema/context/spring-context.xsd"> 17 <!-- 属性占位符 --> 18 <context:property-placeholder location="classpath:db.properties"/> 19 <!-- 配置连接池 --> 20 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 21 <property name="driverClassName" value="${jdbc.driverClassName}" /> 22 <property name="url" value="${jdbc.url}" ></property> 23 <property name="username" value="${jdbc.username}" ></property> 24 <property name="password" value="${jdbc.password}" /> 25 </bean> 26 <!-- 配置SessionFactory --> 27 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 28 <!-- 管理连接池 --> 29 <property name="dataSource" ref="dataSource"></property> 30 <!-- hibernate属性配置 --> 31 <property name="hibernateProperties"> 32 <value> 33 hibernate.dialect = org.hibernate.dialect.MySQLDialect 34 hibernate.show_sql = true 35 hibernate.hbm2ddl.auto = update 36 </value> 37 </property> 38 <!-- 映射文件的位置 --> 39 <property name="mappingLocations" value="classpath:com/wanglei/ssh/domain/*.hbm.xml"></property> 40 </bean> 41 <!--what 配置事务管理器 --> 42 <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 43 <property name="sessionFactory" ref="sessionFactory"></property> 44 </bean> 45 <!--when 通用的crud增强 --> 46 <tx:advice id="cruidAdvice" transaction-manager="txManager"> 47 <tx:attributes> 48 <tx:method name="get*" read-only="true"/> 49 <tx:method name="list*" read-only="true"/> 50 <tx:method name="query*" read-only="true"/> 51 <tx:method name="*" propagation="REQUIRED"/> 52 </tx:attributes> 53 </tx:advice> 54 <!--where 切入点语法 --> 55 <aop:config> 56 <aop:pointcut expression="execution(* com.wanglei.ssh.service.*Service.*(..))" id="crudPoint"/> 57 <aop:advisor advice-ref="cruidAdvice" pointcut-ref="crudPoint"/> 58 </aop:config> 59 60 <!-- 配置DAO --> 61 <bean id="employeeDAO" class="com.wanglei.ssh.dao.impl.EmployeeDAOImpl"> 62 <property name="sessionFactory" ref="sessionFactory"></property> 63 </bean> 64 <!-- 配置Service --> 65 <bean id="employeeService" class="com.wanglei.ssh.service.impl.EmployeeServiceImpl"> 66 <property name="employeeDAO" ref="employeeDAO"></property> 67 </bean> 68 <!-- 配置Action --> 69 <bean id="employeeAction" class="com.wanglei.ssh.web.action.EmployeeAction" scope="prototype"> 70 <property name="employeeService" ref="employeeService"></property> 71 </bean> 72 </beans> 73
5.新建list.jsp页面
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="s" uri="/struts-tags" %> 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 <s:debug></s:debug> 12 </body> 13 </html>
6.新建一个domain类Department.java和Department.hbm.xml
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 6 <!-- 7 8 --> 9 10 <hibernate-mapping package="com.wanglei.ssh.domain"> 11 <class name="Employee" table="employee"> 12 <id name="id"> 13 <generator class="native"></generator> 14 </id> 15 <property name="name"></property> 16 <property name="age"></property> 17 <many-to-one name="dept" column="dept_name"></many-to-one> 18 </class> 19 </hibernate-mapping>
7.在web.xml文件中加入如下代码(OSIV问题,目的是让session在请求的时候打开,在响应完毕后再关闭,不能在业务层内关闭。)
1 <!-- OSIV模式 --> 2 <filter> 3 <filter-name>OSIV</filter-name> 4 <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> 5 </filter> 6 <filter-mapping> 7 <filter-name>OSIV</filter-name> 8 <url-pattern>/*</url-pattern> 9 </filter-mapping>
8.运行后数据库再创建除了Department的表,在该表内赋值。
这样,调试成功,整个SSH框架就搭建起来了!