一、集成步骤
1、新建一个web项目
2、导入Hibernate4.3.5需要的jar包
Hibernate4.3.5Requiredjar包.png3、数据库包
- druid-1.0.15.jar
- mysql-connector-java-8.0.16.jar
4、Spring需要的依赖包
- spring-aop-4.1.2.RELEASE.jar
- spring-aspects-4.1.2.RELEASE.jar
- spring-beans-4.1.2.RELEASE.jar
- spring-context-4.1.2.RELEASE.jar
- spring-core-4.1.2.RELEASE.jar
- spring-expression-4.1.2.RELEASE.jar
- spring-jdbc-4.1.2.RELEASE.jar
- spring-orm-4.1.2.RELEASE.jar
- spring-test-4.1.2.RELEASE.jar
- spring-tx-4.1.2.RELEASE.jar
5、db.properties
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=admin
jdbc.url=jdbc:mysql:///springdemo?useSSL=true&serverTimezone=UTC
jdbc.maxActive=5
#jdbc.url=jdbc:mysql:///springdemo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
6、domain
package com.revanwang.ssh.domain;
import lombok.Data;
@Data
public class Employee {
private Long id;
private String name;
private Integer age;
}
7、dao
package com.revanwang.ssh.dao.impl;
import com.revanwang.ssh.dao.IEmployeeDAO;
import com.revanwang.ssh.domain.Employee;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.List;
public class EmployeeDAOImpl implements IEmployeeDAO {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory;
}
@Override
public void save(Employee employee) {
Session session = this.sessionFactory.getCurrentSession();
session.save(employee);
}
@Override
public void update(Employee employee) {
Session session = this.sessionFactory.getCurrentSession();
session.update(employee);
}
@Override
public void delete(Employee employee) {
Session session = this.sessionFactory.getCurrentSession();
session.delete(employee);
}
@Override
public Employee get(Long id) {
Session session = this.sessionFactory.getCurrentSession();
return (Employee) session.get(Employee.class, id);
}
@Override
public List<Employee> getList() {
Session session = this.sessionFactory.getCurrentSession();
Query query = session.createQuery("SELECT e FROM Employee e");
return query.list();
}
}
7、service
package com.revanwang.ssh.service.impl;
import com.revanwang.ssh.dao.IEmployeeDAO;
import com.revanwang.ssh.domain.Employee;
import com.revanwang.ssh.service.IEmployeeService;
import lombok.Setter;
import java.util.List;
public class EmployeeServiceImpl implements IEmployeeService {
@Setter
private IEmployeeDAO employeeDAO;
@Override
public void save(Employee employee) {
this.employeeDAO.save(employee);
}
@Override
public void update(Employee employee) {
this.employeeDAO.update(employee);
}
@Override
public void delete(Employee employee) {
this.employeeDAO.delete(employee);
}
@Override
public Employee get(Long id) {
return this.employeeDAO.get(id);
}
@Override
public List<Employee> getList() {
return this.employeeDAO.getList();
}
}
8、test
package com.revanwang.ssh.test;
import com.revanwang.ssh.domain.Employee;
import com.revanwang.ssh.service.IEmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class EmployeeServiceTest {
@Autowired
private IEmployeeService employeeService;
@Test
public void save() {
Employee employee = new Employee();
employee.setName("阿朱");
employee.setAge(20);
employeeService.save(employee);
}
@Test
public void update() {
Employee employee = new Employee();
employee.setId(8L);
employee.setName("阿朱");
employeeService.update(employee);
}
@Test
public void delete() {
Employee employee = new Employee();
employee.setId(3L);
employeeService.delete(employee);
}
@Test
public void get() {
System.out.println(employeeService.get(1L));
}
@Test
public void getList() {
List<Employee> list = employeeService.getList();
for (Employee emp : list) {
System.out.println(emp);
}
}
}
二、Struts2集成
1、导入jar包
Struts2.png注意:因为Hibernate中也依赖javassist.jar包,Struts2也依赖javassist.jar包,所以只需要导入一个javassist.jar包就好
2、web.xml配置
2.1 前端控制器
<!--前端控制器-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
2.2 系统启动,初始化Spring容器
<!--系统启动,就初始化Spring容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2.3 监听器寻找Spring的配置文件
<!--告诉监听器去哪里去找Spring的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--告诉监听器去哪里去找Spring的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--系统启动,就初始化Spring容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--前端控制器-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
三、Struts2的Action创建权转交给Spring管理
-
applicationContext.xml
<!-- 5、配置Action -->
<bean id="employeeAction" class="com.revanwang.ssh.web.action.EmployeeAction" scope="prototype">
<property name="employeeService" ref="employeeService"/>
</bean>
-
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="employeePKG" namespace="/" extends="struts-default">
<action name="employee" class="employeeAction"/>
</package>
</struts>
四、Spring和Struts2集成的原理
1、struts-default.xml文件
默认情况下,Struts2中所有的对象都是由 xWork 容器中的 ObjectFactory 创建的
<bean class="com.opensymphony.xwork2.ObjectFactory" name="struts"/>
2、struts2-spring-plugin.jar
struts2-spring-plugin.jar 是Spring和Struts2集成的桥梁。本身也是Struts2提供的一个插件,用来和Spring做整合。
<?xml version="1.0" encoding="UTF-8" ?>
<!--
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
-->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<!-- Make the Spring object factory the automatic default -->
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.class.reloading.watchList" value="" />
<constant name="struts.class.reloading.acceptClasses" value="" />
<constant name="struts.class.reloading.reloadConfig" value="false" />
<constant name="struts.disallowProxyMemberAccess" value="true" />
<constant name="struts.json.result.excludeProxyProperties" value="true" />
<package name="spring-default">
<interceptors>
<interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
</interceptors>
</package>
</struts>
重新定义了一个对象工厂,起名为spring。该对象工厂的类型是StrutsSpringObjectFactory,其本身就是Struts2的对象工厂。ObjectFactory的子类。用来设置:Struts2中所有的对象都由Spring来创建
五、Spring - Struts2 - Hibernate4 整合配置
-
数据库配置文件(db.properties)
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=admin
jdbc.url=jdbc:mysql:///springdemo?useSSL=true&serverTimezone=UTC
jdbc.maxActive=5
#jdbc.url=jdbc:mysql:///springdemo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
-
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--
默认情况下,struts2中所有的对象都是由xWork容器中的ObjectFactory创建的
-->
<!-- <bean class="com.opensymphony.xwork2.ObjectFactory" name="struts"/>-->
<!-- 5、配置Action -->
<bean id="employeeAction" class="com.revanwang.ssh.web.action.EmployeeAction" scope="prototype">
<property name="employeeService" ref="employeeService"/>
</bean>
<!-- 4、service -->
<bean id="employeeService" class="com.revanwang.ssh.service.impl.EmployeeServiceImpl">
<property name="employeeDAO" ref="employeeDAO"/>
</bean>
<!-- 3、employeeDAO -->
<bean id="employeeDAO" class="com.revanwang.ssh.dao.impl.EmployeeDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 2、sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 2.1管理数据库链接 -->
<property name="dataSource" ref="dataSource_db"/>
<!-- 2.2设置Hibernate -->
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update
</value>
</property>
<!-- 2.3设置 bean.hbm.xml -->
<property name="mappingLocations" value="classpath:com/revanwang/ssh/domain/*.hbm.xml"/>
</bean>
<!-- 1、配置数据库 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置dataSource -->
<bean id="dataSource_db" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="url" value="${jdbc.url}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
</bean>
<!-- 0、配置事务 -->
<!-- what:增强事务 -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- when:什么时候 -->
<tx:advice id="adviceId" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="list*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- where:在哪里增加事务 -->
<aop:config>
<aop:pointcut id="pointcutId"
expression="execution(* com.revanwang.ssh.service.*Service.*(..))"/>
<aop:advisor advice-ref="adviceId" pointcut-ref="pointcutId"/>
</aop:config>
</beans>
-
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="employeePKG" namespace="/" extends="struts-default">
<action name="employee" class="employeeAction"/>
</package>
</struts>
网友评论