SSH 整合例子 Struts2 Spring3 Hibernate3

本文介绍了一个基于Struts2、Spring和Hibernate的技术栈实现的项目架构。具体包括了web.xml中Spring监听器和过滤器的配置、struts.xml中的配置细节、Hibernate的映射文件以及核心的applicationContext.xml配置。此外还展示了具体的Action、Service和DAO层的实现方式。
 后台业务层如下(在service处加入的事务)
action <--> service <--> dao

 

------------------------------------------------------------------

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="WebApp_ID" version="2.5">
 <display-name>Struts2Test</display-name>

 <!-- 配置spring的监听器 -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
   <param-value>classpath*:applicationContext*.xml</param-value>
 </context-param>
 <!-- 开启监听 -->
 <listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
 <!-- 配置OpenSessionInViewFilter,必须在struts2监听之前 -->
 <filter>
  <filter-name>lazyLoadingFilter</filter-name>
  <filter-class>
   org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  </filter-class>
 </filter>

 <!-- 配置struts2的过滤器 -->
 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>
   org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  </filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 <!-- 配置欢迎页 -->
 <welcome-file-list>
  <welcome-file>JSP/Index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

 

struts.xml(在src目录下)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
              "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
              " http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <!-- 指定Struts 2默认的ObjectFactory Bean - 交给Spring管理 -->
  <constant name="struts.objectFactory" value="spring" />
  <!-- 开发者模式 -->
  <constant name="struts.devMode" value="true" />
  <!-- 设置需要过滤action的package(annotation注解) -->
  <constant name="struts.convention.package.locators" value="test,leo" />
  <constant name="struts.convention.classes.reload" value="true" />
  <package name="default" namespace="/" extends="struts-default">
    <!-- <action name="welcom" class="leo.test.WelcomAction" method="execute">
      <result name="success">JSP/Welcom.jsp</result> </action> -->
  </package>
</struts>

 

hibernateContext.cfg.xml(在src目录下)

<!DOCTYPE hibernate-configuration
      PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
      " http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <mapping resource="leo/test/dao/CustBasic.hbm.xml" />
  </session-factory>
</hibernate-configuration>

 

applicationContext.xml(在src目录下)

<?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:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    ">

 <!-- 配置dataSource -->
 <!--
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  <property name="url" value="jdbc:mysql://localhost:3306/cccrm10"></property>
  <property name="username" value="cccrm10"></property>
  <property name="password" value="oasuser"></property>
 </bean>
 -->
 <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName">
   <value>java:comp/env/jdbc/SSHTest</value>
  </property>
 </bean>

 <!-- 配置Hibernate的SessionFactory -->
 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource">
   <ref bean="dataSource" />
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <prop key="hibernate.show_sql">true</prop>
   </props>
  </property>
  <property name="configLocations">
   <list>
    <value>classpath*:hibernateContext.cfg.xml</value>
   </list>
  </property>
  <property name="mappingResources">
   <list>
    <!--
    <value>leo/test/dao/CustBasic.hbm.xml</value>
     -->
   </list>
  </property>
 </bean>

 <!-- 定义事务管理器,使用适用于Hibernte的事务管理器 -->
 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref local="sessionFactory" />
  </property>
 </bean>

 <!-- 1.事务处理的一个代理 -->
 <!--
 <bean id="transactionBase" lazy-init="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
  <property name="transactionManager">
   <ref bean="transactionManager" />
  </property>
  <property name="transactionAttributes">
  <props>
   <prop key="get*">PROPAGATION_REQUIRED,readOnly,-Exception</prop>
   <prop key="*">PROPAGATION_REQUIRED,-Exception</prop>
  </props>
  </property>
 </bean>
 配置Service
 <bean id="mySerivceTarget" class="leo.test.service.MyServiceImpl">
  <property name="dao">
   <ref bean="custBasicDao" />
  </property>
 </bean>
 配置加入事务代理的Service
 <bean id="mySerivce" parent="transactionBase" >
  <property name="target" ref="mySerivceTarget" />
 </bean>
 -->

 <!-- 2.配置使用拦截器的事务 -->
 <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
  <property name="transactionManager" ref="transactionManager" />
  <!-- 配置事务属性 -->
  <property name="transactionAttributes">
   <props>
    <!-- 所有以get开头的方法,采用required的事务策略,并且只读 -->
    <prop key="get*">PROPAGATION_REQUIRED,readOnly,-Exception</prop>
    <!-- 其他方法,采用required的事务策略 -->
    <prop key="*">PROPAGATION_REQUIRED,-Exception</prop>
   </props>
  </property>
 </bean>
 <!-- 定义BeanNameAutoProxyCreator,该bean是个bean后处理器,无需被引用,因此没有id属性这个bean后处理器,根据事务拦截器为目标bean自动创建事务代理-->
 <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  <property name="beanNames">
   <list>
    <!-- 所有名字以Service结尾的Bean -->
    <value>*Serivce</value>
   </list>
  </property>
  <property name="interceptorNames">
   <list>
    <value>transactionInterceptor</value>
   </list>
  </property>
 </bean>

 <!-- 配置Dao -->
 <bean id="custBasicDao" class="leo.test.dao.CustBasicDaoImpl">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <!-- 配置Service -->
 <bean id="mySerivce" class="leo.test.service.MyServiceImpl">
  <property name="dao">
   <ref bean="custBasicDao" />
  </property>
 </bean>

 <!-- 配置Action -->
 <bean id="showCustAction" class="leo.test.action.ShowCustAction">
  <property name="mySerivce">
   <ref bean="mySerivce" />
  </property>
 </bean>
