基于Annotation注解的SSH整合例子 Struts2 Spring3 Hibernate3



基于Annotation的SSH整合例子 Struts2 Spring3 Hibernate3.

需要jar

1.Hibernate
-hibernate-jpa-2.0-api-1.0.1.Final.jar
hibernate-annotations-3.4.0.GA.zip(http://sourceforge.net/projects/hibernate/files/hibernate-annotations/)
-ejb3-persistence.jar

2.Spring
javaee.jar (http://www.jarfinder.com/index.php/jars/versionInfo/62754)

3.Struts
struts2-convention-plugin-2.2.3.jar

注意:

1.有些web服务器默认的j2ee版本比较低..javaee.jar尽量也放在web服务器上比较稳妥..

 例如tomcat的话..就把javaee-api-5.0.5.jar放在apache-tomcat-5.5.26\common\lib下

2.数据库连接的驱动jar不要忘记..也要放在apache-tomcat-5.5.26\common\lib下

——————————————————-

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>
<!– 加入springMVC (对 web session request的支持)(Servlet 2.4以后) –>
<listener>
 <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!– 配置OpenSessionInViewFilter,必须在struts2监听之前 –>
<filter>
 <filter-name>lazyLoadingFilter</filter-name>
 <filter-class>
  org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
 </filter-class>
</filter>
<!– 加入springMVC (对 web session request的支持)(Servlet 2.4以前) –>
<!–
<filter>
 <filter-name>requestContextFilter</filter-name>
 <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
 <filter-name>requestContextFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
–>

<!– 配置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 –>
<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” method=”execute”>
  <result name=”success”>JSP/Welcom.jsp</result> </action> –>
</package>
</struts>

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

<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
       ”-//Hibernate/Hibernate Configuration DTD 3.0//EN”
       ”http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>

<hibernate-configuration>
<session-factory>
 <!– 数据库言 –>
 <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
 <!– 将Session扔到线程里去处理 –>
 <property name=”current_session_context_class”>thread</property>
 <!– 在控制台打印SQL语句 –>
 <property name=”show_sql”>true</property>
 <!– 自动把实体类与属性映射成数据库中的表与列 –>
 <property name=”hbm2ddl.auto”>none</property>
 <!– <mapping resource=”leo/test/dao/CustBasic.hbm.xml” /> –>
 <!– 在Hibernate中注册User实体类,区别于上面注释掉的resource写法
 <mapping />
  –>

</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” xmlns:context=”http://www.springframework.org/schema/context”
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
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.1.xsd
   ”>

<!– 注册PostProcessor – 负责扫描使用了 JSR-250 注释的 Bean,并对它们进行相应的操作 –>
<bean />

<!– 配置dataSource –>
<!– <bean id=”dataSource”>
 <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”>
 <property name=”jndiName”>
  <value>java:comp/env/jdbc/SSHAnnotationSample</value>
 </property>
</bean>

<!– 配置SessionFactory,由Spring容器来管理Hibernate –>
<!– 非Annotation时,使用org.springframework.orm.hibernate3.LocalSessionFactoryBean,
 它注入实体类的方式是setMappingResources(),而Hibernate Annotation所用的映射方式 不是mapping resource,而是mapping
 class,这就要用到LocalSessionFactoryBean的子类 AnnotationSessionFactoryBean了.因为AnnotationSessionFactoryBean它支持实体的注入
 方式setAnnotatedClasses,即对应Hibernate中的mapping class.参见这两个类的源代码. –>
<bean id=”sessionFactory”
 class=”org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean”>
 <property name=”dataSource”>
  <ref bean=”dataSource” />
 </property>
 <property name=”configLocation”>
  <value>classpath:hibernateContext.cfg.xml</value>
 </property>
 <property name=”configurationClass” value=”org.hibernate.cfg.AnnotationConfiguration” />
 <property name=”packagesToScan”>
  <list>
   <value>leo.test.dao</value>
  </list>
 </property>
</bean>

 <!– 定义事务管理器(声明式的事务) –>
<bean id=”transactionManager”
 class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
 <property name=”sessionFactory” ref=”sessionFactory” />
</bean>

<!– 让Spring通过自动扫描来查询和管理Bean (添加这句之后<context:annotation-config />可以不写) –>
<context:component-scan base-package=”edu.leo” />

<!– 启动spring注解功能 –>
<tx:annotation-driven transaction-manager=”transactionManager” />

</beans>

ShowCustAction.java

package leo.test.action;

import java.util.List;
import javax.annotation.Resource;
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 org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

//声明此类为控制层的类
@Controller
//为prototype模式调用
@Scope(“prototype”)
@Namespace(“/”)
@ParentPackage(“default”)
@Results({
   @Result(name = “success”, location = “/JSP/Index.jsp”),
   @Result(name = “showCust”, location = “/JSP/ShowCust.jsp”),
   @Result(name = “input”, location = “/JSP/ShowCust.jsp”),
})
public class ShowCustAction extends ActionSupport implements ModelDriven<ShowCustModel> {

   private static final long serialVersionUID = 6164665898354735604L;

   @Resource
   ShowCustModel model;

   //@Autowired(required = true)
   @Resource
   private MySerivce service;

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

   @SkipValidation
   public String search() throws Exception {
       System.out.println(“MenuAction#search()”);
       List<CustBasicEntity> vTestList = service.getAllData();
       model.setShowCustList(vTestList);
       return “showCust”;
   }

   @SkipValidation
   public String insert() throws Exception {
       System.out.println(“MenuAction#insert()”);
       service.insert();
       return search();
   }

   @Validations(
     requiredStrings={
       @RequiredStringValidator(fieldName=”username”,message=”用户名是必须的”,shortCircuit=true,trim=true,type=ValidatorType.FIELD),
       @RequiredStringValidator(fieldName=”password”,message=”密码是必须的”,shortCircuit=true,trim=true,type=ValidatorType.FIELD)},
     fieldExpressions={
       @FieldExpressionValidator(fieldName=”password”, message=”两次密码不相同”,expression=”password==password2″)})
   public String validateTest() throws Exception {
       System.out.println(“MenuAction#validateTest()”);
       System.out.println(“用户名:” + model.getUsername());
       System.out.println(“密码:” + model.getPassword());
       return search();
   }

   public ShowCustModel getModel() {
       return model;
   }
}

ShowCustModel.java


package leo.test.action;

import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import leo.test.dao.CustBasicEntity;

@Scope(“request”)
@Controller
public class ShowCustModel {

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

   private String username;
   private String password;
   private String password2;

   set方法
   get方法
}

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

package leo.test.service;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import leo.test.dao.CustBasicEntity;
import leo.test.dao.CustBasicDao;

//声明此类为业务逻辑层的类
@Service
public class MyServiceImpl implements MySerivce {

   //@Autowired(required = true)
   @Resource
   private CustBasicDao dao;

   @Transactional(readOnly = true)
   public List<CustBasicEntity> getAllData() {
       System.out.println(“MyServiceImpl#getAllData()”);
       return dao.getAllData();
   }

   @Transactional(readOnly = false, rollbackFor = Throwable.class)
   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);
       }
   }
}

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

package leo.test.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

//声明此类为数据持久层的类
@Repository
public class CustBasicDaoImpl extends MyHibernateDaoSupport 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);
   }
}

