一、SSH整合
- spring框架和持久层hibernate整合
- spring框架和mvc框架struts2整合
1.1 导包
- 创建Web3.0
- SSH所需要的基础包
- Myeclipse导入本地jar包
1.2 添加框架支持
添加框架支持的顺序: strus2 + spring + hibernate
1.2.1 添加strus2框架支持
1.2.2 添加spring框架支持
1.2.3 添加hibernate框架支持
添加前Myeclipse需要先连接DB
1.2.4 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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="url"
value="jdbc:mysql://localhost:3306/hiberdb">
</property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
</bean>
<!-- 声明式事务管理 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" /></beans>
1.2.5 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ssh-demos</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- struts2的中央控制器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- spring容器加载的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>
1.3 添加配置
1.3.1 jdbc.properties
#JDBC
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hiberdb?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123
#Hibernate props
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.cache.provider_class=net.sf.ehcache.hibernate.EhCacheProvider
hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
1.3.2 持久层entity代码实例
- 通过hibernate反向工程生成
package cn.linus.ssh.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Users entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "users", catalog = "hiberdb")
public class Users implements java.io.Serializable {
// Fields
private Integer id;
private String name;
private String password;
private String telephone;
private String username;
private String isadmin;
// Constructors
/** default constructor */
public Users() {
}
/** minimal constructor */
public Users(String name, String password) {
this.name = name;
this.password = password;
}
/** full constructor */
public Users(String name, String password, String telephone, String username, String isadmin) {
this.name = name;
this.password = password;
this.telephone = telephone;
this.username = username;
this.isadmin = isadmin;
}
// Property accessors
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "NAME", nullable = false, length = 50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "PASSWORD", nullable = false, length = 50)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "telephone", length = 15)
public String getTelephone() {
return this.telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
@Column(name = "username", length = 50)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "isadmin", length = 5)
public String getIsadmin() {
return this.isadmin;
}
public void setIsadmin(String isadmin) {
this.isadmin = isadmin;
}
}
1.3.3 数据访问层Dao代码实例
/**
* 专门用于数据访问层注解<bean/>
* 从语义上说明当前是数据访问层,核心注解:@Component
*/
@Repository
public class UserDaoImpl implements UserDao {
//自动绑定<bean autowired="byName|byType"/>
@Autowired //默认是根据byType获取
private SessionFactory SessionFactory;
public Session getSession() {
return this.SessionFactory.getCurrentSession();
}
@Override
public Users findUserById(int id) {
return (Users) getSession().get(Users.class, id);
}
@Override
public List<Users> findUserByExample(Users userExample) {
Criteria criteria = getSession().createCriteria(Users.class);
criteria.add(Example.create(userExample));
return criteria.list();
}
public void setSessionFactory(SessionFactory sessionFactory) {
SessionFactory = sessionFactory;
}
}
1.3.4 业务层Service代码实例
/**
* 专门用于业务层注解<bean/>
* 包含@Component,从语义上说明当前类是业务层
*/
@Service
@Transactional //使用了aop(事务管理)
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public Users login(Users user) {
List<Users> list = userDao.findUserByExample(user);
if (list!=null && list.size()>0) {
return list.get(0);
}
return null;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
1.3.5 action代码实例
public class UserAction extends ActionSupport {
@Autowired
private UserService userService;
private Users user;
private String message;//提示消息
public String login() {
Users loginUser = userService.login(user);
if (loginUser != null) {
//保存session
Map<String, Object> sessionMap = ActionContext.getContext().getSession();
sessionMap.put("user", loginUser);
return SUCCESS;
} else {
setMessage("账号或密码错误");
return ERROR;
}
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public UserService getUserService() {
return userService;
}
}
1.3.6 web.xml 配置实例
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ssh-login-demo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- Spring提供的OpenSessionInViewFilter(放第一个) -->
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- struts2的中央控制器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- spring容器加载的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>
1.3.7 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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 启动注解配置 -->
<context:annotation-config></context:annotation-config>
<!-- 读取外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<!-- hibernate专有的属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
</props>
</property>
<!-- 扫描实体包中映射文件,packagesToScan适用于注解映射 -->
<property name="packagesToScan">
<list>
<value>cn.linus.ssh.entity</value>
</list>
</property>
<!-- 用于xml文档映射
<property name="mappingResources">
<list>
<value>cn/web/ssh/entity/Users.hbm.xml</value>
</list>
</property> -->
</bean>
<!-- 扫描dao和service包,便于ioc容器读取当中的注解 -->
<context:component-scan base-package="cn.linus.ssh.dao.impl,cn.linus.ssh.service.impl"></context:component-scan>
<!-- 声明事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
1.3.8 struts.xml 配置实例
<struts>
<package name="login_pack" extends="struts-default">
<!-- action由struts2容器创建,不是由spring创建 -->
<action name="loginAction" class="cn.linus.ssh.action.UserAction" method="login">
<result name="success">/index.jsp</result>
<result name="error">/login.jsp</result>
</action>
</package>
</struts>
1.3.9 login.jsp重要代码
<form action="loginAction.action" method="post">
<p>用户名:<input type="text" name="user.name"></p>
<p>密 码:<input type="password" name="user.password"></p>
<p>
<input type="submit" value="登录">
<span>${message}</span>
</p>
</form>
1.3.10 index.jsp重要代码
<h2>欢迎你,${sessionScope.user.name}</h2>
二、事务管理
- 数据库级别的事务:DBA,ORACLE
- 应用程序级别的事务:应用程序员,业务层
Spring框架是使用aop编程实现事务管理。业务层的每个业务方法都要有事务管理,所以,事务是“共性”问题。采用声明式事务管理的。分成两种:
<!-- beans.xml头部配置 -->
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.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/util
http://www.springframework.org/schema/util/spring-util.xsd">
2.1 声明式事务管理
<!-- 1.配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 2.事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="register" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 3.事务织入 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.linus.ssh.service.impl.*.*(..))"/>
</aop:config>
2.2 注解事务
<!-- 1.配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 启动注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
@Transactional
@Override
public boolean addUser(Users user) {
//goodDao.delete(id);
//userDao.save(user);
return false;
}
2.3 事务传播途径
public void doService1(){
//...
doService2();
//...
}
- REQUIRED:如果当前存在事务,则加入该事务;如果当前不存在事务,则创建一个新的事务。
- REQUIRES_NEW:重新创建一个新的事务,如果当前存在事务,延缓当前的事务。
- SUPPORTS:如果当前存在事务,则加入该事务;如果当前不存在事务,则以非事务的方式继续运行。
- MANDATORY:如果当前存在事务,则加入该事务;如果当前不存在事务,则抛出异常。