</beans>

 

ShowCustAction.java

package leo.test.action;

import java.util.List;
import leo.test.dao.CustBasicEntity;
import leo.test.service.MySerivce;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/")
@ParentPackage("default")
@Results({
    @Result(name = "success", location = "/JSP/Index.jsp"),
    @Result(name = "showCust", location = "/JSP/ShowCust.jsp"),
})
public class ShowCustAction extends ActionSupport {

    private static final long serialVersionUID = 6164665898354735604L;

    // 画面表示用的list
    private List<CustBasicEntity> showCustList;

    // 依赖注入的service
    private MySerivce mySerivce;


    public String execute() throws Exception {
        return SUCCESS;
    }

    public String search() throws Exception {
        System.out.println("MenuAction#search()");
        List<CustBasicEntity> vTestList = mySerivce.getAllData();
        this.setShowCustList(vTestList);
        return "showCust";
    }
    public String insert() throws Exception {
        System.out.println("MenuAction#insert()");
        mySerivce.insert();
        return search();
    }

    public MySerivce getMySerivce() {
        return mySerivce;
    }

    public void setMySerivce(MySerivce mySerivce) {
        this.mySerivce = mySerivce;
    }

    public List<CustBasicEntity> getShowCustList() {
        return showCustList;
    }

    public void setShowCustList(List<CustBasicEntity> showCustList) {
        this.showCustList = showCustList;
    }
}

 

MyServiceImpl.java(MySerivce接口就不发了,什么都没有只有定义)

package leo.test.service;

import java.util.List;
import leo.test.dao.CustBasicEntity;
import leo.test.dao.CustBasicDao;

public class MyServiceImpl implements MySerivce {

    // 依赖注入的dao
    private CustBasicDao dao;

    public List<CustBasicEntity> getAllData() {
        System.out.println("MyServiceImpl#getAllData()");
        return dao.getAllData();
    }

    public void insert() {
        System.out.println("MyServiceImpl#insert()");
        Long vMaxCid = dao.getMaxCid();
        for (int i = 0; i < 3; i++) {
            if (i == 1) {
                //事务测试用
                String vBug = null;
                vBug.split(",");
            }
            CustBasicEntity insertEntity = new CustBasicEntity();
            insertEntity.setCid(vMaxCid + i);
            insertEntity.setAspId(1000L);
            insertEntity.setUserCd("Leo1");
            insertEntity.setCorpKbn("2");
            insertEntity.setRankCd("3");
            insertEntity.setDelFlg("1");
            insertEntity.setUpdCnt(1L);
            dao.insertCust(insertEntity);
        }
    }

    public CustBasicDao getDao() {
        return dao;
    }

    public void setDao(CustBasicDao dao) {
        this.dao = dao;
    }
}

 

CustBasicDaoImpl.java(CustBasicDao接口就不发了,什么都没有只有定义)

package leo.test.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CustBasicDaoImpl extends HibernateDaoSupport implements CustBasicDao {

    public List<CustBasicEntity> getAllData() {
        System.out.println("CpcMCustBasicDaoImpl#getAllData()");
        // Session session = this.getSession(true);
        Session session = this.getSession();
        StringBuffer hql = new StringBuffer();
        hql.append(" from CustBasicEntity ");
        hql.append(" where ");
        hql.append(" del_flg = :delFlg ");
        Query query = session.createQuery(hql.toString());
        //query.setLong("cid", 9000L);
        query.setString("delFlg", "1");
        List<CustBasicEntity> userList = query.list();
        return userList;
    }

    public Long getMaxCid() {
        System.out.println("CpcMCustBasicDaoImpl#getMaxCid()");
        Session session = this.getSession();
        StringBuffer hql = new StringBuffer();
        hql.append(" select max(cid) ");
        hql.append(" from CustBasicEntity ");
        Query query = session.createQuery(hql.toString());
        Object result = query.uniqueResult();
        long vMaxCid = 0;
        if (result == null) {
            vMaxCid = 1;
        } else {
            vMaxCid = Long.parseLong(result.toString());
            vMaxCid++;
        }
        return vMaxCid;
    }

    public void insertCust(CustBasicEntity insertEntity) {
        System.out.println("CpcMCustBasicDaoImpl#insert()");
        Session session = this.getSession();
        session.save(insertEntity);
    }
}

 

