SSH2搭建篇03——spring

来源:互联网 发布:淘宝16年扣24分 编辑:程序博客网 时间:2024/06/05 04:25

前二篇主要讲了struts2 SSH2搭建篇01——strusts2和hibernate SSH2搭建篇02——hibernate 

这篇主要将spring3 如何将struts2 和hibernate 集成进来  前面2个一般都简单,主要会出现问题就是如何把spring配置进去了

首先把spring3.1的jar导进去,还需要

aopalliance.jar    

aspectj.jar    

aspectjweaver.jar    

cglib/cglib-nodep-.jar    

commons-pool.jar    

commons-dbcp.jar    

commons-logging.jar  
应该就这些,具体可以看源码,在第一篇有源码下载地址

1:在 配置spring的applicationContext.xml前,在web.xml中加入spring的listener

<!-- Spring configuration -->      <context-param>          <param-name>contextConfigLocation</param-name>          <param-value>        classpath:applicationContext.xml        </param-value>      </context-param>      <!-- spring加载 -->      <listener>          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      </listener>

一般还有spring的字符过滤器

<!-- 字符集过滤 -->      <filter>          <filter-name>SetCharacterEncoding</filter-name>          <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>          <init-param>              <param-name>encoding</param-name>              <param-value>UTF-8</param-value>          </init-param>      </filter>        <!-- 要过滤得类型 -->      <filter-mapping>          <filter-name>SetCharacterEncoding</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping> 

还有一个是Spring封装hibernate后提供的一个过滤器

   <!-- 这是Spring封装hibernate后提供的一个过滤器,这个过滤器的作用是:每一次请求来的时候都打开一个session每次请求结束后关闭session,解析hibernat延迟加载产生的异常。-->    <filter>    <filter-name>hibernateFilter</filter-name>        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class></filter>

2:spring的applicationContext-hibernate.xml和applicationContext.xml (这些配置文件都是在src根路径下的)先上代码

applicationContext-hibernate.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:aop="http://www.springframework.org/schema/aop"      xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"      xsi:schemaLocation="http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-3.0.xsd             http://www.springframework.org/schema/tx             http://www.springframework.org/schema/tx/spring-tx-3.0.xsd             http://www.springframework.org/schema/aop             http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">             <bean id="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">          <property name="location">              <value>classpath:jdbc.properties</value>          </property>      </bean>      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">          <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />          <property name="url" value="${db.url}" />          <property name="username" value="${db.username}" />          <property name="password" value="${db.password}" />        <property name="defaultAutoCommit" value="false" /><property name="maxActive" value="150" />        <property name="maxIdle" value="100" />        <property name="maxWait" value="60000" />        <property name="minIdle"  value="5" />        <property name="testOnBorrow" value="true"/>        <property name="testWhileIdle" value="true"/>         <property name="validationQuery" value="select 1 from dual" />      </bean>      <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">          <property name="dataSource" ref="dataSource" />          <property name="hibernateProperties">              <props>                 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>                              <prop key="hibernate.show_sql">true</prop>                  <prop key="hibernate.autoReconnect">true</prop>                 <prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>            </props>          </property>          <property name="mappingResources">              <list>                  <value>com/yeshun/bean/User.hbm.xml</value>              </list>          </property>      </bean>          <!--jdbcTemplate--><bean id="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource" /></bean><!--dao--><bean id="baseDAO" class="com.yeshun.dao.impl.BaseDAOImpl"abstract="true"><property name="sessionFactory" ref="sessionFactory" /><property name="jdbcTemplate" ref="jdbcTemplate" /></bean></beans>
jdbc.properties
db.driverClassName=oracle.jdbc.driver.OracleDriverdb.url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:ORCLdb.username=scottdb.password=tiger

第一个是配置dataSource 要注意这个class

org.springframework.jdbc.datasource.DriverManagerDataSource  这个是spring提供的,建立连接是只要有连接就新建一个connection,根本没有连接池的作用

要使用org.apache.commons.dbcp.BasicDataSource  或者com.mchange.v2.c3p0.ComboPooledDataSource (我在这个class上出现过问题在博客上也有)


