导包
hibernate
hibernate必要包 lib/required
hibernate jpa包 lib/jpa-metamodel-generator
数据库驱动包
struts2
核心包 Essential Dependencies Only/struts-2.5.20-min-lib.zip/lib
struts2整合spring插件包 All Dependencies/struts-2.5.20-lib.zip/lib/struts2-spring-plugin-2.5.20.jar
spring
基本
整合web
整合aop
整合hibernate和事务
整合junit测试
c3p0
jstl
annotations-api.jar
整合spring到web
创建配置文件 applicationContext.xml
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd ">
</beans>
配置spring随项目启动 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随web启动而创建的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置spring配置文件位置参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>
启动Tomcat测试
整合struts2到web
配置struts2主配置文件 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="ssh" namespace="/" extends="struts-default">
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="UserAction_*" class="com.company.web.action.UserAction" method="{1}" >
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
配置struts2核心过滤器 web.xml
<!--struts2核心过滤器-->
<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>
整合struts2到spring
配置常量 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>
<!--将action的创建交给spring容器
spring负责装配Action依赖属性(默认打开)
<constant name="struts.objectFactory.spring.autoWire" value="name"></constant>
-->
<constant name="struts.objectFactory" value="spring"></constant>
<package name="ssh" namespace="/" extends="struts-default">
<global-allowed-methods>regex:.*</global-allowed-methods>
<!-- class属性上填写applicationContext.xml配置中action对象的beanName
完全由spring管理action生命周期,包括action的创建
需要手动组装依赖属性
-->
<action name="UserAction_*" class="userAction" method="{1}" >
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
applicationContext.xml
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd ">
<!-- 注意action对象作用范围一定是多例的,这样才符合struts2架构 -->
<bean name="userAction" class="com.company.ssh.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean>
<bean name="userService" class="com.company.ssh.UserServiceImpl"></bean>
</beans>
整合hibernate与spring
配置applicationContext.xml
<!-- 将SessionFactory配置到spring容器
加载配置方法一:使用 applicationContext.xml配置信息(不推荐)
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
-->
<!-- 将SessionFactory配置到spring容器
加载配置方法二:在spring配置中放置hibernate配置信息 -->
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 配置hibernate基本信息 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
<prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase?characterEncoding=utf8
</prop>
<prop key="hibernate.connection.username">root</prop>
<prop key="hibernate.connection.password">root123</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
<property name="mappingDirectoryLocations" value="classpath:com/company/domain"></property>
</bean>
c3p0连接池
配置db.properties
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/mydatabase?characterEncoding=utf8 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=root123
引入连接池到spring
<!-- 读取db.properties文件 -->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 配置c3p0连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
将连接池注入给SessionFactory
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 将连接池注入到sessionFactory,hibernate会通过连接池获得连接 -->
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="mappingDirectoryLocations" value="classpath:com/company/domain"></property>
</bean>
HibernateTemplate模板操作数据库
UserDaoImpl
package com.company.dao.impl;
import com.company.dao.UserDao;
import com.company.domain.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import java.util.List;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
@Override
public User getByUserName(String name) {
//HQL
return getHibernateTemplate().execute(new HibernateCallback<User>() {
@Override
public User doInHibernate(Session session) throws HibernateException {
String hql = "from User where name = ?0 ";
Query query = session.createQuery(hql);
query.setParameter(0, name);
User user = (User) query.uniqueResult();
return user;
}
});
/*
//Criteria
DetachedCriteria dc = DetachedCriteria.forClass(User.class);
dc.add(Restrictions.eq("id",id));
List<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc);
if (list!=null && list.size()>0) {
return list.get(0);
}
return null;
*/
}
}
spring中配置dao注入sessionFactory applicationContext.xml
<!-- dao -->
<bean name="userDao" class="com.company.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
aop事务
配置核心事务管理器 applicationContext.xml
<!-- 核心事务管理器 -->
<bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
xml配置aop事务
配置通知
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
<tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>
配置将通知织入目标对象
<aop:config>
<aop:pointcut expression="execution(* com.company.service.impl.*ServiceImpl.*(..))" id="txPc"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/>
</aop:config>
注解配置aop事务
开启注解事务
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
package com.company.service.impl;
import com.company.dao.UserDao;
import com.company.domain.User;
import com.company.service.UserService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = true)
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Override
public User getUserByPassword(User user) {
return null;
}
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = false)
public void saveUser(User user) {
userDao.save(user);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
扩大session作用范围
为了避免使用懒加载时出现no-session问题,需要扩大session的作用范围
<?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随web启动而创建的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置spring配置文件位置参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 扩大session作用范围
注意:openSessionInView一定要在struts的filter之前调用
任何filter一定要在struts的filter之前调用
-->
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<!--struts2核心过滤器-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>