Spring+Hibernate+Jpa+Struts2整合实例

来源:互联网 发布:stc单片机usb驱动下载 编辑:程序博客网 时间:2024/05/28 15:32
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的网友有所帮助
原创粉丝点击