来源:
基于Annotation的SSH整合例子 Struts2 Spring3 Hibernate3
之前写了一个简单的SSH整合例子
http://blog.sina.com.cn/s/blog_57769b7b0100tr7j.html
这次在上面例子的基础上把Annotation的实现也做一下。
Struts2和hibernate的注解都是非常好理解的。
如果你看不懂Spring的注解的话,请先看一下这里http://blog.sina.com.cn/s/blog_57769b7b0100tt3u.html
需要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目录下)
<!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>
相关推荐
SSH三大框架,即Struts、Spring和Hibernate,是Java Web开发中的常用技术组合,它们各自负责不同的职责:Struts作为MVC模式中的Controller层,处理用户请求并转发到相应的业务逻辑;Spring则作为核心容器,负责依赖...
在IT行业中,SSH2是一个常见的框架组合,由Struts2、Spring和Hibernate三个组件组成,用于构建企业级的Java Web应用程序。在这个特定的项目中,开发者选择了SSH2的特定版本:Struts2.1.6、Spring2.5.6和Hibernate3.3...
Struts2、Spring和Hibernate是Java Web开发中的三大框架,它们各自在应用程序的不同层面...通过分析这些文件,开发者可以更好地理解如何在实际项目中应用基于注解的Struts2、Spring和Hibernate整合,从而提升开发效率。
Struts2、Spring和Hibernate是Java Web开发中的三大框架,它们各司其职,共同构建了一个强大的企业级应用体系。这个示例项目是基于这三个框架的整合应用,用于实现一个基本的用户登录功能。 **Struts2** 是一个用于...
5. **冲突解决**:在SSH整合过程中,可能遇到版本兼容性问题,例如Struts2与Spring、Hibernate的不同版本间的兼容性。选择相互兼容的版本,遵循官方推荐的配置,可以有效避免此类问题。 6. **优势**:SSH整合可以...
### Struts+Spring+Hibernate整合教程 #### 一、SSH整合理念 在现代Web应用程序开发中,使用多种框架和技术来构建高效、可扩展且易于维护的应用程序已成为常态。本教程旨在介绍如何有效地整合Struts(负责表现层)...
SSH整合是Java开发中一种常见的框架组合,包括Spring、Struts和Hibernate三个核心组件。Spring提供了依赖注入(DI)和面向切面编程(AOP),Struts负责MVC模式的实现,而Hibernate则是用于对象关系映射(ORM)。在这...
基于注解Annotation的最新版SSH(Struts2.3.7+Hibernate4.1.9+Spring3.2.0)整合开发,真正实现零配置。 最新版本Struts、Spring、Hibernate框架整合: struts-2.3.7 spring-framework-3.2.0.RELEASE hibernate-...
### 基于Annotation的SSH整合开发:Spring、Struts与Hibernate协同工作 #### 概述 本文将探讨如何在项目中实现基于Annotation的SSH(Spring、Struts、Hibernate)框架整合。随着技术的发展,XML配置逐渐被...
Struts2、Spring和Hibernate是Java Web开发中的三大框架,它们各自解决了一部分问题,而SSH2(Struts2、Spring、Hibernate的整合)则旨在提供一个完整的解决方案,以简化企业级应用的开发流程。本实例将深入探讨如何...
3. **Struts2整合Spring**: - Struts2的Action类可以通过Spring进行管理,使用`@Component`注解标记Action类。 - 配置Struts2-Spring插件,让Struts2知道如何从Spring容器中获取Action实例。 4. **留言管理功能*...
整合SSH可以让开发者利用Spring的管理能力,让Hibernate更易于使用,同时通过Struts2提供良好的用户交互体验。 在描述中,虽然没有提供具体细节,但可以推断出内容可能涉及整合过程中的关键配置和依赖。整合SSH通常...
【基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发】 这篇文档主要介绍了一个使用注解(Annotation)进行Struts2.0、Hibernate3.3和Spring2.5整合开发的教程。这种集成方式相比传统的XML配置,可以简化...
Struts2、Hibernate和Spring是Java开发中三大主流框架,它们的整合应用通常被称为SSH(Struts2-Spring-Hibernate)集成。这个压缩包包含了这三个框架的特定版本:Struts2.18、Hibernate3.3.2和Spring2.5.6,以及可能...
SSH(Struts2、Spring、Hibernate)是一个常见的Java开发框架组合,用于构建基于Maven的Web应用程序。Maven是一个项目管理工具,它可以帮助开发者管理和构建项目,而SSH框架则提供了模型-视图-控制器(MVC)架构的...
超级详细的SSH2项目实例详解,并且附带两个项目详解。两种注解实现方式。不同的生成数据脚本实现。 在JavaEE企业级开发中,以SSH2框架为核心的应用非常广,大象根据项目实践经验,通过二个实例,详细的为大家讲解...
在"Struts2+Hibernate4+Spring3整合"中,通常有两种方式实现整合: 1. **XML方式**:这是传统的配置方式,所有的配置信息都在XML文件中。Struts2的配置文件(struts.xml)定义Action和结果,Hibernate的配置文件...
SSH整合时,Spring通常作为"粘合剂",负责管理和调用Struts2的Action以及Hibernate的数据访问对象(DAO)。通过Spring的ApplicationContext,可以将Struts2的Action和Hibernate的SessionFactory注入到需要的地方,...