SSH 基本配置--OA系统的经典配置

说明:
此SSH架构时OA系统的经典配置
绝对是最经典的配置,您值得拥有

一、structs配置文件

<?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.devMode" value="true" />
    <!-- 全局国际化配置 -->
    <constant name="struts.custom.i18n.resources" value="messages"></constant>
    <constant name="struts.action.extension" value="action,do"/>
    <constant name="struts.configuration.xml.reload" value="true"></constant>
    <constant name="struts.multipart.maxSize" value="10240000"></constant>
    <!-- 表示Action由Spring来进行创建,可以直接使用Spring依赖注入来注入 -->
    <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
    <constant name="struts.ui.theme" value="simple"></constant>  
    <!-- 允许使用静态方法 -->
    <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>  

    <package name="default" namespace="/" extends="json-default">
        <interceptors>
            <interceptor name="privilegeInterceptor" class="com.ssh.oa.filter.PrivilegeInteceptor"></interceptor>
            <interceptor-stack name="defaultStack">
                <interceptor-ref name="privilegeInterceptor"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <global-results>
            <result name="error">/WEB-INF/jsp/inc/error.jsp</result>
            <result name="exception">/WEB-INF/jsp/inc/exception.jsp</result>
            <result name="noPrivilege">/WEB-INF/jsp/inc/noPrivilege.jsp</result>
            <result name="loginUI">/WEB-INF/jsp/user/loginUI.jsp</result>
        </global-results>
        <global-exception-mappings>
            <exception-mapping result="exception" exception="com.ssh.document.exeception.MyExeception"></exception-mapping>
        </global-exception-mappings>
        <!-- 跟方法名不相同的都必须写 -->
        <action name="*_*" class="{1}Action" method="{2}">
            <result name="{2}">/WEB-INF/jsp/{1}/{2}.jsp</result>
            <result name="saveUI">/WEB-INF/jsp/{1}/saveUI.jsp</result>
            <result name="toList" type="redirectAction">{1}_list?parentId=${parentId}</result>
            <result name="loginUI">/WEB-INF/jsp/{1}/loginUI.jsp</result>
            <result name="logout">/WEB-INF/jsp/{1}/logout.jsp</result>
            <result name="toIndex" type="redirect">/index.jsp</result>
            <result name="toTopicShow" type="redirectAction">topic_show?id=${topicId}</result>
            <result name="toShow" type="redirectAction">{1}_show?id=${id}</result>
            <result name="downloadProcessImage" type="stream">
                <param name="contentType">image/png</param>
                <param name="inputName">inputStream</param>
            </result>
            <result name="download" type="stream">
                <param name="contentType">application/octet-stream</param>
                <param name="inputName">inputStream</param>
                <param name="contentDisposition">attachment;fileName="${#fileName}</param>
            </result>           

            <result name="toMyApplicationList" type="redirectAction">{1}_myApplicationList</result>
            <result name="toMyTaskList" type="redirectAction">{1}_myTaskList</result>
        </action>

    </package>

</struts>

