<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>在src下新建struts.xml(也可以从 Struts2/apps/struts2-blank.war/WEB-INF/classes下拷贝)
<constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> </package>
<!-- 配置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>在applicationContext.xml中引入aop、tx、context约束(具体可以从dist包中的xsd-config.html中进行拷贝)
<?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"> </beans>
log4j.properties
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=c:/mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=off, stdout在Servlet/Filter中获得Spring上下文对象
WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(servletContext);
Configurationconfiguration = new Configuration().configure(); SessionFactorysessionFactory= configuration.buildSessionFactory(); Sessionsession = sessionFactory.openSession()/ getCurrentSession(); Transactiontransaction = session.beginTransaction(); 数据库操作 transaction.commit();hibernate.cfg.xml的约束可以在 hibernate3.jar/org.hibernate/hibernate-configuration-3.0.dtd中找到复制拷贝即可
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">至于持久类映射文件的约束可以在 hibernate3.jar/org.hibernate/hibernate-mapping-3.0.dtd中找到复制到 *.hbm.xml中即可。
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
创建包结构
<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>
<package name="default" namespace="/" extends="struts-default"> <action name="book_*" class="ssh1.test.action.BookAction" method="{1}"></action> </package>这种方式在Action中获取Service时只需要在Action中声明一Service变量 然后再提供一个Setter方法 并在applicationContext.xml中注册一下Service即可。然后由Struts2自己创建Action后就会自动按照名称为Action注入Service 如下所示在applicationContext.xml中需如下进行配置:
<bean id="bookService" class="ssh1.test.service.BookService"> <property name="bookDao" ref="bookDao" /> </bean> <bean id="bookDao" class="ssh1.test.dao.BookDao" />之所以Struts2会自动按照名称为Action注入名称对应的Service 是因为在struts2-spring-plugin-x.x.x.jar下有一配置文件: struts-plugin.xml 在此文件中开启了如下常量
<constant name="struts.objectFactory" value="spring" />引发了另一个常量的执行:(Spring的工厂类按照名称自动注入)
struts.objectFactory.spring.autoWire = name
<package name="default" namespace="/" extends="struts-default"> <action name="book_*" class="bookAction" method="{1}"></action> </package>在applicationContext.xml中配置和伪类名相同的Bean
<!-- 配置Action --> <bean id="bookAction" class="ssh1.test.action.BookAction" scope="prototype"> <property name="bookService" ref="bookService" /> </bean> <!-- Service的配置 --> <bean id="bookService" class="ssh1.test.service.BookService"> <property name="bookDao" ref="bookDao" /> </bean> <!-- DAO的配置 --> <bean id="bookDao" class="ssh1.test.dao.BookDao" />
推荐使用第二种方式,在Spring中管理的类,可以对其进行AOP开发,统一的管理
注意:由Sping统一管理创建Action时 一定要声明为scope="prototype" 否则会有线程安全问题
<!-- 零障碍整合 在Spring配置文件中引入Hibernate的配置文件 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> </bean>2. Spring提供了Hibernate的模板,只需要将HibernateTemplate模板注入给DAO(前提是DAO继承自HibernateDaoSupport),注意:注入sessionFactory便可自动设置Hibernate模板
<!-- DAO的配置 --> <bean id="bookDao" class="ssh1.test.dao.BookDao"> <property name="sessionFactory" ref="sessionFactory" /> </bean>改写DAO,继承自HibernateDaoSupport
public class BookDao extends HibernateDaoSupport { public void save(Book book) { System.out.println("DAO层保存图书"); this.getHibernateTemplate().save(book); } }3.创建一个持久化类的映射文件(Book.hbm.xml)
<hibernate-mapping> <class name="ssh1.test.vo.Book" table="book"> <id name="id" column="id"> <generator class="native" /> </id> <property name="name" /> <property name="price" /> </class> </hibernate-mapping>4.使用HibernateTransactionManager管理Spring事务
<!-- 管理事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>5.使用<tx:annotation-driven>开启注解事务
<!-- 注解开启事务 --> <tx:annotation-driven transaction-manager="transactionManager" />项目名myspring_ssh1 具体代码如下:
package ssh1.test.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; } }Book.hbm.xml
<?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="ssh1.test.vo.Book" table="book"> <id name="id" column="id"> <generator class="native" /> </id> <property name="name" /> <property name="price" /> </class> </hibernate-mapping>BookDao
package ssh1.test.dao; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import ssh1.test.vo.Book; public class BookDao extends HibernateDaoSupport { public void save(Book book) { System.out.println("DAO层保存图书"); this.getHibernateTemplate().save(book); } }BookService
package ssh1.test.service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import ssh1.test.dao.BookDao; import ssh1.test.vo.Book; @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false) public class BookService { private BookDao bookDao; public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } public void add(Book book) { System.out.println("Service层保存图书......"); bookDao.save(book); } }BookAction
package ssh1.test.action; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import ssh1.test.service.BookService; import ssh1.test.vo.Book; 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; } }struts.xml
<?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.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="book_*" class="bookAction" method="{1}"></action> </package> </struts>hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 必须配置的属性 --> <!-- 配置数据库连接池的基本信息 --> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="hibernate.connection.url"> jdbc:mysql:///ssh1 </property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!-- Hibernate的方言 --> <!-- 不同的数据库,生成的底层的SQL语句是不同的 --> <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property> <!-- 可选的属性 --> <!-- 显示SQL --> <property name="hibernate.show_sql">true</property> <!-- 格式化SQL --> <property name="hibernate.format_sql">true</property> <property name="hibernate.connection.autocommit">false</property> <!-- hbm: 映射 to DDL: create drop alter --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- C3P0连接池设定 --> <!-- 使用c3po连接池 配置连接池提供的供应商 --> <property name="connection.provider_class"> org.hibernate.connection.C3P0ConnectionProvider </property> <!--在连接池中可用的数据库连接的最少数目 --> <property name="c3p0.min_size">5</property> <!--在连接池中所有数据库连接的最大数目 --> <property name="c3p0.max_size">20</property> <!--设定数据库连接的过期时间,以秒为单位, 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 --> <property name="c3p0.timeout">120</property> <!--每3000秒检查所有连接池中的空闲连接 以秒为单位 --> <property name="c3p0.idle_test_period">3000</property> <!-- 通知Hibernate加载那些映射文件 --> <mapping resource="ssh1/test/vo/Book.hbm.xml" /> </session-factory> </hibernate-configuration>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: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"> <!-- 零障碍整合 在Spring配置文件中引入Hibernate的配置文件 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> </bean> <!-- 配置Action --> <bean id="bookAction" class="ssh1.test.action.BookAction" scope="prototype"> <property name="bookService" ref="bookService" /> </bean> <!-- Service的配置 --> <bean id="bookService" class="ssh1.test.service.BookService"> <property name="bookDao" ref="bookDao" /> </bean> <!-- DAO的配置 --> <bean id="bookDao" class="ssh1.test.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>log4j.properties
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=c:/mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=info, stdoutaddBook.jsp
<%@ 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"/> <s:submit value="添加图书"/> </s:form> </body> </html>web.xml
<?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"> <!-- 配置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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>运行结果如下
<!-- 引入外部属性文件 --> <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>2.配置Hibernate常用属性以及持久化类映射文件
<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.autocommit">false</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <!-- 加载映射 --> <property name="mappingDirectoryLocations"> <list> <value>classpath:ssh2/test/vo</value> </list> </property> </bean>HibernateTemplate的API
<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>新建项目myspring3_ssh2 项目结构如下:
package ssh2.test.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 + "]"; } }Book.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="ssh2.test.vo.Book" table="book"> <id name="id" column="id"> <generator class="native" /> </id> <property name="name" /> <property name="price" /> </class> <query name="findByName"> from Book where name = ? </query> </hibernate-mapping>BookDao
package ssh2.test.dao; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import ssh2.test.vo.Book; 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); } }BookService
package ssh2.test.service; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import ssh2.test.dao.BookDao; import ssh2.test.vo.Book; @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false) public class BookService { private BookDao bookDao; public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } public void add(Book book) { System.out.println("Service层保存图书......"); 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); } }BookAction
package ssh2.test.action; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import ssh2.test.service.BookService; import ssh2.test.vo.Book; 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; } }SSHTest
package ssh2.test.junitDemo; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import ssh2.test.service.BookService; import ssh2.test.vo.Book; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class SSHTest { @Autowired @Qualifier("bookService") private BookService bookService; @Test public void demo1() { Book book = new Book(); book.setId(1); book.setName("Java从入门到精通"); book.setPrice(98d); bookService.update(book); } @Test public void demo2() { Book book = new Book(); book.setId(1); bookService.delete(book); } @Test public void demo3() { Book book = bookService.findById(2); System.out.println(book); } @Test public void demo4() { List<Book> books = bookService.findAll(); for (Book book : books) { System.out.println(book); } } @Test public void demo5() { DetachedCriteria criteria = DetachedCriteria.forClass(Book.class); criteria.add(Restrictions.eq("name", "Struts2开发入门")); List<Book> books = bookService.findByCriteria(criteria); for (Book book : books) { System.out.println(book); } } @Test public void demo6() { List<Book> books = bookService.findByName("SSH整合2"); for (Book book : books) { System.out.println(book); } } }struts.xml
<?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.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="book_*" class="bookAction" method="{1}"></action> </package> </struts>log4j.properties
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=c:/mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=info, stdoutjdbc.proeprties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///ssh2 jdbc.user=root jdbc.password=rootapplicationContext.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: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> <!-- 无Hibernate配置文件整合 在Spring配置文件中引入Hibernate应该配置的信息 --> <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.autocommit">false</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <!-- 加载映射 --> <property name="mappingDirectoryLocations"> <list> <value>classpath:ssh2/test/vo</value> </list> </property> </bean> <!-- 配置Action --> <bean id="bookAction" class="ssh2.test.action.BookAction" scope="prototype"> <property name="bookService" ref="bookService" /> </bean> <!-- Service的配置 --> <bean id="bookService" class="ssh2.test.service.BookService"> <property name="bookDao" ref="bookDao" /> </bean> <!-- DAO的配置 --> <bean id="bookDao" class="ssh2.test.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>web.xml
<?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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>addBook.jsp
<%@ 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>部署项目后访问如下
<!-- 扫描添加注解的类 --> <context:component-scan base-package="ssh3.test.action,ssh3.test.dao,ssh3.test.service" />2.配置连接池
<!-- 连接池信息 --> <!-- 引入外部属性文件 --> <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>3.使用AnnotationSessionFactoryBean配置Hibernate属性与映射扫描
<!-- 无Hibernate配置文件整合 在Spring配置文件中引入Hibernate应该配置的信息 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!-- 管理连接池 --> <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.autocommit">false</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <!-- 映射扫描 --> <property name="packagesToScan"> <list> <value>ssh3.test.vo</value> </list> </property> </bean>4.最后配置Hibernate模板与事务管理
<!-- 配置Hibernate模板 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <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" />新建项目myspring3_ssh3
package ssh3.test.vo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "book") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name") 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 + "]"; } }BookDao
package ssh3.test.dao; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import ssh3.test.vo.Book; @Repository("bookDao") public class BookDao { @Autowired @Qualifier("hibernateTemplate") HibernateTemplate hibernateTemplate; public void save(Book book) { System.out.println("DAO层保存图书"); hibernateTemplate.save(book); } }BookService
package ssh3.test.service; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import ssh3.test.dao.BookDao; import ssh3.test.vo.Book; @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false) @Service("bookService") public class BookService { @Autowired @Qualifier("bookDao") private BookDao bookDao; public void add(Book book) { System.out.println("Service层保存图书......"); bookDao.save(book); } }BookAction
package ssh3.test.action; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import ssh3.test.service.BookService; import ssh3.test.vo.Book; //<package namespace="/" extends="strtus-default"> @Namespace("/") @ParentPackage("struts-default") @Controller("bookAction") @Scope("prototype") public class BookAction extends ActionSupport implements ModelDriven<Book> { // 模型驱动类 private Book book = new Book(); public Book getModel() { return book; } // 在Action中注入Service @Autowired @Qualifier("bookService") private BookService bookService; // 请求处理的方法 @Action(value = "book_add") public String add() { System.out.println("web层的方法添加执行了......"); bookService.add(book); return NONE; } }jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///ssh3 jdbc.user=root jdbc.password=rootlog4j.properties
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=c:/mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=info, stdoutapplicationContext.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: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"> <!-- 使用纯注解实现三大框架的整合 --> <!-- 扫描添加注解的类 --> <context:component-scan base-package="ssh3.test.action,ssh3.test.dao,ssh3.test.service" /> <!-- 连接池信息 --> <!-- 引入外部属性文件 --> <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配置文件整合 在Spring配置文件中引入Hibernate应该配置的信息 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!-- 管理连接池 --> <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.autocommit">false</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <!-- 映射扫描 --> <property name="packagesToScan"> <list> <value>ssh3.test.vo</value> </list> </property> </bean> <!-- 配置Hibernate模板 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <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>web.xml
<?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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>addBook.jsp
<%@ 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>运行测试 成功