jpa+spring+stuct整合


  下面就对今天的jpa+spring+stuct进行总结也希望这篇文章对您有帮助,下面我们就开始搭建环境(注:jpa只是一种规范他的实现产品有hibernate、lbatis等)及一个简单的注册例子来测试框架是否整合完成

  环境所需*.jar

这里JPA的实现采用hibernate,需要使用到下面的jar文件

Hiberante核心包(8个文件)
hibernate-distribution-3.3.1.GA
---------------------------------------------
hibernate3.jar
lib\bytecode\cglib\hibernate-cglib-repack-2.1_3.jar
lib\required\*.jar

Hiberante注解包(3个文件):hibernate-annotations-3.4.0.GA
------------------------------------------------------------------------------------
hibernate-annotations.jar
lib\ejb3-persistence.jar、hibernate-commons-annotations.jar

Hibernate针对JPA的实现包(3个文件):hibernate-entitymanager-3.4.0.GA
------------------------------------------------------------------------------------------------------
hibernate-entitymanager.jar
lib\test\log4j.jar、slf4j-log4j12.jar

spring的*.jar

dist\spring.jar
lib\jakarta-commons\commons-logging.jar
如果使用了切面编程(AOP),还需要下列jar文件
lib/aspectj/aspectjweaver.jar和aspectjrt.jar
lib/cglib/cglib-nodep-2.1_3.jar
如果使用了JSR-250中的注解,如@Resource/@PostConstruct/@PreDestroy,还需要下列jar文件
lib\j2ee\common-annotations.jar


struct的*.jar


下载struts-1.3.8-lib.zip,需要使用到解压目录下的所有jar,建议把jstl-1.0.2.jar和standard-1.0.2.jar更换为1.1版本。Spring中已经存在一个antlr-2.7.6.jar,所以把struts中的antlr-2.7.2.jar删除,避免jar冲突。
数据库驱动jar

导入完所需的*.jar文件后...

第一步: 首先配置spring的配置文件如下:

<?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/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="itcast"/>
   </bean>
  <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory"/>
  </bean>
  <tx:annotation-driven transaction-manager="txManager"/>

</beans>

第二步:在src目录先新建一个META-INF文件夹,在该文件夹中根据jpa的规范编写一个persistence.xml内容如下:

<?xml version="1.0"?>
<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="itcast" transaction-type="RESOURCE_LOCAL">
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
         <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>
         <property name="hibernate.connection.username" value="root"/>
         <property name="hibernate.connection.password" value="liyong"/>
         <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&amp;characterEncoding=UTF-8"/>
         <property name="hibernate.max_fetch_depth" value="3"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
      </properties>
  </persistence-unit>
</persistence>

第三步:配置struct配置文件struts-config.xml文件如下

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
        "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>

<!-- 让struct1.x中的action交个spring管理 -->
<controller>
<set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor"/>
</controller>
<!-- 用做国际化 -->
<message-resources parameter="MessageResources"/>


</struts-config>

第四步:接下来在web.xml文件中配置spring的启动信息

<!-- 指定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>

<!-- 配置actionservlet -->
<servlet>
<servlet-name>struts</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>struts</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

到这来环境搭建算是完成但是我们的需解决中文乱码的文件和entityManager关闭解决懒加载问题:

  <!-- 解决乱码 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 使用spring解决JPA因EntityManager关闭导致的延迟加载例外问题。-->
<filter>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

到此为止环境搭建才算是真正的完成恭喜您...
 
接下来我们结合到一个注册例子来验证框架的搭建
 
我们从页面端开始做起新建一个注册页面regester.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <title>注册页面</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>
<!-- <%=request.getContextPath() %>/login.do -->
<!-- /SS1.x/login.do -->
<!-- login.do -->
   <form action="person/add.do" method="post">
用户名:<input type="text"  name="name"> <br>
<input type="submit" value="提交">
</form>
  </body>
</html>

注册成功和注册失败的页面fail.jsp和login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <title>登陆...</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>
   登陆失败
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <title>登陆...</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>
  登陆成功...
  </body>
