谁能给个SSH整合过程谢谢

解决方案 »

  1.   

    首先:先给你个文档,具体操作在下面:

    WEB.XML
    <?xml version="1.0" encoding="UTF-8"?>
    <?XML:NAMESPACE PREFIX = [default] http://www.springframework.org/schema/beans NS = "http://www.springframework.org/schema/beans" /><web-app xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee &#13;&#10;&#9;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5">
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      
       <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    <!-- default: /WEB-INF/applicationContext.xml -->
    </listener> <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
    </context-param>
      
      
      <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></web-app>
      

  2.   

    beans.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <?XML:NAMESPACE PREFIX = [default] http://www.springframework.org/schema/beans NS = "http://www.springframework.org/schema/beans" /><beans xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans&#13;&#10;           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&#13;&#10;           http://www.springframework.org/schema/context&#13;&#10;           http://www.springframework.org/schema/context/spring-context-2.5.xsd&#13;&#10;           http://www.springframework.org/schema/aop&#13;&#10;           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd&#13;&#10;           http://www.springframework.org/schema/tx&#13;&#10;            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd&#13;&#10;           &#13;&#10;           " xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <CONTEXT:ANNOTATION-CONFIG />
    <CONTEXT:COMPONENT-SCAN base-package="wtl" /><bean class=org.springframework.beans.factory.config.PropertyPlaceholderConfigurer>
    <property name="locations">
    <value>classpath:jdbc.properties</value>
    </property>
    </bean> <bean id=dataSource class=org.apache.commons.dbcp.BasicDataSource destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
    </bean><bean id=sessionFactory class=org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean>
    <property name="dataSource" ref="dataSource"></property>
    <property name="annotatedClasses">
    <list>
    <value>wtl.model.User</value>
    </list>
    </property>

    <property name="hibernateProperties">
    <props>
    <prop key="hibernate.dialect">
    org.hibernate.dialect.MySQLDialect
    </prop>
    <prop key="hibernate.show_sql">true</prop>
    </props>
    </property>
    </bean><bean id=txManager class=org.springframework.orm.hibernate3.HibernateTransactionManager>
      <property name="sessionFactory" ref="sessionFactory"></property>
    </bean><TX:ANNOTATION-DRIVEN transaction-manager="txManager" />
    <bean id=hibernateTemplate class=org.springframework.orm.hibernate3.HibernateTemplate><property name="sessionFactory">
    <ref bean="sessionFactory"></ref>
    </property>
    </bean>
    <AOP:CONFIG>
    <AOP:POINTCUT id=bussinessService expression="execution(public * wtl.service.*.*(..))" />
    <AOP:ADVISOR advice-ref="txAdvice" pointcut-ref="bussinessService" />
    </AOP:CONFIG> <TX:ADVICE id=txAdvice transaction-manager="txManager">
    <TX:ATTRIBUTES>
    <TX:METHOD name="exists" read-only="true" />
    <TX:METHOD name="save" propagation="REQUIRED" />
    </TX:ATTRIBUTES>
    </TX:ADVICE>
    </beans>
      

  3.   

    jdbc.propertiesjdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/hibernate
    jdbc.username=root
    jdbc.password=00user
    package wtl.model;import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;@Entity
    public class User {
    private  int id;
    private  String name;
    private String password;
    @Id
    @GeneratedValue
    public int getId() {
    return id;
    }
    public void setId(int id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public String getPassword() {
    return password;
    }
    public void setPassword(String password) {
    this.password = password;
    }




    }
    UserManagerImpl
    package wtl.service_imp;
    import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Component;import wtl.dao.UserDao;
    import wtl.model.User;
    import wtl.service.UserManager;@Component("userManager")
    public class UserManagerImp implements UserManager {
    private  UserDao userDao ;
    @Override
    public boolean exits(User user) {
    return userDao.exits(user);
    } @Override
    public void save(User user) {
    userDao.save(user);
    } public UserDao getUserDao() {
    return userDao;
    }
    @Resource
    public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
    }@Override
    public List<USER> getUsers() {

    return this.userDao.getUsers();
    }

    }
    re test
    import java.util.List;import org.junit.Assert;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;import wtl.action.UserAction;
    import wtl.model.User;
    public class test { @Test
    public void testList() {

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
    UserAction userAction = (UserAction) applicationContext.getBean("user");
    userAction.list();
    List<USER> list= userAction.getUsers(); System.out.println(list.size());

    Assert.assertTrue(list.size()>0);

    }
    }
      

  4.   

    课程内容
    1. 面向接口(抽象)编程的概念与好处
    2. IOC/DI的概念与好处
    a) inversion of control
    b) dependency injection
    3. AOP的概念与好处
    4. Spring简介
    5. Spring应用IOC/DI(重要)
    a) xml
    b) annotation
    6. Spring应用AOP(重要)
    a) xml
    b) annotation
    7. Struts2.1.6 + Spring2.5.6 + Hibernate3.3.2整合(重要)
    a) opensessionInviewfilter(记住,解决什么问题,怎么解决)
    8. Spring JDBC
    面向接口编程(面向抽象编程)
    1. 场景:用户添加
    2. Spring_0100_AbstractOrientedProgramming
    a) 不是AOP:Aspect Oriented Programming
    3. 好处:灵活
    什么是IOC(DI),有什么好处
    1. 把自己new的东西改为由容器提供
    a) 初始化具体值
    b) 装配
    2. 好处:灵活装配
    Spring简介
    1. 项目名称:Spring_0200_IOC_Introduction
    2. 环境搭建
    a) 只用IOC
    i. spring.jar , jarkata-commons/commons-loggin.jar
    3. IOC容器
    a) 实例化具体bean
    b) 动态装配
    4. AOP支持
    a) 安全检查
    b) 管理transaction
    Spring IOC配置与应用
    1. FAQ:不给提示:
    a) window – preferences – myeclipse – xml – xml catalog
    b) User Specified Entries – add
    i. Location: D:\share\0900_Spring\soft\spring-framework-2.5.6\dist\resources\spring-beans-2.5.xsd
    ii. URI:    file:///D:/share/0900_Spring/soft/spring-framework-2.5.6/dist/resources/spring-beans-2.5.xsd
    iii. Key Type: Schema Location
    iv. Key: http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    2. 注入类型
    a) Spring_0300_IOC_Injection_Type
    b) setter(重要)
    c) 构造方法(可以忘记)
    d) 接口注入(可以忘记)
    3. id vs. name
    a) Spring_0400_IOC_Id_Name
    b) name可以用特殊字符
    4. 简单属性的注入
    a) Spring_0500_IOC_SimpleProperty
    b) <property name=… value=….>
    5. <bean 中的scope属性
    a) Spring_0600_IOC_Bean_Scope
    b) singleton 单例
    c) proptotype 每次创建新的对象
    6. 集合注入
    a) Spring_0700_IOC_Collections
    b) 很少用,不重要!参考程序
    7. 自动装配
    a) Spring_0800_IOC_AutoWire
    b) byName
    c) byType
    d) 如果所有的bean都用同一种,可以使用beans的属性:default-autowire
    8. 生命周期
    a) Spring_0900_IOC_Life_Cycle
    b) lazy-init (不重要) : 容易在初始化的时候不装入容器,用到时才装入
    c) init-method destroy-methd 不要和prototype一起用(了解)
    9. Annotation第一步:
    a) 修改xml文件,参考文档<context:annotation-config />
    10. @Autowired
    a) 默认按类型by type
    b) 如果想用byName,使用@Qulifier
    c) 写在private field(第三种注入形式)(不建议,破坏封装)
    d) 如果写在set上,@qualifier需要写在参数上
    11. @Resource(重要)
    a) 加入:j2ee/common-annotations.jar
    b) 默认按名称,名称找不到,按类型
    c) 可以指定特定名称
    d) 推荐使用
    e) 不足:如果没有源码,就无法运用annotation,只能使用xml
    12. @Component @Service @Controller @Repository
    a) 初始化的名字默认为类名首字母小写
    b) 可以指定初始化bean的名字
    13. @Scope
    14. @PostConstruct = init-method; @PreDestroy = destroy-method;什么是AOP
    1. 面向切面编程Aspect-Oriented-Programming
    a) 是对面向对象的思维方式的有力补充
    2. Spring_1400_AOP_Introduction
    3. 好处:可以动态的添加和删除在切面上的逻辑而不影响原来的执行代码
    a) Filter
    b) Struts2的interceptor
    c) Jsp权限的检查
    d) 事务的管理
    4. 概念:
    a) JoinPoint
    b) PointCut
    c) Aspect(切面)
    d) Advice
    e) Target被加入对象
    f) Weave织入
    Spring AOP配置与应用
    1. 两种方式:
    a) 使用Annotation
    b) 使用xml
    2. Annotation
    a) 加上对应的xsd文件spring-aop.xsd
    b) beans.xml <aop:aspectj-autoproxy />
    c) 此时就可以解析对应的Annotation了
    d) 建立我们的拦截类
    e) 用@Aspect注解这个类
    f) 建立处理方法
    g) 用@Before来注解方法
    h) 写明白切入点(execution …….)
    i) 让spring对我们的拦截器类进行管理@Component
    3. 常见的Annotation:
    a) @Pointcut
    b) @Before
    c) @AfterReturning
    d) @AfterThrowing
    e) @After
    f) @Around
    4. 织入点语法
    a) void !void
    b) 参考文档(* ..)
    5. xml配置AOP
    a) 把interceptor对象初始化
    b) <aop:config
    i. <aop:aspect …..
    1. <aop:pointcut
    2. <aop:before
    Spring整合Hibernate
    1. Spring 指定datasource
    a) 参考文档,找dbcp.BasicDataSource
    i. c3p0
    ii. dbcp: database connection pool
    iii. proxool
    b) 在DAO或者Service中注入dataSource
    c) 在Spring中可以使用PropertyPlaceHolderConfigure来读取Properties文件的内容
    2. Spring整合Hibernate
    a) <bean .. AnnotationSessionFactoryBean>
    i. <property dataSource
    ii. <annotatedClasses
    b) 引入hibernate 系列jar包
    c) User上加Annotation
    d) UserDAO或者UserServie 注入SessionFactory
    e) jar包问题一个一个解决
    3. 声明式的事务管理
    a) 事务加在DAO层还是Service层?
    b) annotation
    i. 加入annotation.xsd
    ii. 加入txManager bean
    iii. <tx:annotation-driven
    iv. 在需要事务的方法上加:@Transactional
    v. 需要注意,使用SessionFactory.getCurrentSession 不要使用OpenSession
    c) @Transactional详解
    Readonly =true , 当确定里面没有数据更新,只是读取的时候,可以这样设,可以提高一些效率
    i. 什么时候rollback 
    1. 运行期异常,非运行期异常不会触发rollback
    2. 必须uncheck (没有catch)
    3. 不管什么异常,只要你catch了,spring就会放弃管理
    4. 事务传播特性:propagation_required
    5. read_only
    d) xml(推荐,可以同时配置好多方法)
    i. <bean txmanager
    ii. <aop:config 
    1. <aop:pointcut
    2. <aop:advisor pointcut-ref advice-ref
    iii. <tx:advice: id transaction-manager = 
    e) HibernateTemplate、HibernateCallback、HibernateDaoSupport(不重要)介绍
    i. 设计模式:Template Method
    ii. Callback:回调/钩子函数
    iii. 第一种:(建议)
    1. 在spring中初始化HibernateTemplate,注入sessionFactory
    2. DAO里注入HibernateTemplate
    3. save写getHibernateTemplate.save();
    iv. 第二种:
    1. 从HibernateDaoSupport继承
    2. 必须写在xml文件中,无法使用Annotation,因为set方法在父类中,而且是final的
    f) spring整合hibernate的时候使用packagesToScan属性,可以让spring自动扫描对应包下面的实体类
    Struts2.1.6 + Spring2.5.6 + Hibernate3.3.2
    1. 需要的jar包列表
    jar包名称 所在位置 说明
    antlr-2.7.6.jar hibernate/lib/required 解析HQL
    aspectjrt spring/lib/aspectj AOP
    aspectjweaver .. AOP
    cglib-nodep-2.1_3.jar spring/lib/cglib 代理,二进制增强
    common-annotations.jar spring/lib/j2ee @Resource
    commons-collections-3.1.jar hibernate/lib/required 集合框架
    commons-fileupload-1.2.1.jar struts/lib struts
    commons-io-1.3.2 struts/lib struts
    commons-logging-1.1.1 单独下载,删除1.0.4(struts/lib) struts
    spring
    dom4j-1.6.1.jar hibernate/required 解析xml
    ejb3-persistence hibernate-annotation/lib @Entity
    freeer-2.3.13 struts/lib struts
    hibernate3.jar hibernate
    hibernate-annotations hibernate-annotation/
    hibernate-common-annotations hibernate-annotation/lib
    javassist-3.9.0.GA.jar hiberante/lib/required hibernate
    jta-1.1.jar .. hibernate transaction
    junit4.5
    mysql-
    ognl-2.6.11.jar struts/lib
    slf4j-api-1.5.8.jar hibernate/lib/required hibernate-log
    slf4j-nop-1.5.8.jar hibernate/lib/required
    spring.jar spring/dist
    struts2-core-2.1.6.jar struts/lib
    xwork-2.1.2.jar struts/lib struts2
    commons-dbcp spring/lib/jarkata-commons
    commons-pool.jar ..
    struts2-spring-plugin-2.1.6.jar struts/lib
    2. BestPractice:
    a) 将这些所有的jar包保存到一个位置,使用的时候直接copy
    3. 步骤
    a) 加入jar包
    b) 首先整合Spring + Hibernate
    i. 建立对应的package
    1. dao / dao.impl / model / service / service.impl/ test
    ii. 建立对应的接口与类框架
    1. S2SH_01
    iii. 建立spring的配置文件(建议自己保留一份经常使用的配置文件,以后用到的时候直接copy改)
    iv. 建立数据库
    v. 加入Hibernate注解
    1. 在实体类上加相应注解@Entity @Id等
    2. 在beans配置文件配置对应的实体类,使之受管
    vi. 写dao service的实现
    vii. 加入Spring注解
    1. 在对应Service及DAO实现中加入@Component,让spring对其初始化
    2. 在Service上加入@Transactional或者使用xml方式(此处建议后者,因为更简单)
    3. 在DAO中注入sessionFactory
    4. 在Service中注入DAO
    5. 写DAO与Service的实现
    viii. 写测试
    c) 整合Struts2
    i. 结合点:Struts2的Action由Spring产生
    ii. 步骤:
    1. 修改web.xml加入 struts的filter
    2. 再加入spring的listener,这样的话,webapp一旦启动,spring容器就初始化了
    3. 规划struts的action和jsp展现
    4. 加入struts.xml
    a) 修改配置,由spring替代struts产生Action对象
    5. 修改action配置
    a) 把类名改为bean对象的名称,这个时候就可以使用首字母小写了
    b) @Scope(“prototype”)不要忘记
    iii. struts的读常量:
    1. struts-default.xml 
    2. struts-plugin.xml
    3. struts.xml
    4. struts.properties
    5. web.xml
    iv. 中文问题:
    1. Struts2.1.8已经修正,只需要改i18n.encoding = gbk
    2. 使用spring的characterencoding
    3. 需要严格注意filter的顺序
    4. 需要加到Struts2的filter前面
    v. LazyInitializationException
    1. OpenSessionInViewFilter
    2. 需要严格顺序问题
    3. 需要加到struts2的filter前面
    Suspend挂起1. 我感觉,superdao(里面注入了hibernatetemplate)  可以继承actionsupport,那样就可以符合struts了:::好像不大行啊
    2. DTO  data transfer object :传输数据用的
    3. Vo   value object
    设计的2大任务
    1. 界面原型,确定需求分析
    2. 确定实体类Model,数据库表
    3<filter>
    <filter-name>opensessionInView</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    </filter-class>
    </filter>
    在beans.xml里没有配事务边境的时候, 此filter将它得到的每个session设置为readonly,所有不能保存数据库
    4自学ingcontexttest
    5: action 有两个产生方式:struts、spring
    1. Struts时不用配@omponent,属性也不用配,会自动注入]
    2. Spring时:@Component("user") @Scope("prototype")都要配上,且struts 的配置里,class=“user”即:@Component("user")里的名字
    3.
      

  5.   

    package com.testingonline.dao.iface;import java.io.Serializable;/**
     * An interface shared by all business data access objects.
     * <P>
     * All CRUD (create, read, update, delete) basic data access operations are
     * isolated in this interface and shared across all DAO implementations.
     *
     */
    public interface IGenericDAO<?XML:NAMESPACE PREFIX = [default] http://www.springframework.org/schema/beans NS = "http://www.springframework.org/schema/beans" /><T, extends Serializable> {    /**
         * Tries to get an instance of the object 
         * @param id the id to search for
         * @return the requested instance, or <CODE>null</CODE> if not found
         */
        public T get(ID id);
        
        /**
         * Adds a new instance of the object
         * @param entity the instance to save
         */
        public void save(T entity);
        
        /**
         * Deletes the object
         * @param entity the object to delete
         */
        public void delete(T entity);
        
        /**
         * Updates the information of an existing object
         * @param entity the instance to update
         */
        public void update(T entity);}package com.testingonline.dao.impl;import java.lang.reflect.ParameterizedType;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import java.io.Serializable;import org.hibernate.HibernateException;
    import org.hibernate.Query;
    import org.hibernate.SQLQuery;
    import org.hibernate.Session;
    import org.springframework.dao.DataAccessException;
    import org.springframework.orm.hibernate3.HibernateCallback;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.testingonline.dao.iface.IGenericDAO;
    import com.testingonline.utils.PageBean;/**
     * Implements the generic CRUD data access operations using Hibernate.
     * <P>
     * To write a DAO, subclass and parameterize this class with your entity.
     * Of course, assuming that you have a traditional 1:1 approach for
     * Entity:DAO design. 
     *
     */
    public abstract class GenericDAOImpl<T,ID extends Serializable> 
            extends HibernateDaoSupport implements IGenericDAO<T,> {

        private Class<T> persistentClass;    @SuppressWarnings("unchecked")
        public GenericDAOImpl() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
                    .getGenericSuperclass()).getActualTypeArguments()[0];
            
        }    public Class<T> getPersistentClass() {
            return persistentClass;
        }
        
        public void save(T entity) {
            getHibernateTemplate().save(entity);
            getHibernateTemplate().flush();    }    public void update(T entity) {
            getHibernateTemplate().update(entity);
            getHibernateTemplate().flush();
        }    public void delete(T entity) {
            getHibernateTemplate().delete(entity);
            getHibernateTemplate().flush();
        }    public T get(ID id) {
            return (T) getHibernateTemplate().get(getPersistentClass(), id);
        }
        
        /**
         * 获取某一实体类的所有纪录
         */
        @SuppressWarnings("unchecked")
    protected PageBean<T> findAll(PageBean<T> page,final Class<T> clazz)throws DataAccessException{
    try{
    Query query=getSession(false).createQuery("select count(*) from "+clazz.getName());
    Integer totalRows=((Long)query.uniqueResult()).intValue();
    page.setTotalRows(totalRows);
    page.getList().clear();
    for(int i=1;i<=page.getTotalPage();i++)
    page.getList().add(i);
    query=null;
    query=getSession(false).createQuery("from "+clazz.getName());
    if(page.getPrePage()==0)
    query.setFirstResult(0);
    else
    query.setFirstResult(page.getPrePage()*page.getRowsPerPage());
    query.setMaxResults(page.getRowsPerPage());
    List<T> list=query.list();
    page.setRecords(list);
    }catch(HibernateException e){
    throw convertHibernateAccessException(e);
    }
    return page;
    }
        
        /**
         * 根据查询语句获取总记录数与总页数
         */
        @SuppressWarnings("unchecked")
    public PageBean getTotalPageNumber(PageBean page,final String queryString, final Object[] values)throws DataAccessException{
    List list = getHibernateTemplate().executeFind(new HibernateCallback(){
    public Object doInHibernate(Session session)throws HibernateException, SQLException{
    Query query = session.createQuery(queryString);
    if(null!=values){
    for (int i = 0 ; i < values.length ; i++){
    query.setParameter( i, values[i]);
    }
    }
    Integer totalRows=((Long)query.uniqueResult()).intValue();
    List rows= new ArrayList();
    rows.add(totalRows);
    return rows;
    }
    });
    page.setTotalRows((Integer)list.get(0));
    page.getList().clear();
    for(int i=1;i<=page.getTotalPage();i++)
    page.getList().add(i);
    return page;
    }
        
        /**
         *根据给定条件获取分页信息及要检索的信息 
         */
        @SuppressWarnings("unchecked")
    protected PageBean<?> findByPage(PageBean page,final String getCount,final String hql, final Object value)throws DataAccessException{
    page = getTotalPageNumber(page,getCount,new Object[]{value});
    //define variables for pagination
    final int offset=page.getBeginIndex();
    final int pageSize=page.getRowsPerPage();

    List info= getHibernateTemplate().executeFind(new HibernateCallback(){
    public Object doInHibernate(Session session)throws HibernateException, SQLException{
    Query query = session.createQuery(hql);
    query.setParameter( 0, value);
    List result = query.setFirstResult(offset).setMaxResults(pageSize).list();
    return result;
    }
    });
    page.setRecords(info);
    return page;
     }
        
        /**
         * 根据给定条件获取分页信息及要检索的信息 
         */
        @SuppressWarnings("unchecked")
    protected PageBean<?> findByPage(PageBean page,final String getCount,final String hql, final Object[] values)throws DataAccessException{
         page = getTotalPageNumber(page,getCount,values);
    final int offset=page.getPrePage()*page.getRowsPerPage(); //define variables for pagination
    final int pageSize=page.getRowsPerPage();

    List info= getHibernateTemplate().executeFind(new HibernateCallback(){
    public Object doInHibernate(Session session)throws HibernateException, SQLException{
    Query query = session.createQuery(hql);
    for (int i = 0 ; i < values.length ; i++){
    query.setParameter( i, values[i]);
    }
    List result = query.setFirstResult(offset).setMaxResults(pageSize).list();
    return result;
    }
    });
    page.setRecords(info);
    return page;
     }
        
        /**
         *使用原生SQL语句查询而非HQL 
         */
        @SuppressWarnings("unchecked")
    protected PageBean<?> findByNativeQuery(PageBean page,String getCount,String sql,Object[] values)throws DataAccessException{
    try{
    SQLQuery query=getSession(false).createSQLQuery(getCount);
    for (int i = 0 ; i < values.length ; i++){
    query.setParameter( i, values[i]);
    }
    Integer totalRows=((Integer)query.uniqueResult()).intValue();
    page.setTotalRows(totalRows);
    page.getList().clear();
    for(int i=1;i<=page.getTotalPage();i++)
    page.getList().add(i);
    query=null;

    query=getSession(false).createSQLQuery(sql);
    for (int i = 0 ; i < values.length ; i++){
    query.setParameter( i, values[i]);
    }
    if(page.getPrePage()==0)
    query.setFirstResult(0);
    else
    query.setFirstResult(page.getPrePage()*page.getRowsPerPage());
    query.setMaxResults(page.getRowsPerPage());
    List list=query.list();
    page.setRecords(list);
    }catch(HibernateException e){
    throw convertHibernateAccessException(e);
    }
    return page;
    }
    }
    </P>
      

  6.   

    先配置hibernate,然后配置struts,然后把对象管理放入spring
      

  7.   

    去百度找找吧! SSH 整合有例子的,图形文字说明! 这里面不好解释!
      

  8.   

    推荐一本书  《 java EE企业实战项目:struts+hibernate+spring》 这里有虽然有点厚 但是是学习ssh的必经之路
      

  9.   

    package com.testingonline.dao.iface;import java.util.List;import com.testingonline.entity.TbResource;
    import com.testingonline.exception.SystemException;public interface IResourceDAO extends IGenericDAO<TbResource, Integer>{ /**
         * 根据Resource类型获得resource对象集合。
         * 
         * @param type Resource type
         * @return <code>Resources</code> 对象集合
         */
    public List<TbResource> findByType(Object type);

    /**
     * 根据资源类型查找 
     */
    public List<TbResource> findByType(Object[] types);

    /**
     * 获取所有TbResource 
     */
    public List<TbResource> getAll()throws SystemException;

    /**
     * 根据资源名称查找 
     */
    public TbResource findByResourceName(String resourceName)throws SystemException;

    }
    package com.testingonline.dao.impl;import java.util.List;import com.testingonline.dao.iface.IResourceDAO;
    import com.testingonline.entity.TbResource;
    import com.testingonline.exception.SystemException;public class ResourceDAOImpl extends GenericDAOImpl<TbResource, Integer> implements IResourceDAO{ @SuppressWarnings("unchecked")
    public List<TbResource> findByType(Object type) {
    return getHibernateTemplate().find("from TbResource r where r.resourceType=?", type);
    } @SuppressWarnings("unchecked")
    public List<TbResource> findByType(Object[] types) {
    return getHibernateTemplate().find("from TbResource r where r.resourceType=? or r.resourceType=?", types);
    } @SuppressWarnings("unchecked")
    public List<TbResource> getAll() throws SystemException {

    return getHibernateTemplate().find("from TbResource");
    } public TbResource findByResourceName(String resourceName)
    throws SystemException {
    List<TbResource> list = getHibernateTemplate().find("from TbResource where resourceName=?",resourceName);
    if(!list.isEmpty())
    return list.get(0);
    return null;
    }
    }
    package com.testingonline.dao.iface;import java.io.Serializable;/**
     * An interface shared by all business data access objects.
     * <p>
     * All CRUD (create, read, update, delete) basic data access operations are
     * isolated in this interface and shared across all DAO implementations.
     *
     */
    public interface IGenericDAO<T, ID extends Serializable> {    /**
         * Tries to get an instance of the object 
         * @param id the id to search for
         * @return the requested instance, or <code>null</code> if not found
         */
        public T get(ID id);
        
        /**
         * Adds a new instance of the object
         * @param entity the instance to save
         */
        public void save(T entity);
        
        /**
         * Deletes the object
         * @param entity the object to delete
         */
        public void delete(T entity);
        
        /**
         * Updates the information of an existing object
         * @param entity the instance to update
         */
        public void update(T entity);}package com.testingonline.dao.impl;import java.lang.reflect.ParameterizedType;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import java.io.Serializable;import org.hibernate.HibernateException;
    import org.hibernate.Query;
    import org.hibernate.SQLQuery;
    import org.hibernate.Session;
    import org.springframework.dao.DataAccessException;
    import org.springframework.orm.hibernate3.HibernateCallback;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.testingonline.dao.iface.IGenericDAO;
    import com.testingonline.utils.PageBean;/**
     * Implements the generic CRUD data access operations using Hibernate.
     * <p>
     * To write a DAO, subclass and parameterize this class with your entity.
     * Of course, assuming that you have a traditional 1:1 approach for
     * Entity:DAO design. 
     *
     */
    public abstract class GenericDAOImpl<T,ID extends Serializable> 
            extends HibernateDaoSupport implements IGenericDAO<T, ID> {

        private Class<T> persistentClass;    @SuppressWarnings("unchecked")
        public GenericDAOImpl() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
                    .getGenericSuperclass()).getActualTypeArguments()[0];
            
        }    public Class<T> getPersistentClass() {
            return persistentClass;
        }
        
        public void save(T entity) {
            getHibernateTemplate().save(entity);
            getHibernateTemplate().flush();    }    public void update(T entity) {
            getHibernateTemplate().update(entity);
            getHibernateTemplate().flush();
        }    public void delete(T entity) {
            getHibernateTemplate().delete(entity);
            getHibernateTemplate().flush();
        }    public T get(ID id) {
            return (T) getHibernateTemplate().get(getPersistentClass(), id);
        }
        
        /**
         * 获取某一实体类的所有纪录
         */
        @SuppressWarnings("unchecked")
    protected PageBean<T> findAll(PageBean<T> page,final Class<T> clazz)throws DataAccessException{
    try{
    Query query=getSession(false).createQuery("select count(*) from "+clazz.getName());
    Integer totalRows=((Long)query.uniqueResult()).intValue();
    page.setTotalRows(totalRows);
    page.getList().clear();
    for(int i=1;i<=page.getTotalPage();i++)
    page.getList().add(i);
    query=null;
    query=getSession(false).createQuery("from "+clazz.getName());
    if(page.getPrePage()==0)
    query.setFirstResult(0);
    else
    query.setFirstResult(page.getPrePage()*page.getRowsPerPage());
    query.setMaxResults(page.getRowsPerPage());
    List<T> list=query.list();
    page.setRecords(list);
    }catch(HibernateException e){
    throw convertHibernateAccessException(e);
    }
    return page;
    }
        
        /**
         * 根据查询语句获取总记录数与总页数
         */
        @SuppressWarnings("unchecked")
    public PageBean getTotalPageNumber(PageBean page,final String queryString, final Object[] values)throws DataAccessException{
    List list = getHibernateTemplate().executeFind(new HibernateCallback(){
    public Object doInHibernate(Session session)throws HibernateException, SQLException{
    Query query = session.createQuery(queryString);
    if(null!=values){
    for (int i = 0 ; i < values.length ; i++){
    query.setParameter( i, values[i]);
    }
    }
    Integer totalRows=((Long)query.uniqueResult()).intValue();
    List rows= new ArrayList();
    rows.add(totalRows);
    return rows;
    }
    });
    page.setTotalRows((Integer)list.get(0));
    page.getList().clear();
    for(int i=1;i<=page.getTotalPage();i++)
    page.getList().add(i);
    return page;
    }
        
        /**
         *根据给定条件获取分页信息及要检索的信息 
         */
        @SuppressWarnings("unchecked")
    protected PageBean<?> findByPage(PageBean page,final String getCount,final String hql, final Object value)throws DataAccessException{
    page = getTotalPageNumber(page,getCount,new Object[]{value});
    //define variables for pagination
    final int offset=page.getBeginIndex();
    final int pageSize=page.getRowsPerPage();

    List info= getHibernateTemplate().executeFind(new HibernateCallback(){
    public Object doInHibernate(Session session)throws HibernateException, SQLException{
    Query query = session.createQuery(hql);
    query.setParameter( 0, value);
    List result = query.setFirstResult(offset).setMaxResults(pageSize).list();
    return result;
    }
    });
    page.setRecords(info);
    return page;
     }
        
        /**
         * 根据给定条件获取分页信息及要检索的信息 
         */
        @SuppressWarnings("unchecked")
    protected PageBean<?> findByPage(PageBean page,final String getCount,final String hql, final Object[] values)throws DataAccessException{
         page = getTotalPageNumber(page,getCount,values);
    final int offset=page.getPrePage()*page.getRowsPerPage(); //define variables for pagination
    final int pageSize=page.getRowsPerPage();

    List info= getHibernateTemplate().executeFind(new HibernateCallback(){
    public Object doInHibernate(Session session)throws HibernateException, SQLException{
    Query query = session.createQuery(hql);
    for (int i = 0 ; i < values.length ; i++){
    query.setParameter( i, values[i]);
    }
    List result = query.setFirstResult(offset).setMaxResults(pageSize).list();
    return result;
    }
    });
    page.setRecords(info);
    return page;
     }
        
        /**
         *使用原生SQL语句查询而非HQL 
         */
        @SuppressWarnings("unchecked")
    protected PageBean<?> findByNativeQuery(PageBean page,String getCount,String sql,Object[] values)throws DataAccessException{
    try{
    SQLQuery query=getSession(false).createSQLQuery(getCount);
    for (int i = 0 ; i < values.length ; i++){
    query.setParameter( i, values[i]);
    }
    Integer totalRows=((Integer)query.uniqueResult()).intValue();
    page.setTotalRows(totalRows);
    page.getList().clear();
    for(int i=1;i<=page.getTotalPage();i++)
    page.getList().add(i);
    query=null;

    query=getSession(false).createSQLQuery(sql);
    for (int i = 0 ; i < values.length ; i++){
    query.setParameter( i, values[i]);
    }
    if(page.getPrePage()==0)
    query.setFirstResult(0);
    else
    query.setFirstResult(page.getPrePage()*page.getRowsPerPage());
    query.setMaxResults(page.getRowsPerPage());
    List list=query.list();
    page.setRecords(list);
    }catch(HibernateException e){
    throw convertHibernateAccessException(e);
    }
    return page;
    }
    }
    <bean id="resourceDAO" class="com.testingonline.dao.impl.ResourceDAOImpl">
    <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
      

  10.   

    用myeclipse新建web项目,然后依次添加struts、spring、hibernate框架。
    在生成的struts.xml中添加如下,即action交由spring管理
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.ObjectFactory" value="spring"></constant>
    在web.xml中添加如下,即启动spring
     <!-- spring启动 -->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
    </context-param>
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
      <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
      </welcome-file-list>
    然后再applicationContext.xml中配置需要的bean就可以了。
      

  11.   

    给你个测试的例子吧
    package service;import static org.junit.Assert.*;import java.util.List;import org.junit.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
    import org.springframework.test.context.transaction.TransactionConfiguration;import com.testingonline.dao.iface.IStuffCategoryDAO;
    import com.testingonline.dao.iface.IStuffDAO;
    import com.testingonline.entity.TbStuff;
    import com.testingonline.entity.TbStuffCategory;
    import com.testingonline.exception.SystemException;@ContextConfiguration(locations={"classpath:applicationContext*.xml"})
    @TransactionConfiguration(transactionManager="transactionManager",defaultRollback=false)
    public class StuffServiceImplTest extends AbstractTransactionalJUnit4SpringContextTests{ @Autowired
    private IStuffCategoryDAO stuffCategoryDAO;

    @Autowired
    private IStuffDAO stuffDAO;

    @Test
    public void testFindAllCategories() {
    fail("Not yet implemented");
    } @Test
    public void testFindAllStuffs() throws SystemException {
    List<TbStuff> list = stuffDAO.getAllStuffs();
    if(!list.isEmpty())
    System.out.println(list.size());
    else {
    System.out.println("The list is empty");
    }
    } @Test
    public void testFindStuffsByCategory() throws SystemException {
    TbStuffCategory category = new TbStuffCategory();
    category.setSutffCategoryName("工具");
    List<TbStuff> list = stuffDAO.getStuffByCategory(category);
    if(!list.isEmpty())
    System.out.println(list.size());
    else {
    System.out.println("Category 工具  has no stuffs");
    }
    }}
    package action;import java.util.HashSet;
    import java.util.List;
    import java.util.Set;import org.junit.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
    import org.springframework.test.context.transaction.TransactionConfiguration;import com.testingonline.biz.iface.IStuffService;
    import com.testingonline.entity.TbStuffCategory;
    import com.testingonline.exception.SystemException;
    @ContextConfiguration(locations={"classpath:applicationContext*.xml"})
    @TransactionConfiguration(transactionManager="transactionManager",defaultRollback=false)
    public class StuffActionTest extends AbstractTransactionalJUnit4SpringContextTests{ @Autowired
    private IStuffService stuffService;
    private TbStuffCategory category;

    private Set<TbStuffCategory> firstLevelCategories = new HashSet<TbStuffCategory>();
    // private Set<TbStuffCategory> secondLevelCategories = new HashSet<TbStuffCategory>();
    // private Set<TbStuffCategory> thirdLevelCategories = new HashSet<TbStuffCategory>();

    @Test
    public void testExecute() throws SystemException{
    List<TbStuffCategory> list = stuffService.findAllCategories();

    for (TbStuffCategory c:list) {
    if(null==c.getStuffCategoryParent()){
    category = c;
    System.out.println("First Level Category Name: "+category.getSutffCategoryName()+"  number: "+category.getStuffCategoryNumber());
    }
    else if(category.getStuffCategoryId().equals(c.getStuffCategoryParent())){
    firstLevelCategories.add(c);
    System.out.println("First Level Category Name: "+c.getSutffCategoryName()+"  number: "+c.getStuffCategoryNumber());
    }
    //System.out.println("First Level Category Name: "+c.getSutffCategoryName()+"  number: "+c.getStuffCategoryParent());
    }

    // for(TbStuffCategory c:firstLevelCategories){
    // System.out.println("First Level Category Name: "+c.getSutffCategoryName()+"  number: "+c.getStuffCategoryNumber());
    // }
    }}
      

  12.   

    http://www.ibm.com/developerworks/cn/java/j-lo-spring25-test/
      

  13.   

    http://hi.baidu.com/lupeng0527/blog/item/bf153aec60d038d62f2e213d.html
    http://xiaofancn.javaeye.com/blog/953084