CustBasicEntity.java

package leo.test.dao;

import java.util.Date;

public class CustBasicEntity {

    private Long cid;
    private Long aspId;
    private String userCd;
    private String corpKbn;
    private String rankCd;
    private String custInsDate;
    private Date insDate;
    private String insUserId;
    private Date updDate;
    private String updUserId;
    private Date delDate;
    private String delUserId;
    private String delFlg;
    private Long updCnt;

    set 方法
    get 方法
}

 

CustBasic.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
" http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2011/04/27 10:55:49 by Hibernate Tools 3.2.4.GA -->
<hibernate-mapping>
      <class name="leo.test.dao.CustBasicEntity" table="cpc_m_cust_basic">
              <id name="cid" type="java.lang.Long">
                      <column name="cid" precision="18" scale="0" />
                      <generator class="assigned" />
              </id>
              <property name="aspId" type="java.lang.Long">
                      <column name="asp_id" precision="18" scale="0" not-null="true">
                              <comment>ASPID&#129;i&#145;&#227;&#141;s&#138;&#233;&#139;&#198;ID&#129;j</comment>
                      </column>
              </property>
              <property name="userCd" type="string">
                      <column name="user_cd" length="20">
                              <comment>&#131;&#134;&#129;[&#131;U&#129;[&#131;R&#129;[&#131;h</comment>
                      </column>
              </property>
              <property name="corpKbn" type="string">
                      <column name="corp_kbn" length="2">
                              <comment>&#150;@&#144;l&#139;&#230;&#149;&#170;</comment>
                      </column>
              </property>
              <property name="rankCd" type="string">
                      <column name="rank_cd" length="10">
                              <comment>&#131;&#137;&#131;&#147;&#131;N&#131;R&#129;[&#131;h</comment>
                      </column>
              </property>
              <property name="custInsDate" type="string">
                      <column name="cust_ins_date" length="10">
                              <comment>&#140;&#218;&#139;q&#143;&#238;&#149;&#241;&#147;o&#152;^&#147;&#250;</comment>
                      </column>
              </property>
              <property name="insDate" type="timestamp">
                      <column name="ins_date" length="19">
                              <comment>&#147;o&#152;^&#147;&#250;&#142;&#158;</comment>
                      </column>
              </property>
              <property name="insUserId" type="string">
                      <column name="ins_user_id" length="20">
                              <comment>&#147;o&#152;^&#131;&#134;&#129;[&#131;U&#129;[ID</comment>
                      </column>
              </property>
              <property name="updDate" type="timestamp">
                      <column name="upd_date" length="19">
                              <comment>&#141;X&#144;V&#147;&#250;&#142;&#158;</comment>
                      </column>
              </property>
              <property name="updUserId" type="string">
                      <column name="upd_user_id" length="20">
                              <comment>&#141;X&#144;V&#131;&#134;&#129;[&#131;U&#129;[ID</comment>
                      </column>
              </property>
              <property name="delDate" type="timestamp">
                      <column name="del_date" length="19">
                              <comment>&#141;&#237;&#143;&#156;&#147;&#250;&#142;&#158;</comment>
                      </column>
              </property>
              <property name="delUserId" type="string">
                      <column name="del_user_id" length="20">
                              <comment>&#141;&#237;&#143;&#156;&#131;&#134;&#129;[&#131;U&#129;[ID</comment>
                      </column>
              </property>
              <property name="delFlg" type="string">
                      <column name="del_flg" length="1" not-null="true">
                              <comment>&#141;&#237;&#143;&#156;&#131;t&#131;&#137;&#131;O</comment>
                      </column>
              </property>
              <property name="updCnt" type="java.lang.Long">
                      <column name="upd_cnt" not-null="true">
                              <comment>&#141;X&#144;V&#137;&#241;&#144;&#148;</comment>
                      </column>
              </property>
      </class>
</hibernate-mapping>

 

ShowCust.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show Cust</title>
</head>
<body>
  <div align="center">
    <s:a action="show-cust!insert.action">insert</s:a>
    <br><br>
    <table bordercolor="blue" border="1">
      <tr>
        <th>
          cid
        </th>
        <th>
          aspId
        </th>
        <th>
          userCd
        </th>
      </tr>
      <s:iterator value="showCustList" id="element">
      <tr>
        <td>
          <s:property value="#element.cid" />
        </td>
        <td>
          <s:property value="#element.aspId" />
        </td>
        <td>
          <s:property value="#element.userCd" />
        </td>
      </tr>
      </s:iterator>
    </table>
  </div>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值