第二个是配置hibernate的sessionFactory,<property name="hibernateProperties"> 这个是一些配置可以看这篇SSH2框架Hibernate一些配置
<property name="mappingResources">   下放对应bean的hibernate配置文件

jdbcTemplate      spring提供的底层jdbc类 (最好只做查询,在查资料是看到的,做增删改可能会破坏hibernate的一级缓存)

baseDAO 做一个公共的dao继承HibernateDaoSupport ,让别的dao都继承baseDAO   方便!!!


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:aop="http://www.springframework.org/schema/aop"      xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"      xsi:schemaLocation="http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-3.0.xsd             http://www.springframework.org/schema/tx             http://www.springframework.org/schema/tx/spring-tx-3.0.xsd             http://www.springframework.org/schema/aop             http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  <!-- Hibernate configuration --><import resource="classpath:applicationContext-hibernate.xml" /><!-- 定义事务管理器 --> <bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean><tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="get*" propagation="REQUIRED" read-only="true" />            <tx:method name="find*" propagation="REQUIRED" read-only="true" />            <tx:method name="list*" propagation="REQUIRED" read-only="true" />            <tx:method name="load*" propagation="REQUIRED" read-only="true" />            <tx:method name="save*" propagation="REQUIRED" rollback-for="Exception"/>            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>            <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>            <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>    <!-- 其他方法使用默认的事务设置 -->            <tx:method name="*" propagation="REQUIRED"/>        </tx:attributes>    </tx:advice>       <aop:config>        <aop:pointcut id="aopPointcut"            expression="execution(* com.yeshun.service.impl.*Impl.*(..))" />        <aop:advisor advice-ref="txAdvice"            pointcut-ref="aopPointcut" />           </aop:config>         <bean id="userDao" class="com.yeshun.dao.impl.UserDaoImpl" parent="baseDAO" />            <bean id="userService" class="com.yeshun.service.impl.UserServiceImpl"><property name="userDao" ref="userDao" /></bean>       <!-- struts beans -->      <bean id="LoginAction" class="com.yeshun.action.LoginAction" scope="prototype">          <property name="userService" ref="userService" />      </bean>      </beans>  

这里主要是将applicationContext-hibernate.xml  加入进来,还有就是配置spring事务,这里不做介绍,可以看 五种Spring事务的配置方式

还有bean的配置  主要看下action的   scope="prototype"  这属性

spring默认scope是单例模式,这样只会创建一个action,每次访问都是同一个action对象,数据不安全,而struts2是线程安全的,要求每次访问都对应不同的action

scope="prototype"  可以保证spring在每次访问的时候都创建一个新的对象


然后我们来看一下 dao service action的代码

package com.yeshun.dao;import java.io.Serializable;import java.sql.SQLException;/** * @author yeshun */public interface BaseDao {Object getObject(Class clazz, Serializable id);Object saveObject(Object obj) throws RuntimeException, SQLException;void updateObject(Object obj) throws RuntimeException, SQLException;void deleteObject(Object obj) throws RuntimeException, SQLException;Object removeObject(Class clazz, Serializable id) throws RuntimeException, SQLException;java.util.List getAll(Class clazz);public void saveOrUpdate(Object obj) throws RuntimeException, SQLException;}

