`
huttoncs
  • 浏览: 198982 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring+Hibernate+Jpa+Struts2整合实例

阅读更多
1、首先引入进去所需要用到的jar包(内容见附件)

2、工程的web.xml配置文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:beans/**/*.xml</param-value>
</context-param>

<!-- 对Spring容器进行实例化 -->
<listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 指定log4j日志的配置 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>

<!-- 字符编码过滤器配置 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
com.xxx.eb.filter.EncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>

<!-- 对Struts进行实例化 -->
<filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
   </filter-mapping>


  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3、先进行Spring、Hibernate和JPA的整合,我这里是用的mysql数据库
(a)、applicationContext-common.xml中是关于dataSource内容的配置,其内容如下
<?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"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
default-autowire="byName" default-lazy-init="false">

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:jdbc.properties</value>
<value>classpath*:hibernate.properties</value>
</list>
</property>
</bean>

<!-- develop.dataSource.begin -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${database.driverClass}" />
<property name="jdbcUrl" value="${database.jdbcUrl}" />
<property name="user" value="${database.user}" />
<property name="password" value="${database.password}" />
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="1"/>
<!--连接池中保留的最小连接数。-->
<property name="minPoolSize" value="1"/>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="300"/>
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="60"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="5"/>
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60"/>
</bean>

<aop:aspectj-autoproxy />

</beans>

(b)、dataAccessContext-jpa-local.xml文件是有关entityManagerFactory的配置,其内容如下:
<?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:context="http://www.springframework.org/schema/context"
       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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<context:annotation-config />
<!-- JPA Common configuration -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<!-- default EntityManager Configuration -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-default.xml" />
<property name="jpaPropertyMap">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>

<property name="loadTimeWeaver">
          <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
    </property>
</bean>

<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>



</beans>

(c)、hibernate.properties的内容如下:
hibernate.initialPoolSize=1
hibernate.minPoolSize=1
hibernate.maxPoolSize=300
hibernate.maxIdleTime=60
hibernate.acquireIncrement=5
hibernate.idleConnectionTestPeriod=60
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.format_sql=false

(d)、jdbc.properties的内容如下:
# mysql Database
database.driverClass=org.gjt.mm.mysql.Driver
database.jdbcUrl=jdbc:mysql://localhost:3306/dangdang?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
database.user=root
database.password=mysql
hibernate.dialect=org.hibernate.dialect.MySQLDialect

(e)、persistence-default.xml的内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="ebwebPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>model/project-eb-user-mysql.orm.xml</mapping-file>
<properties>

<!--<property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>
        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/tests2sj?useUnicode=true&amp;characterEncoding=UTF-8"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="112284"/>
   
    --><!--以上为不与spring集成时需要的配置项-->
</properties>
</persistence-unit>
</persistence>

4、实体对象User.java类的内容为:
package com.xxx.eb.model.user;

public class User {
private static final long serialVersionUID = -3612556521346269368L;

private Long id;
private String userName;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}


}

5、project-eb-user-mysql.orm.xml是实体对象持久化的配置,其内容为:
<?xml version="1.0" encoding="utf-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
<description> component ORM for MySQL</description>
<package>com.xxx.eb.model.user</package>

    <entity class="User" name="AdminUser">
<table name="T_USER" />
<attributes>
  <id name="id">
  <column name="ID" />
  <generated-value strategy="IDENTITY" />
  </id>
  <basic name="userName">
              <column name="USERNAME" />
          </basic>
          <basic name="password">
              <column name="PASSWORD" />
          </basic>
         
</attributes>
</entity>


</entity-mappings>

整合工作到此基本完成,下面是对spring和jpa整合的一个unit测试
6、首先是一个Dao的service类UserService.java,其内容为:
package com.xxx.eb.service;

import java.util.List;

import org.springside.modules.orm.hibernate.Page;

import com.xxx.eb.model.user.User;

public interface UserService {

public void add(User user);
public void update(User user);
public User findById(int id);
public List findAll(String jpql,Object...param);
public Page find(String jpql,Page page,Object...param);
public void delete(User user);
public User getReferenceById(int id);
}
实现类UserServiceImpl.java的内容为:
package com.xxx.eb.service.impl;

import java.util.List;

import org.springside.modules.orm.hibernate.Page;

import com.xxx.eb.model.user.User;
import com.xxx.eb.service.UserService;
import com.xxx.eb.servlet.queryUser.QueryUserService;




public class UserServiceImpl implements UserService {
   

    private QueryUserService queryUserService;



public void add(User user){
queryUserService.persist(user);
}
public void update(User user){
queryUserService.update(user);
}
public User findById(int id){
return queryUserService.findById(User.class, id);
}

public User getReferenceById(int id){
return queryUserService.getReferenceById(User.class, id);
}

public List findAll(String jpql,Object...param){

return queryUserService.findAll(jpql, param);
}

public Page find(String jpql,Page page,Object...param){
return queryUserService.find(jpql, page, param);
}
public void delete(User employee){
queryUserService.delete(employee);
}

public QueryUserService getQueryUserService() {
return queryUserService;
}
public void setQueryUserService(QueryUserService queryUserService) {
this.queryUserService = queryUserService;
}


}

7、service类在spring的配置test-service.xml内容为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
   default-lazy-init="true">

<!-- 测试服务
<property name="iBaseDao"><ref local="iBaseDao"/></property>
-->
<bean id="queryUserService" class="com.xxx.eb.servlet.queryUser.impl.QueryUserServiceImpl">

</bean>

<bean id="iBaseDao" class="com.xxx.eb.servlet.queryUser.impl.IBaseDaoImpl">
</bean>

<bean id="userService" class="com.xxx.eb.service.impl.UserServiceImpl">
<property name="queryUserService" ><ref local="queryUserService" /></property>
</bean>
</beans>


8、Util类UserServiceTest.java的内容为:
package com.xxx.eb.util;


import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.xxx.eb.model.user.User;
import com.xxx.eb.service.UserService;

public class UserServiceTest {

private static UserService userService;

@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext act = new ClassPathXmlApplicationContext("classpath*:beans/**/*.xml");
userService=(UserService)act.getBean("userService");

} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Test
public void save(){
User user=new User();

user.setUserName("SHJQ0417");
user.setPassword("88888888");

userService.add(user);

}


}
单元测试执行成功的话,说明spring和jpa的整合成功了,然后再进行spring和struts2的
整合

9、struts2的配置文件struts.xml,其内容如下:
<?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>
<!-- 默认的视图主题 -->
    <constant name="struts.ui.theme" value="simple" />
    <constant name="struts.devMode" value="true" />
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.i18n.encoding" value="utf-8"/>
<include file="/actions/struts_login.xml"></include>

<package name="struts-comm" extends="struts-default">
<global-results>
   <result name="login">/main/webapp/pub/index.jsp</result>
   </global-results>
</package>
</struts>

10、struts2和spring的整合文件applicationContext-action.xml内容为:
<?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:context="http://www.springframework.org/schema/context"
       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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
           default-autowire="byName" default-lazy-init="false">

    <!-- <context:annotation-config/> -->


<bean id="employeeManageAction" class="com.xxx.eb.view.login.EmployeeManageAction" > 
<property name="userService" ref="userService"/>
    </bean>

</beans>


11、Action类EmployeeManageAction.java的内容为:
package com.xxx.eb.view.login;

import java.text.ParseException;

import com.opensymphony.xwork2.ActionSupport;
import com.xxx.eb.model.user.User;
import com.xxx.eb.service.UserService;


public class EmployeeManageAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private UserService userService;
private User user;
private String userName;
private String password;


public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String addUI(){
return "add";
}

public String add() throws ParseException{
System.out.println("进入anction方法中.........");
user = new User();
user.setUserName(userName);
user.setPassword(password);
userService.add(user);
return "add";
}


public UserService getUserService() {
return userService;
}

public void setUserService(UserService userService) {
this.userService = userService;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}


}


12、工程启动的首页和Action用于返回的index.jsp内容如下:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>Login page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
  </head>
 
  <body>
   <form action="/my_ebw/login/user_add.action" method="post" >
    <tr>
<td>userName</td>
<td>
<input type="text" id="userName"  name="userName"  >
</td>
</tr>
<tr>
<td>passward</td>
<td><input type="password" id="password" name="password" ></td>
</tr>
    <input type="submit" value="SUBMIT">
   </form>
    <p>welcom ${user.userName}
  </body>
</html>

13、工程中用到的Log日志文件log4j.properties的内容为:
log4j.rootLogger=ERROR,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} %5p %c\:(%F\:%L) %n - %m%n


14、工程中用到的filter类EncodingFilter.java的内容为:
package com.xxx.eb.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

@SuppressWarnings("serial")
public class EncodingFilter extends HttpServlet implements Filter {
private String charset;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(charset);
chain.doFilter(request, response);
}

public void init(FilterConfig config) throws ServletException {
charset = config.getInitParameter("encoding"); 
}


/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

public String getCharset() {
return charset;
}

public void setCharset(String charset) {
this.charset = charset;
}


}


15、项目启动后,能运行出附件中的“项目运行效图”的样子,说明整个spring、jpa和struts2的整合成功了。以上所有内容是我自己做的s2sh小例子,希望能对正在学习spring, struts, jpa, hibernate的网友有所帮助
  • lib.rar (8.4 MB)
  • 下载次数: 104
  • 大小: 45 KB
  • 大小: 40 KB
0
3
分享到:
评论

相关推荐

    Struts2 + Spring2.5 + JPA(hibernate) + AJAX+ 实例

    Struts 2 + Spring 2 + JPA + hibernate + AJAX +实例, 包含依赖jar包。

    struts2+spring+jpa分页实例(带jar包和数据库脚本)

    是一个基于struts2+spring+jpa架构的分页实例(带jar包和数据库脚本)还原好数据库,用MyEclipse导入工程,部署到Tomcat就可运行。注:由于资源大小限制,我去掉了spring.jar 和 hibernate3.jar 自己加上,JDK用6.0...

    spring+struts+hibernate+dwr+jstl做的实例

    以用户管理为例,结合spring struts hibernate dwr jstl做的实例,struts hibernate dwr 与Spring完全结合,实现用户列表、信息增、删、改、查、维护时用户重名提示等功能,还包括页面自动转码设置(web.xml),...

    Struts2+Spring2.0+JPA(Hibernate3.3)实例

    服务器:tomcat6.0 可运行,http://localhost:8080/spring/test.do 其中spring为tomcat配置path属性值 主要用于演示他们之间如何配置

    网上书店系统(Struts+Hibernate)(Java EE项目案例)

    ed2k://|file|%E7%B2%BE%E9%80%9AJava.EE%E9%A1%B9%E7%9B%AE%E6%A1%88%E4%BE%8B-%E5%9F%BA%E4%BA%8EEclipse.Spring.Struts.Hibernate%E5%85%89%E7%9B%98%E6%BA%90%E7%A0%81.rar|70436209|475e7c3548acf955e89e378...

    Java EE实用开发指南

    《Java EE实用开发指南:基于Weblogic+EJB3+Struts2+Hibernate+Spring》是一本讲解如何使用Weblogicl0.3+EJB3+JPA+Struts2+Hibernate+Spring开发Java Web应用程序的实用性图书,书中在具体讲解SSH2开发技术的同时,...

    JAVA WEB典型模块与项目实战大全.part2(第二卷)

    典型模型与项目实战大全&gt;&gt; 出版社: 清华大学出版社; 第1版 (2011年1月1日) 平装: 922页 ...第26章 权限管理系统(Struts 2.X+Spring+JPA) 第27章 商业银行设备巡检系统(Struts 2.X+Spring+Hibernate)

    JAVA WEB典型模块与项目实战大全.part4

    典型模型与项目实战大全&gt;&gt; 出版社: 清华大学出版社; 第1版 (2011年1月1日) 平装: 922页 ...第26章 权限管理系统(Struts 2.X+Spring+JPA) 第27章 商业银行设备巡检系统(Struts 2.X+Spring+Hibernate)

    JAVA WEB典型模块与项目实战大全.part3(第三卷)

    典型模型与项目实战大全&gt;&gt; 出版社: 清华大学出版社; 第1版 (2011年1月1日) 平装: 922页 ...第26章 权限管理系统(Struts 2.X+Spring+JPA) 第27章 商业银行设备巡检系统(Struts 2.X+Spring+Hibernate)

    JAVA WEB典型模块与项目实战大全.part1(第一卷)

    典型模型与项目实战大全&gt;&gt; 出版社: 清华大学出版社; 第1版 (2011年1月1日) 平装: 922页 ...第26章 权限管理系统(Struts 2.X+Spring+JPA) 第27章 商业银行设备巡检系统(Struts 2.X+Spring+Hibernate)

    spring2.5学习PPT 传智博客

    28.Struts与Spring集成方案2(Spring集成Struts) 29.为Spring集成的Hibernate配置二级缓存 30.Spring提供的CharacterEncoding和OpenSessionInView功能 31.使用Spring集成JPA 32.Struts+Spring+JPA集成 33.使用...

    spring-hibernate-dwr实例

    spring-hibernate-dwr做的AJAX操作CRUD实例 环境:myeclipse6.0+jdk1.6 所需lib列表,请自行加入 mysql-connector-java-3.1.7-bin.jar antlr-2.7.6rc1.jar asm-attrs.jar cglib-2.1.3.jar ...

    学习struts2,hibernate3(jpa注释编程),spring2,ajax的经典实例

    这个整合与我公司的差不多 不过我公司的是使用了泛型的替换 希望大家喜欢,jar包因为很大 所以我要分开上传 敬请关注

    JQuery,ajax,hibernate+spring,分页查询.rar

    网上找的一些资料: hibernate+spring的一个简单分页实现; 利用JQuery方便实现基于Ajax的数据查询、排序和分页功能; Hibernate+Struts分页代码

    自己做的SSH2自动生成数据库表的实例

    因为数据库处理未实现,此实例只是说明动态生成数据库表,如果要实现数据操作 可以自行定义方法,希望大家能够理解spring和hibernate 本资例只是说明jpa和hibernate的配置关系及spring的关系 如果需要jar包请与我...

    Spring 2.5 jar 所有开发包及完整文档及项目开发实例

    Spring 2.0的'spring-jdo.jar', 'spring-jpa.jar', 'spring-hibernate3.jar', 'spring-toplink.jar' 和 'spring-ibatis.jar' 被合并到Spring 2.5大粒度的'spring-orm.jar'中。 Spring 2.5的 'spring-test.jar' 取代...

    学习SSH2经典实例的jar包3

    学习struts2,hibernate3(jpa注释编程),spring2,ajax的经典实例 的jar包第三部分 总共为五部分

Global site tag (gtag.js) - Google Analytics