MyHibernateDaoSupport.java

package leo.test.dao;

import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class MyHibernateDaoSupport extends HibernateDaoSupport {

   //为父类HibernateDaoSupport注入sessionFactory的值
   @Resource(name = “sessionFactory”)
   public void setSuperSessionFactory(SessionFactory sessionFactory) {
       super.setSessionFactory(sessionFactory);
   }

}

CustBasicEntity.java

package leo.test.dao;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = “cpc_m_cust_basic”)
public class CustBasicEntity {

   @Id
   //@GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long cid;

   @Column(name = “asp_id”, length = 18)
   private Long aspId;

   @Column(name = “user_cd”, length = 20)
   private String userCd;

   @Column(name = “corp_kbn”, length = 2)
   private String corpKbn;

   @Column(name = “rank_cd”, length = 10)
   private String rankCd;

   @Column(name = “cust_ins_date”, length = 10)
   private String custInsDate;

   @Column(name = “insDate”, length = 19)
   private Date insDate;

   @Column(name = “ins_user_id”, length = 20)
   private String insUserId;

   @Column(name = “upd_date”, length = 19)
   private Date updDate;

   @Column(name = “upd_user_id”, length = 20)
   private String updUserId;

   @Column(name = “del_date”, length = 19)
   private Date delDate;

   @Column(name = “del_user_id”, length = 20)
   private String delUserId;

   @Column(name = “del_flg”, length = 1)
   private String delFlg;

   @Column(name = “upd_cnt”)
   private Long updCnt;

   set方法
   get方法
}

 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:form action=”show-cust!validateTest.action” theme=”simple”>
  用户名:<s:textfield name=”username” /><br>
  密码:<s:password name=”password” /><br>
  密码2:<s:password name=”password2″ /><br>
  <s:submit value=”注册” />
 </s:form>
 <s:fielderror></s:fielderror>

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

http://blog.csdn.net/springsen/article/details/7303555