SSH框架整合(XML)
Struts2+Spring+Hibernate导包
Struts2导入jar包
struts2/apps/struts2-blank.war/WEB-INF/lib/*.jar
导入与spring整合的jar
struts2/lib/struts2-spring-plugin-2.3.15.3.jar --- 整合Spring框架
struts2/lib/struts2-json-plugin-2.3.15.3.jar --- 整合AJAX
struts2/lib/struts2-convention-plugin-2.3.15.3.jar --- 使用Struts2注解开发.
配置web.xml
<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>/*</url-pattern> </filter-mapping>
配置struts.xml
<struts> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"></package> </struts>
Spring导入jar包
Spring3.2 开发最基本jar包
spring-beans-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar
spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.log4j-1.2.15.jar
AOP开发
spring-aop-3.2.0.RELEASE.jar
spring-aspects-3.2.0.RELEASE.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
Spring事务管理
spring-tx-3.2.0.RELEASE.jar
Spring整合其他ORM框架
spring-orm-3.2.0.RELEASE.jar
Spring在web中使用
spring-web-3.2.0.RELEASE.jar
Spring整合Junit测试
spring-test-3.2.0.RELEASE.jar
在web.xml中配置监听器
<!-- 配置Spring的监听器 --> <listener> <!-- 监听器默认加载的是WEB-INF/applicationContext.xml --> <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>
Hibernate的jar包导入
核心包
hibernate3.jar
lib/required/*.jar
lib/jpa/*.jar
引入hibernate整合日志系统的jar包
数据连接池
数据库驱动
二级缓存(可选)
backport-util-concurrent.jar
commons-logging.jar
ehcache-1.5.0.jar
Struts2和Spring的整合
新建包结构
cn.yzu.action
cn.yzu.service
cn.yzu.dao
cn.yzu.vo
创建实体类
public class Book { private Integer id; private String name; private Double price; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", price=" + price + "]"; } }
新建一个jsp页面(addBook.jsp)
<s:form action="book_add" namespace="/" method="post" theme="simple"> 图书名称:<s:textfield name="name"/><br/> 图书价格:<s:textfield name="price"/><br/> <s:submit value="添加图书"/> </s:form>
编写Action
public class BookAction extends ActionSupport implements ModelDriven<Book>{ // 模型驱动类 private Book book = new Book(); public Book getModel() { return book; } // 处理请求的方法: public String add(){ System.out.println("web层的添加执行了..."); return NONE; } }
配置struts.xml
<action name="book_*" class="cn.yzu.action.BookAction" method="{1}"></action>
Struts2和Spring的整合两种方式
Struts2自己管理Action(方式一,不推荐):Struts2框架自动创建Action的类
<action name="book_*" class="cn.yzu.action.BookAction" method="{1}">
Action交给Spring管理(方式二,推荐,交由Spring管理,有利于AOP开发,进行统一管理)
可以在<action>标签上通过一个伪类名方式进行配置
<action name="book_*" class="bookAction" method="{1}"></action>
在spring的配置文件中
<!-- 配置Action 注意:Action交给Spring管理一定要配置scope=”prototype”--> <bean id="bookAction" class="cn.yzu.action.BookAction" scope=”prototype”></bean>
Web层获得Service:
传统方式:获得WebApplicationContext对象,通过WebAppolicationContext中getBean(“”)
实际开发中
引入struts2-spring-plugin-2.3.15.3.jar,有一个配置文件 : struts-plugin.xml,它开启了常量
<constant name="struts.objectFactory" value="spring" />引发另一个常量的执行:(Spring的工厂类按照名称自动注入)
struts.objectFactory.spring.autoWire = name
Spring整合Hibernate
Spring整合Hibernate框架的时候有两种方式
零障碍整合(一)
可以在Spring中引入Hibernate的配置文件,通过LocalSessionFactoryBean在spring中直接引用hibernate配置文件
<!-- 零障碍整合 在spring配置文件中引入hibernate的配置文件 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"/> </bean>
Spring提供了Hibernate的模板.只需要将HibernateTemplate模板注入给DAO,改写DAO继承HibernateDaoSupport
<!-- DAO的配置 --> <bean id="bookDao" class="cn.yzu.dao.BookDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean>
public class BookDao extends HibernateDaoSupport{ public void save(Book book) { System.out.println("DAO层的保存图书..."); this.getHibernateTemplate().save(book); } }
创建一个映射文件
<hibernate-mapping> <class name="cn.yzu.vo.Book" table="book"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <property name="price"/> </class> </hibernate-mapping>
别忘记事务管理
<!-- 管理事务器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 注解开启事务 --> <tx:annotation-driven transaction-manager="transactionManager"/>
没有Hibernate配置文件的形式(二)
不需要Hibernate配置文件的方式,将Hibernate配置文件的信息直接配置到Spring中
连接池
<!-- 引入外部属性文件. --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean>
Hibernate常用属性
<!-- 配置Hibernate的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.connection.autocommit">false</prop> </props> </property>
映射
<!--<property name="mappingResources"> <list> <value>cn/yzu/vo/Book.hbm.xml</value> </list> </property> --> <property name="mappingDirectoryLocations"> <list> <value>classpath:cn/yzu/vo</value> </list> </property>
HibernateTemplate的API
Serializable save(Object entity) :保存数据
void update(Object entity) :修改数据
void delete(Object entity) :删除数据
<T> T get(Class<T> entityClass, Serializable id) :根据ID进行检索.立即检索
<T> T load(Class<T> entityClass, Serializable id) :根据ID进行检索.延迟检索.
List find(String queryString, Object... values) :支持HQL查询.直接返回List集合.
List findByCriteria(DetachedCriteria criteria) :离线条件查询.
List findByNamedQuery(String queryName, Object... values) :命名查询的方式.
OpenSessionInView
解决办法:1:不使用懒加载 2:在web层开启事务开启事务(添加如下配置)
<filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
完整配置
public class BookAction extends ActionSupport implements ModelDriven<Book>{ private BookService bookService; public void setBookService(BookService bookService) { this.bookService = bookService; } // 模型驱动类 private Book book = new Book(); public Book getModel() { return book; } // 处理请求的方法: public String add(){ System.out.println("web层的添加执行了..."); bookService.add(book); return NONE; } public String findByIdLazy(){ Book book = bookService.findByIdLazy(2); System.out.println(book); return NONE; } }
public class BookDao extends HibernateDaoSupport{ public void save(Book book) { System.out.println("DAO层的保存图书..."); this.getHibernateTemplate().save(book); } public void update(Book book){ this.getHibernateTemplate().update(book); } public void delete(Book book){ this.getHibernateTemplate().delete(book); } public Book findById(Integer id){ return this.getHibernateTemplate().get(Book.class, id); } public List<Book> findAll(){ return this.getHibernateTemplate().find("from Book"); } public List<Book> findByCriteria(DetachedCriteria criteria){ return this.getHibernateTemplate().findByCriteria(criteria); } public List<Book> findByName(String name){ return this.getHibernateTemplate().findByNamedQuery("findByName", name); } public Book findByIdLazy(Integer id){ return this.getHibernateTemplate().load(Book.class,id); } }
@Transactional public class BookService { private BookDao bookDao; public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } public void add(Book book) { bookDao.save(book); } public void update(Book book) { bookDao.update(book); } public void delete(Book book) { bookDao.delete(book); } public Book findById(Integer id) { return bookDao.findById(id); } public List<Book> findAll(){ return bookDao.findAll(); } public List<Book> findByCriteria(DetachedCriteria criteria){ return bookDao.findByCriteria(criteria); } public List<Book> findByName(String name){ return bookDao.findByName(name); } public Book findByIdLazy(Integer id){ return bookDao.findByIdLazy(id); } }
public class Book { private Integer id; private String name; private Double price; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", price=" + price + "]"; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="cn.yzu.vo.Book" table="book"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <property name="price"/> </class> <query name="findByName"> from Book where name = ? </query> </hibernate-mapping>
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/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"> <!-- 没有Hibernate配置文件 --> <!-- 连接池信息 --> <!-- 引入外部属性文件. --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 管理连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 配置Hibernate的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.connection.autocommit">false</prop> </props> </property> <!-- 加载映射 --> <!-- <property name="mappingResources"> <list> <value>cn/yzu/vo/Book.hbm.xml</value> </list> </property> --> <property name="mappingDirectoryLocations"> <list> <value>classpath:cn/yzu/vo</value> </list> </property> </bean> <!-- 配置Action --> <bean id="bookAction" class="cn.yzu.action.BookAction" scope="prototype"> <property name="bookService" ref="bookService"/> </bean> <!-- Service的配置 --> <bean id="bookService" class="cn.yzu.service.BookService"> <property name="bookDao" ref="bookDao"/> </bean> <!-- DAO的配置 --> <bean id="bookDao" class="cn.yzu.dao.BookDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 管理事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 注解开启事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="book_*" class="bookAction" method="{1}"></action> </package> </struts>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置Spring的监听器 --> <listener> <!-- 监听器默认加载的是WEB-INF/applicationContext.xml --> <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> <!-- 配置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>/*</url-pattern> </filter-mapping> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>添加图书</h1> <s:form action="book_add" namespace="/" method="post" theme="simple"> 图书名称:<s:textfield name="name"/><br/> 图书价格:<s:textfield name="price"/><br/> <s:submit value="添加图书"/> </s:form> </body> </html>