Struts2、Spring、Hibernate三大框架在一个项目中的具体职责分配如下:
三大框架整合,导入各个框架和整合所需的包(本项目采用的是Struts2.3+spring3.0+hibernate)
1.添加Spring框架
1)编写applicationContext-bean.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-3.0.xsd"> <bean id="date" class="java.util.Date"></bean> </beans>
2)测试
public class SSHTest { @Test public void spring(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-*.xml"); System.out.println(context.getBean("date")); } }
若测试通过,则spring框架添加成功
2.添加Hibernate框架
1)添加hibernate配置文件
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="connection.url"> jdbc:mysql://localhost:3306/shop </property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="c3p0.initialPoolSize">5</property> <property name="c3p0.minPoolSize">10</property> <property name="c3p0.maxPoolSize">20</property> <property name="c3p0.checkoutTimeout">6000</property> <property name="show_sql">true</property> </session-factory> </hibernate-configuration>
该配置文件中采用了数据库连接池
2)编写测试工具类
HibernateSessionFactory.java
package cn.lsl.test; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory { private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } public static Configuration getConfiguration() { return configuration; } }
3)测试
@Test public void hibernate(){ System.out.println(HibernateSessionFactory.getSessionFactory()); }
若测试通过,则Hibernate框架添加成功
3.Hibernate与Spring框架整合
1)配置LocalSessionFactoryBean
<!-- 1: Spring来管理Hibernate配置文件,就是取代了HibernateSessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 加载hibernate的配置文件 --> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> </bean>
2)配置hibernateTemplate
<!-- 2.通过sessionFactory,返回session,在Spring由HibenrateTemplate封装session --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <!-- 需要sessionFactory --> <property name="sessionFactory" ref="sessionFactory" /> </bean>
3)配置事务管理器
<!-- 3.配置事物管理器transactionManager 如果要实现Spring的AOP声明式事务,则需要Spring提供事物管理器,所有session都是从sessionFactory创建的, 事务管理器,需要控制sessionFactory --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
4)配置事物通知
<!-- 4 配置事务通知: 事务由事务管理器提供 --> <tx:advice id="advice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="*" propagation="NEVER" read-only="true"/> </tx:attributes> </tx:advice>
5)配置切入点表达式
<!-- 5: 切入表达式: 配置运行的时候*包的*类切入通知 --> <aop:config> <aop:pointcut expression="execution(* cn.lsl.shop.service.impl.*.*(..))" id="pointcut"/> <aop:advisor advice-ref="advice" pointcut-ref="pointcut"/> </aop:config>
6)编写实体类和映射文件
package cn.lsl.shop.pojo; public class Category implements java.io.Serializable { private Integer cid; private String ctype; private Boolean chot; private Integer aid; public Category() { super(); // TODO Auto-generated constructor stub } public Category(String ctype, Boolean chot, Integer aid) { super();this.ctype = ctype; this.chot = chot; this.aid = aid; } public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } public String getCtype() { return ctype; } public void setCtype(String ctype) { this.ctype = ctype; } public Boolean getChot() { return chot; } public void setChot(Boolean chot) { this.chot = chot; } public Integer getAid() { return aid; } public void setAid(Integer aid) { this.aid = aid; } }
映射文件
<?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="cn.lsl.shop.pojo.Category" table="category"> <id name="cid" type="java.lang.Integer"> <column name="cid" /> <generator class="native"></generator> </id> <property name="ctype" type="java.lang.String"> <column name="ctype" length="20" /> </property> <property name="chot" type="java.lang.Boolean"> <column name="chot" /> </property> <property name="aid" type="java.lang.Integer"> <column name="aid" /> </property> </class> </hibernate-mapping>
最后记得在hibernate.cfg.xml文件中添加
<mapping resource="cn/lsl/shop/pojo/Category.hbm.xml" />
7)编写Service层
package cn.lsl.shop.service.impl; import org.springframework.orm.hibernate3.HibernateTemplate; import cn.lsl.shop.pojo.Category; public class CategoryServiceImpl { private HibernateTemplate hibernateTemplate = null; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public void save(Category category){ hibernateTemplate.save(category); } }
并纳入Spring容器管理
<bean id="categoryServiceImpl" class="cn.lsl.shop.service.impl.CategoryServiceImpl"> <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean>
8)测试
/*
* Spring管理Hibernate,采用AOP实现声明式事物
*
* 加载Spring与Hibernate整合的jar包
* */
@Test
public void springHibernate(){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext-*.xml");
CategoryServiceImpl categoryServiceImpl=(CategoryServiceImpl)context.getBean("categoryServiceImpl");
Category category=new Category("test",false,1);
categoryServiceImpl.save(category);
}
若数据成功插入数据库,则Spring和Hibernate整和成功
4.添加struts2框架
1)编写Action类
package cn.lsl.shop.action; import cn.lsl.shop.service.impl.CategoryServiceImpl; public class TestAction { public String test(){ System.out.println(categoryServiceImpl); return "success"; } }
2)编写配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 注意:添加jar包的时候要刷新tomcat中项目 Struts 与Spring的整合作用: Spring来管理Action,从而实现Action与Service解耦 --> <!-- struts-default 使用默认Struts拦截器 --> <package name="shop" extends="struts-default"> <action name="testAction_*" class="cn.lsl.shop.action.TestAction" method="{1}"> <!-- struts2中 重定向可以忽略工程名 --> <result name="success" type="redirect">/success.jsp</result> </action> </package> </struts>
3)配置web.xml文件
<!-- 配置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>
5.整合Spring和Struts2
1)修改Action类,并纳入spring管理
public class TestAction { private CategoryServiceImpl categoryServiceImpl=null; public void setCategoryServiceImpl(CategoryServiceImpl categoryServiceImpl) { this.categoryServiceImpl = categoryServiceImpl; } public String test(){ System.out.println(categoryServiceImpl); return "success"; } }
<bean id="testAction" class="cn.lsl.shop.action.TestAction"> <property name="categoryServiceImpl" ref="categoryServiceImpl" /> </bean>
2)修改配置文件
<package name="shop" namespace="/" extends="struts-default"> <action name="testAction_*" class="testAction" method="{1}"> <!-- struts2中 重定向可以忽略工程名 --> <result name="success" type="redirect">/success.jsp</result> </action> </package>
3)在web.xml文件中配置Spring监听器
<!-- 配置Spring的ContextLoaderListener监听器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
4)测试
http://localhost:8080/shop/testAction_test.action