二、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">
    <!-- 配置 自动代理 -->
    <aop:aspectj-autoproxy />
    <context:annotation-config />
    <context:component-scan base-package="com.ssh.oa.*"></context:component-scan>
    <!-- <aop:aspectj-autoproxy proxy-target-class="true"/> -->

    <!-- 引入外部 properties 文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>

        <!-- 其他配置 -->
        <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
        <property name="initialPoolSize" value="3"></property>
        <!--连接池中保留的最小连接数。Default: 3 -->
        <property name="minPoolSize" value="3"></property>
        <!--连接池中保留的最大连接数。Default: 15 -->
        <property name="maxPoolSize" value="5"></property>
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
        <property name="acquireIncrement" value="3"></property>
        <!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 
            0 -->
        <property name="maxStatements" value="8"></property>
        <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
        <property name="maxStatementsPerConnection" value="5"></property>
        <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
        <property name="maxIdleTime" value="1800"></property>
    </bean>

    <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <!-- 引用数据库连接池 -->
        <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">false</prop>
                <prop key="hibernate.format_sql">false</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.connection.autocommit">true</prop>
            </props>
        </property>
        <!-- 引用hbm 映射文件 -->
        <property name="mappingDirectoryLocations">
            <list>
                <value>classpath:com/ssh/oa/domain</value>
            </list>
        </property>
        <property name="mappingLocations">
            <list>
                <value>classpath:jbpm.execution.hbm.xml</value>
                <value>classpath:jbpm.history.hbm.xml</value>
                <value>classpath:jbpm.identity.hbm.xml</value>
                <value>classpath:jbpm.repository.hbm.xml</value>
                <value>classpath:jbpm.task.hbm.xml</value>
            </list>
        </property>
        <!-- <property name="packagesToScan"> <value>com.ssh.document.domain</value> 
            </property> -->
    </bean>

    <!-- 事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

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


    <!-- 配置哪些方法要加入事务控制 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 -->
            <tx:method name="*" propagation="REQUIRED" read-only="true" />
            <!-- 以下方法都是可能设计修改的方法,就无法设置为只读 -->
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="set*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="move*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置AOP,Spring是通过AOP来进行事务管理的 -->
    <aop:config>
        <!-- 设置pointCut表示哪些方法要加入事务处理 -->
        <!-- 以下的事务是声明在DAO中,但是通常都会在Service来处理多个业务对象逻辑的关系,注入删除,更新等,此时如果在执行了一个步骤之后抛出异常 
            就会导致数据不完整,所以事务不应该在DAO层处理,而应该在service,这也就是Spring所提供的一个非常方便的工具,声明式事务 -->
        <aop:pointcut id="allMethods"
            expression="execution(* com.ssh.oa.base.*.*(..)) or execution(* com.ssh.oa.service..*.*(..))" />
        <!-- 通过advisor来确定具体要加入事务控制的方法 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" />

    </aop:config>

    <!-- 整合Spring第一步创建JavaMailSenderImpl对象 -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
            </props>
        </property>
    </bean>

    <!-- 使用Spring的ThreadPoolTaskExecutor可以方便实现多线程的程序 -->
    <bean id="taskExecutor"
        class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="5" />
        <property name="maxPoolSize" value="10" />
        <property name="queueCapacity" value="25" />
    </bean>

    <!-- 配置ProcessEngine -->
    <bean id="springHelper" class="org.jbpm.pvm.internal.processengine.SpringHelper">
        <property name="jbpmCfg" value="spring-jbpm4.cfg.xml"></property>
    </bean>
    <bean id="processEngine" factory-bean="springHelper" factory-method="createProcessEngine" />

</beans>

三、数据库配置文件jdbc.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///ssh_oa?characterEncoding=UTF-8
jdbc.user = root
jdbc.password=root

四、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>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>

    <listener>
        <listener-class>com.ssh.oa.filter.InitPrivilegeListener</listener-class>
    </listener>

    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置Spring的用于解决懒加载问题的过滤器 -->
    <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>*.action</url-pattern>
    </filter-mapping>


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

    <listener>
        <listener-class>org.apache.struts2.dispatcher.ng.listener.StrutsListener</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>

五、相关jar包

