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

2024-01-27 00:32

本文主要是介绍基于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" class="leo.test.WelcomAction" 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 class="edu.leo.dao.LoginEntity" />
   -->

 </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 class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

 

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

这篇关于基于Annotation的SSH整合例子 Struts2 Spring3 Hibernate3的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/648522

相关文章

Java设计模式---迭代器模式(Iterator)解读

《Java设计模式---迭代器模式(Iterator)解读》:本文主要介绍Java设计模式---迭代器模式(Iterator),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录1、迭代器(Iterator)1.1、结构1.2、常用方法1.3、本质1、解耦集合与遍历逻辑2、统一

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

Java 线程安全与 volatile与单例模式问题及解决方案

《Java线程安全与volatile与单例模式问题及解决方案》文章主要讲解线程安全问题的五个成因(调度随机、变量修改、非原子操作、内存可见性、指令重排序)及解决方案,强调使用volatile关键字... 目录什么是线程安全线程安全问题的产生与解决方案线程的调度是随机的多个线程对同一个变量进行修改线程的修改操

从原理到实战深入理解Java 断言assert

《从原理到实战深入理解Java断言assert》本文深入解析Java断言机制,涵盖语法、工作原理、启用方式及与异常的区别,推荐用于开发阶段的条件检查与状态验证,并强调生产环境应使用参数验证工具类替代... 目录深入理解 Java 断言(assert):从原理到实战引言:为什么需要断言?一、断言基础1.1 语

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

SpringBoot整合liteflow的详细过程

《SpringBoot整合liteflow的详细过程》:本文主要介绍SpringBoot整合liteflow的详细过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋...  liteflow 是什么? 能做什么?总之一句话:能帮你规范写代码逻辑 ,编排并解耦业务逻辑,代码

JavaSE正则表达式用法总结大全

《JavaSE正则表达式用法总结大全》正则表达式就是由一些特定的字符组成,代表的是一个规则,:本文主要介绍JavaSE正则表达式用法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录常用的正则表达式匹配符正则表China编程达式常用的类Pattern类Matcher类PatternSynta

Spring Security中用户名和密码的验证完整流程

《SpringSecurity中用户名和密码的验证完整流程》本文给大家介绍SpringSecurity中用户名和密码的验证完整流程,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 首先创建了一个UsernamePasswordAuthenticationTChina编程oken对象,这是S