package com.yeshun.dao.impl;import java.io.Serializable;import java.sql.SQLException;import java.util.List;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.yeshun.dao.BaseDao;/** * @author yeshun */public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {protected JdbcTemplate jdbcTemplate;public JdbcTemplate getJdbcTemplate() {return jdbcTemplate;}public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}public Object getObject(Class clazz, Serializable id) {return getHibernateTemplate().load(clazz.getName(), id);}public Object saveObject(Object obj) throws RuntimeException, SQLException{return getHibernateTemplate().save(obj);}public void updateObject(Object obj) throws RuntimeException, SQLException{getHibernateTemplate().update(obj);}    public void saveOrUpdate(Object obj) throws RuntimeException, SQLException{    getHibernateTemplate().saveOrUpdate(obj);}public void deleteObject(Object obj) throws RuntimeException, SQLException{this.getHibernateTemplate().delete(obj);}public Object removeObject(Class clazz, Serializable id) throws RuntimeException, SQLException{// TODO Auto-generated method stubObject obj = this.getObject(clazz, id);if(obj!=null)deleteObject(obj);return obj;}public java.util.List getAll(Class clazz) {List list=getHibernateTemplate().loadAll(clazz);return list;}}
BaseDaoImpl 中实现了一些基础对象的增删改查,有没有发现dao里面没有sessionFactory ,那是因为继承了HibernateDaoSupport  有2个好处

第一 继承了HibernateDaoSupport类的类获取session时,已不可用SessionFactory.OpenSessioon的形式来获取Session了,由于HibernateDaoSupport本身已有获取session的方法getSession(),所以直接用Session se=this.getSession();来获取

第二 在依据hql获取用户信息时,继承了HibernateDaoSupport类的类中不能在使用Query类了,而是用List<Ssh> list = this.getHibernateTemplate().find(hql);形式来获取实体类集合


package com.yeshun.dao;import java.util.List;import com.yeshun.bean.User;public interface UserDao {public List<User> findAllUser();public void saveUser(User user);}


package com.yeshun.dao.impl;import java.sql.SQLException;import java.util.List;import org.hibernate.Query;import com.yeshun.bean.User;import com.yeshun.dao.UserDao;public class UserDaoImpl extends BaseDaoImpl implements UserDao{public List<User> findAllUser() {return this.getAll(User.class);/*String hql = "from User where 1 = 1";          Query query = getSession().createQuery(hql);          List<User> list = (List) query.list();  return list;*/}public void saveUser(User user) {// TODO Auto-generated method stubtry {this.saveObject(user);} catch (RuntimeException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

package com.yeshun.service;import java.util.List;import com.yeshun.bean.User;public interface UserService {public List<User> findAllUser();public void saveUser(User user);}

package com.yeshun.service.impl;import java.util.List;import com.yeshun.bean.User;import com.yeshun.dao.UserDao;import com.yeshun.service.UserService;public class UserServiceImpl implements UserService{private UserDao userDao;public UserDao getUserDao() {return userDao;}public void setUserDao(UserDao userDao) {this.userDao = userDao;}public List<User> findAllUser() {// TODO Auto-generated method stubreturn userDao.findAllUser();}public void saveUser(User user) {// TODO Auto-generated method stubuserDao.saveUser(user);}}


创建一个BaseAction 让别的action都继承它方便管理action 

package com.yeshun.action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.struts2.interceptor.ServletRequestAware;import org.apache.struts2.interceptor.ServletResponseAware;import com.opensymphony.xwork2.ActionSupport;import com.yeshun.util.BasePath;public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware {private static final long serialVersionUID = 1L;protected HttpServletRequest request;protected HttpServletResponse response;protected BasePath basePath;protected final Log log = LogFactory.getLog(getClass());public void setServletRequest(HttpServletRequest request) {this.request = request;}public void setServletResponse(HttpServletResponse response) {this.response = response;}public BasePath getBasePath() {this.basePath = new BasePath(request);return basePath;}}


package com.yeshun.action;import java.util.List;import com.yeshun.bean.User;import com.yeshun.service.UserService;public class LoginAction extends BaseAction {private static final long serialVersionUID = 1L;private String username;private String password;private UserService userService;public String login(){System.out.println(username+" -  "+password);if("admin".equals(username) && "123456".equals(password)){User user = new User();user.setUsername(username);user.setPassword(password);request.getSession().setAttribute("user", user);List<User> list = userService.findAllUser();for (User u : list) {System.out.println(u.getUsername());}//userService.saveUser(user);return SUCCESS;}else{request.setAttribute("msg", "用户名或密码错误!");}return LOGIN;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public UserService getUserService() {return userService;}public void setUserService(UserService userService) {this.userService = userService;}}

好了,然后就跑项目吧! 


总的来说SSH2 应该算是配置好了,有更好的欢迎来指导,不好的地方请指出,一起学习!!!


原创粉丝点击