activation.jar
antlr-2.7.6.jar
antlr-runtime.jar
aopalliance.jar
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
aspectjrt.jar
aspectjweaver.jar
c3p0-0.9.1.jar
cglib-nodep-2.1_3.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.log4j-1.2.15.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-beanutils-1.8.2.jar
commons-codec.jar
commons-collections-3.1.jar
commons-dbcp.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-pool.jar
dom4j-1.6.1.jar
freemarker-2.3.19.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jbpm-bpmn.jar
jbpm-console-form-plugin.jar
jbpm-console-graphView-plugin.jar
jbpm-console-integration.jar
jbpm-console-reports.jar
jbpm-db.jar
jbpm-examples-tests.jar
jbpm-jboss.jar
jbpm-test-db-tests.jar
jbpm-tomcat6.jar
jbpm.jar
joda-time.jar
jpdl-4.4.xsd
jsf-api.jar
jsf-impl.jar
jstl-1.2.jar
jta-1.1.jar
junit-4.10.jar
log4j-1.2.16.jar
mail.jar
mysql-connector-java-5.1.17-bin.jar
ognl-3.0.5.jar
org.springframework.aop-3.1.3.RELEASE.jar
org.springframework.asm-3.1.3.RELEASE.jar
org.springframework.aspects-3.1.3.RELEASE.jar
org.springframework.beans-3.1.3.RELEASE.jar
org.springframework.context-3.1.3.RELEASE.jar
org.springframework.context.support-3.1.3.RELEASE.jar
org.springframework.core-3.1.3.RELEASE.jar
org.springframework.expression-3.1.3.RELEASE.jar
org.springframework.instrument-3.1.3.RELEASE.jar
org.springframework.instrument.tomcat-3.1.3.RELEASE.jar
org.springframework.jdbc-3.1.3.RELEASE.jar
org.springframework.jms-3.1.3.RELEASE.jar
org.springframework.orm-3.1.3.RELEASE.jar
org.springframework.test-3.1.3.RELEASE.jar
org.springframework.transaction-3.1.3.RELEASE.jar
org.springframework.web-3.1.3.RELEASE.jar
org.springframework.web.portlet-3.1.3.RELEASE.jar
org.springframework.web.servlet-3.1.3.RELEASE.jar
org.springframework.web.struts-3.1.3.RELEASE.jar
pager-taglib.jar
sitemesh-2.4.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.7.2.jar
spring-aop-3.2.0.RELEASE.jar
spring-aspects-3.2.0.RELEASE.jar
spring-beans-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar
spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
spring-jdbc-3.2.0.RELEASE.jar
spring-orm-3.2.0.RELEASE.jar
spring-test-3.2.0.RELEASE.jar
spring-tx-3.2.0.RELEASE.jar
spring-web-3.2.0.RELEASE.jar
struts2-convention-plugin-2.3.7.jar
struts2-core-2.3.7.jar
struts2-json-plugin-2.3.7.jar
struts2-sitemesh-plugin-2.3.4.1.jar
struts2-spring-plugin-2.3.7.jar
xwork-core-2.3.7.jar

六、Dao层的基本方法
1)DaoSupport.java

public interface DaoSupport<T> {

    public void save(T t);
    public void update(T t);
    public void delete(Serializable...ids);
    public T loadById(Serializable id);
    public void delete(Long id);
    public T getById(Long id);
    public T findByObj(String hql, Object...objs);
    public List<T> listByIds(Serializable...ids);
    public List<T> findByIds(Long...ids);
    public List<T> listAll();
    public PageBean getPageBean(int pageNum, int pageSize, QueryHelper queryHelper);

}

2)DaoSupportImpl.java

@SuppressWarnings("all")
public class DaoSupportImpl<T> extends HibernateDaoSupport implements DaoSupport<T> {

    private Class<T> clazz;

