手把手教你如何玩转SSH(Spring+Strus2+Hibernate)

来源:互联网 发布:linux系统磁盘分区 编辑:程序博客网 时间:2024/05/16 06:40

一:ssh三大框架整合的理论


二:导包(非常重要哦,一共41个)

首先:Hibernate包


其次 struts包:



最后就是最复杂的spring包


PS:如果开发环境是用的Eclipse,那么还需要导入下面的包(用的MyEclipse的就不需要导入)


三:单独配置spring容器到web项目中


其中的配置spring随项目启动是在web.xml文件中(在我之前的文章中又详细介绍过)

<!-- 让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>

四:单独配置struts2到web项目中

步骤:(1)配置struts2的配置文件

<?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><package name="crm" namespace="/" extends="struts-default"><action name="UserAction_*" class="hnu.scw.UserAction" method="{1}"><result name="success">/success.jsp</result></action></package></struts>

(2)在web.xml文件中配置struts2的核心过滤器

 <!-- 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>

五:spring与struts2的整合

步骤:(1)导包(按照我之前的步骤的话,就不需要导入了)

(2)struts.xml文件中配置常量

<!-- #  struts.objectFactory = spring将action的创建交给spring容器struts.objectFactory.spring.autoWire = name spring负责装配Action依赖属性--><constant name="struts.objectFactory" value="spring"></constant>

(3)整合struts2和spring

方法一:struts2自己创建action,而spring负责组装依赖属性

<!-- 整合方案1:class属性上仍然配置action的完整类名struts2仍然创建action,由spring负责组装Action中的依赖属性 --><action name="UserAction_*" class="hnu.scw.UserAction" method="{1}" ><result name="success" >/success.jsp</result></action>

PS:不推荐使用这种方法,因为最好由spring完整管理action生命周期,spring的功能才能运用到action中。

方法二:

<!-- 整合方案2:class属性上填写spring中action对象的BeanName完全由spring管理action生命周期,包括Action的创建注意:需要手动组装依赖属性--><action name="UserAction_*" class="userAction" method="{1}" ><result name="success" >/success.jsp</result></action>

其中的spring.xml中的文件配置是这样的。(注意:其中的UserAction就是一个action类,没什么特别的地方,其中的userDao也是一个操作service接口实现类而已)

        <!-- service --><!-- action --><!-- 注意:Action对象作用范围一定是多例的.这样才符合struts2架构 --><bean name="userAction" class="cn.itcast.web.action.UserAction" scope="prototype" ><property name="userService" ref="userService" ></property></bean><!-- service --><bean name="userService" class="cn.itcast.service.impl.UserServiceImpl" ></bean>

好了,贴一下Action中的代码吧。

import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;import cn.itcast.domain.User;import cn.itcast.service.UserService;public class UserAction extends ActionSupport implements ModelDriven<User> {private UserService userService ;public void setUserService(UserService userService) {this.userService = userService;}public String login() throws Exception {system.out.prinln(userService)return super.excute();}}

六:单独配置Hibernate到web项目

步骤:(1)导包(前面已经导入过了)

(2)编写实体对象类,比如UserBean这样的对象类

(3)编写主配置文件hibernate.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> <!-- 数据库url --><property name="hibernate.connection.url">jdbc:mysql:///crm_32</property> <!-- 数据库连接用户名 --><property name="hibernate.connection.username">root</property> <!-- 数据库连接密码 --><property name="hibernate.connection.password">1234</property><!-- 数据库方言注意: MYSQL在选择方言时,请选择最短的方言. --><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><!-- 将hibernate生成的sql语句打印到控制台 --><property name="hibernate.show_sql">true</property><!-- 将hibernate生成的sql语句格式化(语法缩进) --><property name="hibernate.format_sql">true</property><!-- 自动导出表结构. 自动建表 --><property name="hibernate.hbm2ddl.auto">update</property></session-factory></hibernate-configuration>

(4)编写对应的实体配置orm文件,比如User.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 package="cn.itcast.domain" ><class name="User" table="sys_user" ><id name="user_id"  ><generator class="native"></generator></id><property name="user_code"  ></property><property name="user_name"  ></property><property name="user_password"  ></property><property name="user_state"  ></property></class></hibernate-mapping>

(5)hibernate.xm文件添加引入实体配置引用文件

<!-- 引入实体配置文件 --><mapping resource="cn/itcast/domain/User.hbm.xml" />

(6)编写测试Hibernate环境是否搭建成功,当然如果很熟的话,这一步可以不要,但是建议在每个框架都搭完的时候都进行测试一下

