本文主要是介绍基于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);