    public DaoSupportImpl() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[0];
    }

    /*
     * private Class<T> getClazz(){ if (clazz == null) { clazz =
     * ((Class<T>)(((ParameterizedType
     * )(this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]));
     * } return clazz; }
     */

    /*
     * @Resource private SessionFactory sessionFactory;
     * 
     * protected Session getSession(){ return
     * sessionFactory.getCurrentSession(); }
     */

    @Resource(name = "sessionFactory")
    public void setSuperSessionFactory(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    @Override
    public void save(T t) {
        getSession().save(t);
    }

    @Override
    public void update(T t) {
        getSession().update(t);
    }

    @Override
    public void delete(Serializable... ids) {
        if (ids != null && ids.length == 1) {
            Object object = loadById(ids);
            getSession().delete(object);
        } else if (ids != null && ids.length > 1) {
            for (Serializable id : ids) {
                System.out.println("id===" + id);
                Object object = loadById(id);
                if (object != null) {
                    getSession().delete(object);
                }
            }
        }

    }

    @Override
    public T loadById(Serializable id) {
        if (id != null) {
            return (T) getSession().load(clazz, id);
        }
        return null;
    }

    @Override
    public void delete(Long id) {
        Object object = getById(id);
        getHibernateTemplate().delete(object);
    }

    @Override
    public T getById(Long id) {
        if (id != null) {
            return (T) getSession().load(clazz, id);
        }
        return null;
    }

    @Override
    public T findByObj(String hql, Object... objs) {
        return (T) getQuery(hql, objs).uniqueResult();
    }

    public Query getQuery(String hql, Object... objs) {
        Query query = getSession().createQuery(hql);
        if (objs != null && objs.length > 0) {
            for (int i = 0; i < objs.length; i++) {
                query.setParameter(i, objs[i]);
            }
        }
        return query;
    }

    @Override
    public List<T> listAll() {
        String hql = " FROM " + clazz.getSimpleName();
        return this.getSession().createQuery(hql).list();
    }

    @Override
    public List<T> listByIds(Serializable... ids) {
        if (ids != null && ids.length > 0) {
            String hql = " FROM " + clazz.getSimpleName() + " WHERE id in(:ids)";
            return getSession().createQuery(hql).setParameterList("ids", ids).list();
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    public List<T> findByIds(Long... ids) {
        if (ids != null && ids.length > 0) {
            String hql = " FROM " + clazz.getSimpleName() + " WHERE id in(:ids)";
            return getSession().createQuery(hql).setParameterList("ids", ids).list();
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    public PageBean getPageBean(int pageNum, int pageSize, QueryHelper queryHelper) {
        String listHQL = queryHelper.getListHQL();

        List<Object> paramList = queryHelper.getParams();
        Query listQuery = getSession().createQuery(listHQL);
        if (paramList != null) { // 设置参数
            for (int i = 0; i < paramList.size(); i++) {
                listQuery.setParameter(i, paramList.get(i));
            }
        }
        int first = (pageNum - 1) * pageSize;
        List dataList = listQuery.setFirstResult(first).setMaxResults(pageSize).list();

        String countHQL = queryHelper.getCountHQL();
        Query countQuery = getSession().createQuery(countHQL);
        if (paramList != null) { // 设置参数
            for (int i = 0; i < paramList.size(); i++) {
                countQuery.setParameter(i, paramList.get(i));
            }
        }
        Long recordCount = (Long) countQuery.uniqueResult();
        PageBean pageBean = new PageBean(pageNum, pageSize, recordCount.intValue(), dataList);
        return pageBean;
    }

}

七、分页类

@SuppressWarnings("all")
public class PageBean {

    private List dataList = new ArrayList();// 本页的数据列表
    private int pageNum;// 当前页
    private int pageSize;// 每页显示多少条
    private int recordCount;// 总记录数
    private int pageCount;// 总页数    
    private int beginIndex;// 页码列表的开始索引(包含)
    private int endIndex;// 页码列表的结束索引(包含)


    public PageBean(int pageNum, int pageSize, int recordCount, List dataList){
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.dataList = dataList;
        this.recordCount = recordCount;
        // 计算总页码
        pageCount = (recordCount + pageSize - 1)/pageSize;

        //如果pageCount<10就全部显示
        if (pageCount <= 10) {
            beginIndex = 1;
            endIndex = pageCount;
        }else {
            //如果pageCount>10显示pageNum前4后5
            beginIndex = pageNum - 4;
            endIndex = pageNum + 5;
            if (pageNum<1) {
                beginIndex = 1;
                endIndex = 10;
            }else if (pageNum > pageCount) {
                beginIndex = pageNum - 9;
                endIndex = pageCount;
            }
        }
    }



    public List getDataList() {
        return dataList;
    }
    public void setDataList(List dataList) {
        this.dataList = dataList;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }



    public int getRecordCount() {
        return recordCount;
    }



    public void setRecordCount(int recordCount) {
        this.recordCount = recordCount;
    }



    public int getPageCount() {
        return pageCount;
    }



    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }



    public int getBeginIndex() {
        return beginIndex;
    }



    public void setBeginIndex(int beginIndex) {
        this.beginIndex = beginIndex;
    }



    public int getEndIndex() {
        return endIndex;
    }



    public void setEndIndex(int endIndex) {
        this.endIndex = endIndex;
    }




}
一,集成 Spring 与 Hibernate 1,配置SessionFactory 1,配置 ---------------------- applicationContext.xml ------------------------ <!-- 配置SessionFactory(整合Hibernate) --> <context:property-placeholder location="classpath:jdbc.properties" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <bean class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 数据库连接信息 --> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="driverClass" value="${driverClass}"></property> <property name="user" value="${username}"></property> <property name="password" value="${password}"></property> <!-- 其他配置 --> <property name="initialPoolSize" value="3"></property> <property name="maxPoolSize" value="5"></property> <property name="minPoolSize" value="3"></property> <property name="acquireIncrement" value="2"></property> <property name="maxStatements" value="8"></property> <property name="maxStatementsPerConnection" value="5"></property> <property name="maxIdleTime" value="20"></property> </bean> </property> <!-- 指定hibernate的配置文件的位置 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> </bean> ---------------------- jdbc.properties ------------------------ jdbcUrl = jdbc:mysql:///itcastoa driverClass = com.mysql.jdbc.Driver username = root password = 1234 2,测试代码 @Test// 测试 SessionFactory 的配置 public void testSessionFactory(){ SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory"); Assert.assertNotNull(sessionFactory.openSession()); } 2,配置声明式事务(使用基于注解的方式) 1,配置 <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置基于注解的事务支持--> <tx:annotation-driven transaction-manager="transactionManager"/> 2,测试代码 1,Service类 @Service public class InsertUserService { @Resource private SessionFactory sessionFactory; @Transactional public void addUsers() { sessionFactory.getCurrentSession().save(new User()); // int a = 1 / 0; // 这行会抛异常 sessionFactory.getCurrentSession().save(new User()); } } 2,单元测试 @Test // 测试声明式事务 public void testTransaction() { InsertUserService service = (InsertUserService) ac.getBean("insertUserService"); service.addUsers(); } 3,在web.xml中配置 spring 的 OpenSessionInView 过滤器(解决抛LazyInitializationException的问题) 1,配置 <!-- 配置 spring 的 OpenSessionInView 过滤器 --> <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>*.do</url-pattern> </filter-mapping> 2,LazyInitializationException异常说明 1,对于集合属性,默认是lazy="true"的,在第一次使用时才加载。 2,但在加载时,如果Session已经关掉了就会抛LazyInitializationException异常 二,集成 Spring 与 Struts2.1.8.1 1,在web.xml配置监听器(Spring Reference 15.2 Common configuration) <!-- 集成Spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/applicationContext*.xml</param-value> </context-param> 2,在struts-config.xml中配置controller(Spring Reference 15.4.1.1. DelegatingRequestProcessor) <!-- 集成Spring --> <controller> <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor" /> </controller> 3,测试 1,写Action类与Service类 @Controller("testAction") @Scope("prototype") public class TestAction extends ActionSupport { @Resource private TestService testService; @Override public String execute(){ testService.saveTwoUser(); return SUCCESS; } } @Service public class TestService { @Resource private SessionFactory sessionFactory; @Transactional public void saveTwoUser() { sessionFactory.getCurrentSession().save(new User()); // int a = 1 / 0; // 这行会抛异常 sessionFactory.getCurrentSession().save(new User()); } } 2,在struts.xml中配置Action <!-- 测试 --> <action name="test" class="testAction"> <result>/test.jsp</result> </action> 3,部署到Tomcat中并访问测试。 4,说明: 1,在写Action时要指定 @Controller 与 @Scope("prototype") 2,在struts.xml中配置action时,在class属性中写bean的名称
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lovoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值