package hnu.scw.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Test;import hnu.scw.bean.User;public class HibernateTest {@Testpublic void fun1(){Configuration configuration = new Configuration().configure();SessionFactory sf = configuration.buildSessionFactory();Session session = sf.openSession();Transaction tc = session.beginTransaction();//---------操作User user = new User();user.setUser_code("scw");user.setUser_name("汤姆");user.setUser_password("123");session.save(user);tc.commit();session.close();sf.close();}}

七:spring结合Hibernate

整合原理:将sessionFactory配置到spring容器中

步骤:(1)配置spring.xml文件中获取sessionFactory的获取

方法一:(了解,不推荐)

<!-- 将SessionFactory配置到spring容器中 --><!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 --> <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" ><property name="configLocation" value="classpath:hibernate.cfg.xml" ></property></bean> 

方法二:(掌握)

!-- 加载配置方案2:在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:///crm_32</prop><prop key="hibernate.connection.username" >root</prop><prop key="hibernate.connection.password" >1234</prop> <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></props></property><!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 --><property name="mappingDirectoryLocations" value="classpath:cn/itcast/domain" ></property></bean>

测试上面的结合代码:

package hnu.scw.test;import javax.annotation.Resource;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import hnu.scw.bean.User;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class HibernateTest {@Resource(name="sessionFactory")private SessionFactory sessionFactory ;@Testpublic void fun2(){Session session = sessionFactory.openSession();Transaction tc = session.beginTransaction();//---------操作User user = new User();user.setUser_code("wyd");user.setUser_name("王耀东");user.setUser_password("123456789");session.save(user);tc.commit();session.close();}}

八:spring整合c3p0连接池

步骤:(1)编写配置文件properties

(2)编写applicationContext.xml文件(注意与上面代码的差别,通过这样的方式省很多代码,因为通过properties文件来进行获取了数据库的具体配置)

1)引入连接池

<!-- 读取db.properties文件 --><context:property-placeholder location="classpath:db.properties" /><!-- 配置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>

2)将连接池注入到sessionFactory中(对比与上面的一个知识点中的配置的差别

<!-- 加载配置方案2:在spring配置中放置hibernate配置信息 --><bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" ><!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 --><property name="dataSource" ref="dataSource" ></property><!-- 配置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></props></property><!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 --><property name="mappingDirectoryLocations" value="classpath:cn/itcast/domain" ></property></bean>

九:spring整合Hibernate模版进行操作数据库

比如,Dao层接口代码:

package hnu.scw.dao;import hnu.scw.bean.User;public interface UserDao {User getUserByUsername(String namecode);}

Dao层实现层:(必须继承HibernateDaoSupport):这里的实现用了HQL语句和Criteria两种方法。PS:记住HibernateCallback和HibernateDaoSupport的版本要对应所用的Hibernate版本

package hnu.scw.imp;import java.sql.SQLException;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.criterion.DetachedCriteria;import org.hibernate.criterion.Restrictions;import org.springframework.orm.hibernate5.HibernateCallback;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import hnu.scw.bean.User;import hnu.scw.dao.UserDao;public class UserDaoImp extends HibernateDaoSupport implements UserDao {@Overridepublic User getUserByUsername(final String namecode) {//操作数据库,这里用一个例子来做代表,并且用两种方法来实现数据库的查询操作//方法一:HQL/*return getHibernateTemplate().execute(new HibernateCallback<User>() {@Overridepublic User doInHibernate(Session session) throws HibernateException, SQLException {String hql = "from User where user_code = ?";Query query = session.createQuery(hql);query.setParameter(0, namecode);User user = (User) query.uniqueResult();return user;}});*///方法二:CriteriaDetachedCriteria dc  = DetachedCriteria.forClass(User.class);dc.add(Restrictions.eq("user_code" , namecode));List<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc);if(list != null && list.size() >0){return list.get(0);}else{return null;}}}

配置applicationContext.xml文件(增加DaoImp层的Bean节点)

<bean name="userDao" class="hnu.scw.imp.UserDaoImp" ><!-- 注入sessionFactory --><property name="sessionFactory" ref="sessionFactory" ></property></bean>

十:整合AOP事务

方法一:通过application.xml配置

<!-- 配置核心事务管理器 --><bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 配置通知 --><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(* hnu.scw.imp.*ServiceImp.*(..))" id="txPc"/><aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" /></aop:config> 

方法二:注解配置(在application中加入下面代码)

<tx:annotation-driven transaction-manager="transactionManager"/>

然后在对应的service实现类中进行设置隔离级别,是否只读和传播属性(这个在我前面的文章中已经有详细讲解过)

比如:

(1)可以在方法中使用

@Transactional(isolation=Isolation.REPEATABLE_READ, readOnly=false, propagation=Propagation.REQUIRED)@Overridepublic void saveUser(User user) {userDao.saveUser(user);}

(2)可以直接设置在类上

@Transactional(isolation=Isolation.REPEATABLE_READ, readOnly=true, propagation=Propagation.REQUIRED)public class UserServiceImp implements UserService {

十一:扩大session的作用范围(为了避免在进行懒加载的过程时候,出现session问题)

步骤:web.xml中配置

<!-- 扩大session作用范围  注意: 任何filter一定要在struts的filter之前调用   -->   <filter>   <filter-name>openSessionInView</filter-name>   <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>   </filter>  <filter-mapping>  <filter-name>openSessionInView</filter-name>  <url-pattern>/*</url-pattern>  </filter-mapping>

      这上面就是三大框架的结合的流程,一把可以分为这11步来进行,而且最好是做完一步就测试一下,当熟练之后,就可以很流畅的书写了,加油,刚刚将整个内容一起整合起来可能会有点混乱,但是慢慢慢熟悉就好了的。如果对其中的框架某个部分有不了解的,可以查看我之前的文章,都对每个框架进行了非常详细的知识点介绍。。