</html>

在新建一个首页进行登录login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    <title>登陆</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>
 
   <a href="login.jsp">登录</a>
  </body>
</html>


首先建立实体映射bean Person.java

package com.liyong.beans;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person implements Serializable{

private Integer id;
private String name;

public Person(){}
public Person(String name){

this.name=name;
}
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=10,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}


}

编写业务代码层 PersonService.java

package com.liyong.service.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.liyong.beans.Person;
import com.liyong.service.IPsersonService;

@Transactional
public class PersonService {

//注入EntityManager
@PersistenceContext EntityManager entityManager;

/* (non-Javadoc)
* @see com.liyong.service.impl.IPsersonService#save(com.liyong.beans.Person)
*/
public void save(Person person){

entityManager.persist(person);
}

/* (non-Javadoc)
* @see com.liyong.service.impl.IPsersonService#update(com.liyong.beans.Person)
*/
public void update(Person person)
{
entityManager.merge(person);
}

/* (non-Javadoc)
* @see com.liyong.service.impl.IPsersonService#getPerson(java.lang.Integer)
*/
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
public Person getPerson(Integer id)
{

return entityManager.find(Person.class, id);
}
//不支持事务
/* (non-Javadoc)
* @see com.liyong.service.impl.IPsersonService#getPersons()
*/
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
@SuppressWarnings("unchecked")
public List<Person> getPersons()
{
return entityManager.createQuery("select o from Person o").getResultList();

}
}

我们需要面向借口编程所以得抽取接口IPsersonService.java


package com.liyong.service;

import java.util.List;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.liyong.beans.Person;

public interface IPsersonService {

public abstract void save(Person person);

public abstract void update(Person person);

@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
public abstract Person getPerson(Integer id);

//不支持事务
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
@SuppressWarnings("unchecked")
public abstract List<Person> getPersons();

}

对业务逻辑层进行单元测试

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

import com.liyong.beans.Person;
import com.liyong.service.IPsersonService;

public class PersonServiceTest {


private static IPsersonService personService=null;

@BeforeClass
public static void setUpBeforeClass() throws Exception {

try {

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
personService=(IPsersonService)context.getBean("personSevice");
System.out.println(personService);

} catch (Exception e) {
e.printStackTrace();
}
}

@Test
public void save()
{
Person person=new Person("xiaoming");
personService.save(person);
}

   ..................
}


然后是一个ActonForm PersonForm.java

package com.liyong.formbean;

import org.apache.struts.action.ActionForm;

public class PersonForm extends ActionForm {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


}


接下来我们来新建一个Action PersonAction.java

package com.liyong.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.liyong.beans.Person;
import com.liyong.formbean.PersonForm;
import com.liyong.service.impl.PersonService;

public class PersonAction extends Action {
//注入personSevice这个得需要把PersonSevice交给spring管理
@Resource PersonService personSevice;

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
PersonForm personForm=(PersonForm)form;
Person person=new Person(personForm.getName());
try {
personSevice.save(person);
} catch (Exception e) {

e.printStackTrace();
return mapping.findForward("fail");
}

return mapping.findForward("success");
}
}

 
接下来需要在struts-config.xml中配置form-bean 和action

<form-beans>
<form-bean name="personFromBean" type="com.liyong.formbean.PersonForm" >
</form-bean>
</form-beans>
<action-mappings>
<action path="/person/add" scope="request" validate="false" name="personFromBean">
<forward name="success" path="/success.jsp"/>
<forward name="fail" path="/fail.jsp"/>
</action>
</action-mappings>

然后在spring的配置文件中注入bean

  <bean id="personSevice" class="com.liyong.service.impl.PersonService"></bean>
  <!-- 因为这个bean交个了spring来管理所有不能使用id只能使用name这个name 和这个Action的访问路径path相同 -->
  <bean name="/person/add" class="com.liyong.action.PersonAction"></bean>


项目完成....祝您成功!!!

你可能感兴趣的:(spring)