`
javaping2008
  • 浏览: 106462 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

sturts2.0 jpa spring

阅读更多

Prerequisites
Struts 2
Tomcat 5.5
Eclipse
Eclipse WTP
Hibernate Core
Hibernate Annotations
Hibernate Entity Manager
MySql Server
Mysql JDBC Driver
Spring 2.0
Tomcat
安装Tomcat。

MySql
安装配置MySql. 建立一个 数据库 ,命名为 quickstart,然后运行以下 sql 脚本语句。在 applicationContext.xml 中,我们将使用 root 作为访问数据库的用户名和密码,你可以修改你的数据库的用户名。也可以修改 applicationContext.xml 文件中的配置。

sql 代码

CREATE TABLE 'quickstart'.'Person' (
'id' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
'firstName' VARCHAR(45) NOT NULL,
'lastName' VARCHAR(45) NOT NULL,
PRIMARY KEY('id')
)
ENGINE = InnoDB;
Create Eclipse project
Open Eclipse. Seriously, you need to open Eclipse.
Click File -> New -> Project. Under the "Web" folder, select "Dynamic Web Project" and click "Next".
Enter the project name, "quickstart" from here on. The project will be running inside Tomcat, so we need to create a server configuration for it.
Under "Target Runtime", click "New", select "Apache Tomcat 5.5" and click next.
Enter Tomcat's installation directory and select an installed JRE (1.5 is required)
Now you should be back to the project creation wizard, with Tomcat as your Target Runtime. Click "Next". Select "Dynamic Web Module" and "Java" facets, and click "Finish".
Dependencies
Your project should contain the folders "src", "build" and "WebContent". We are going to put all the required jars under "/WebContent/WEB-INF/lib". To add files to the "lib" folder, just copy them to ${workspace}\quickstart\WebContent\WEB-INF\lib, where ${workspace} is the location of your Eclipse workspace folder. The version has been removed from the jar files.
Jar From
xwork.jar Struts 2
struts2-api.jar Struts 2
struts2-core.jar Struts 2
struts2-Spring-plugin.jar Struts 2
ognl.jar Struts 2
freemarker-2.3.4.jar Struts 2
mysql-connector-java.jar MySql JDBC Driver
spring.jar Sping 2.0
antlr.jar Hibernate Core
asm.jar Hibernate Core
asm-attrs.jar Hibernate Core
cglib.jar Hibernate Core
dom4j.jar Hibernate Core
jdbc2_0-stdext.jar Hibernate Core
ehcache.jar Hibernate Core
hibernate3.jar Hibernate Core
xml-apis.jar Hibernate Core
commons-collections.jar Hibernate Core
ejb3-persistence.jar Hibernate Annotations
jta.jar Hibernate Annotations
hibernate-annotations.jar Hibernate Annotations
hibernate-entitymanager.jar Hibernate Entity Manager
javassist.jar Hibernate Entity Manager
jboss-archive-browsing.jar Hibernate Entity Manager

Right click on the project and select "Refresh" (to notify Eclipse of the jars that we just added).

Domain
Our domain model will consist of just a simple "Person" class with a couple of fields.

Create a new class named "Person" (File -> New -> Class), and enter "quickstart.model" for the package name.
Add the fields "id" (int), "firstName" (String), and lastName ("String") with their setter/getter methods.
Mark your class with the "@Entity" annotation, and the "id" field with the annotations "@Id" and "@GeneratedValue".
your class will look like:

Person.java

package quickstart.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {
@Id
@GeneratedValue
private Integer id;
private String lastName;
private String firstName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}
} @Entity will let the provider know that this class can be persisted. @Id marks the "id" field as the primary key for this class. @GeneratedValue will cause the id field to be generated by the provider (Hibernate). Classes and fields are by default mapped to tables and columns with the same name, see JPA's documentation for more details.

Person service.
We will now write the class that will take care of CRUD operations on "Person" objects.

Create a new interface (File -> New -> Interface), enter "PersonService" for the name, and "quickstart.service" for the namespace. Set its content to:

PersonService.java

package quickstart.service;

import java.util.List;

import quickstart.model.Person;

public interface PersonService {
public List<Person> findAll();

public void save(Person person);

public void remove(int id);

public Person find(int id);
} Create a new class (File -> New -> Class), enter "PersonServiceImpl" for the name and "quickstart.service" for the namespace. Set its content to:

PersonServiceImpl.java

package quickstart.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import quickstart.model.Person;

@Transactional
public class PersonServiceImpl implements PersonService {
private EntityManager em;

@PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}

@SuppressWarnings("unchecked")
public List<Person> findAll() {
Query query = getEntityManager().createQuery("select p FROM Person p");
return query.getResultList();
}

public void save(Person person) {
if (person.getId() == null) {
// new
em.persist(person);
} else {
// update
em.merge(person);
}
}

public void remove(int id) {
Person person = find(id);
if (person != null) {
em.remove(person);
}
}

private EntityManager getEntityManager() {
return em;
}

public Person find(int id) {
return em.find(Person.class, id);
}

} @PersistenceContext will make Spring inject an EntityManager into the service when it is instantiated. The @PersistenceContext annotation can be placed on the field, or on the setter method. If the class is annotated as @Transactional, Spring will make sure that its methods run inside a transaction.

JPA configuration
Create a folder named "META-INF" under the "src" folder.
Create a file named "persistence.xml" under the "META-INF" folder and set its content to:

persistence.xml

<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="punit">
</persistence-unit>
</persistence>

JPA configuration can be set on this file. On this example it will be empty because the datasource configuration will be on the Spring configuration file.

Spring
Update the content of web.xml under /WebContent/WEB-INF/web.xml to:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="person" version="2.4" 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">
<display-name>person</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</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>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
This will make the container redirect all requests to Struts "FilterDispatcher" class. "index.jsp" is set as the home page, and Spring's "ContextLoaderListener" is configured as a listener.

Create a file named "applicationContext.xml" under /WebContent/WEB-INF, and set its content to:

applicationContext.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: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.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<bean id="personService" class="quickstart.service.PersonServiceImpl" />

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>

<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="personAction" scope="prototype"
class="quickstart.action.PersonAction">
<constructor-arg ref="personService" />
</bean>
</beans>
Note that the "class" attribute of the bean "personAction" is set to the name of the action class, and the "personService" bean will be passed as a parameter to the action constructor. Change the "url", "username" and "password" in the "dataSource" bean to the appropiate values for your database. For more details on the rest of the beans on this file, see Spring's documentation. The "scope" attribute is new in Spring 2, and it means that Spring will create a new PersonAction object every time an object of that type is requested. In Struts 2 a new action object is created to serve each request, that's why we need scope="prototype".

Struts
We will now create a simple Struts action that wraps PersonServices methods, and we will configure Struts to use Spring as the object factory.

Open the new class dialog (File -> New -> Class) and enter "PersonAction" for the classname, and "quickstart.action" for the namespace. Set its content to:

PersonAction.java

package quickstart.action;

import java.util.List;

import quickstart.model.Person;
import quickstart.service.PersonService;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.Preparable;

public class PersonAction implements Preparable {
private PersonService service;
private List<Person> persons;
private Person person;
private Integer id;

public PersonAction(PersonService service) {
this.service = service;
}

public String execute() {
this.persons = service.findAll();
return Action.SUCCESS;
}

public String save() {
this.service.save(person);
this.person = new Person();
return execute();
}

public String remove() {
service.remove(id);
return execute();
}

public List<Person> getPersons() {
return persons;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public void prepare() throws Exception {
if (id != null)
person = service.find(id);
}

public Person getPerson() {
return person;
}

public void setPerson(Person person) {
this.person = person;
}
}
Look mom my action is a simple POJO!
The "Preparable" interface instructs Struts to call the "prepare" method if the "PrepareInterceptor" is applied to the action (by default, it is). The constructor of the action takes a "PersonService" as a parameter, which Spring will take care of passing when the action is instatiated.

Create a new file named "struts.xml" under the "src" folder. And set its content to:

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.objectFactory" value="spring" />
<constant name="struts.devMode" value="true" />

<package name="person" extends="struts-default">

<action name="list" method="execute" class="personAction">
<result>pages/list.jsp</result>
<result name="input">pages/list.jsp</result>
</action>

<action name="remove" class="personAction" method="remove">
<result>pages/list.jsp</result>
<result name="input">pages/list.jsp</result>
</action>

<action name="save" class="personAction" method="save">
<result>pages/list.jsp</result>
<result name="input">pages/list.jsp</result>
</action>
</package>

</struts>
Setting "struts.objectFactory" to "spring" will force Struts to instantiate the actions using Spring, injecting all the defined dependencies on applicationContext.xml. The "class" attribute for each action alias is set to "personAction", which is the bean id that we defined on applicationContext.xml for the PersonAction class. This is all that is needed to make Struts work with Spring.

The pages
We only have two pages, "index.jsp" and "list.jsp". "list.jsp" returns a table with a list of the persons on the database.We have this list on a different page because we are going to add some AJAX to spicy it up.

Create a new file named "list.jsp" under /WebContent/pages/ and set its content to:

list.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>

<p>Persons</p>
<s:if test="persons.size > 0">
<table>
<s:iterator value="persons">
<tr id="row_<s:property value="id"/>">
<td>
<s:property value="firstName" />
</td>
<td>
<s:property value="lastName" />
</td>
<td>
<s:url id="removeUrl" action="remove">
<s:param name="id" value="id" />
</s:url>
<s:a href="%{removeUrl}" theme="ajax" targets="persons">Remove</s:a>
<s:a id="a_%{id}" theme="ajax" notifyTopics="/edit">Edit</s:a>
</td>
</tr>
</s:iterator>
</table>
</s:if>

This is going to render a table with each row showing the first and last name of the person, a link to remove the person, and a link to edit. The remove link has the attribute "targets", set to "persons", which means that when the user clicks on it, an asynchronous request will be made to the "remove" action (as configured on struts.xml, "remove" points to the "remove" method in PersonAction), passing the person id as parameter.

When the edit link is clicked on, it will publish the "/edit" topic, which will trigger a javascript function to populate the fields.

Create a new file named "index.jsp" under /WebContent and set its content to:

index.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<s:head theme="ajax" debug="true"/>
<script type="text/javascript">
dojo.event.topic.subscribe("/save", function(data, type, request) {
if(type == "load") {
dojo.byId("id").value = "";
dojo.byId("firstName").value = "";
dojo.byId("lastName").value = "";
}
});

dojo.event.topic.subscribe("/edit", function(data, type, request) {
if(type == "before") {
var id = data.split("_")[1];

var tr = dojo.byId("row_"+id);
var tds = tr.getElementsByTagName("td");

dojo.byId("id").value = id;
dojo.byId("firstName").value = dojo.string.trim(dojo.dom.textContent(tds[0]));
dojo.byId("lastName").value = dojo.string.trim(dojo.dom.textContent(tds[1]));
}
});
</script>
</head>
<body>
<s:url action="list" id="descrsUrl"/>

<div style="width: 300px;border-style: solid">
<div style="text-align: right;">
<s:a theme="ajax" notifyTopics="/refresh">Refresh</s:a>
</div>
<s:div id="persons" theme="ajax" href="%{descrsUrl}" loadingText="Loading..." listenTopics="/refresh"/>
</div>

<br/>

<div style="width: 300px;border-style: solid">
<p>Person Data</p>
<s:form action="save" validate="true">
<s:textfield id="id" name="person.id" cssStyle="display:none"/>
<s:textfield id="firstName" label="Fisrt Name" name="person.firstName"/>
<s:textfield id="lastName" label="Last Name" name="person.lastName"/>
<s:submit theme="ajax" targets="persons" notifyTopics="/save"/>
</s:form>
</div>
</body>
</html>
Look mom no page refresh!
The div "persons" will load its content asynchronously, and will show "Loading..." while while the request is on progress (you can use the "indicator" attribute for better progress feedback), you can force it to refresh clicking on the "Refresh" link. The "submit" button, will make an asynchronous request to the action "save" ("save" method on PersonAction), and will publish the topic "/save" to which we subscribed to, using "dojo.event.topic.subscribe", to clear the input fields.

Validation
Because we don't want any John Doe on our database, we will add some basic client side validation to our form. In Struts 2, validation can be placed on xml files with the name pattern ActionName-validation.xml, located on the same package as the action. To add validation to an specific alias of an action (like a method), the validation file name follows the pattern ActionName-alias-validation.xml, where "alias" is the action alias name (in this case a method name, "save"). Add a file named "PersonAction-save-validation.xml" under /src/quickstart/action, and set its content to:

xml 代码

<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="person.firstName">
<field-validator type="requiredstring">
<message>First name is required!</message>
</field-validator>
</field>
<field name="person.lastName">
<field-validator type="requiredstring">
<message>Last name is required!</message>
</field-validator>
</field>
</validators>
See the Struts documentation for details on existing validators, and how to write, and plug in, your own validators.

To run the project, Right click on your project and Run As -> Run on Server. You can debug it on the same way, Right click on the project and Debug As -> Debug on Server. Download and install Struts 2 Showcase to see more examples.

References
Struts
Spring JPA Doc
JPA and Spring Tutorial
Eclipse Dali

分享到:
评论

相关推荐

    EXt2.1+sturts2.0+spring2.5+hibernate

    标题中的"EXt2.1+sturts2.0+spring2.5+hibernate"是一个典型的Java Web开发技术栈,它包含了四个关键组件:EXT JS 2.1、Struts 2.0、Spring 2.5和Hibernate。这些技术在2000年代末至2010年代初是非常流行的,它们...

    Sturts2.0+Hibernate+Spring 简单的例子

    Struts2.0、Hibernate和Spring是Java Web开发中的三大框架,它们的集成使用能构建出高效、可维护的Web应用程序。在这个简单的例子中,我们将深入理解这三个框架如何协同工作,以及它们各自的核心功能。 首先,...

    sturts2.0项目代码

    在"sturts2.0项目代码"中,我们可以看到一个初学者学习并实践Struts2.0框架的过程,这些代码主要涵盖了基础的使用场景。 1. **模型(Model)**:在Struts2中,模型通常由JavaBeans或POJO(Plain Old Java Object)...

    sturts2.0的源代码

    Struts2.0是Apache软件基金会的一个开源框架,主要用于构建基于Java的企业级Web应用程序。它在Struts1的基础上进行了重大改进,提供了更强大的功能和更好的灵活性。深入理解Struts2的源代码对于开发者来说,不仅可以...

    Sturts2.0.11.2源代码

    在Struts2.0.11.2版本中,该框架提供了一系列更新和改进,旨在提高应用程序的安全性、性能以及开发效率。这个版本的源代码包含了许多关键组件和模块,下面我们将深入探讨Struts2.0.11.2中的核心知识点。 1. **核心...

    Sturts2.0.11.2jar包

    "lib"目录通常包含所有依赖的JAR文件,这些文件是运行Struts2应用程序所必需的,如Spring、Log4j、Commons等Apache Commons库,以及其他的第三方库。 在实际开发中,使用Struts2.0.11.2jar包时,开发者需要确保所有...

    Sturts2.0 网上购物例子

    Struts2.0是一个强大的MVC(Model-View-Controller)框架,用于构建高效、可扩展的Web应用程序。网上购物系统是使用Struts2.0框架实现的一个具体应用实例,它展示了如何在实际环境中整合该框架来处理用户交互、业务...

    sturts2.0+Extjs文件上传2

    实现了多文件上传,下载,压缩,解压缩,用struts2.0+Extjs实现,是第二部分,分享一下希望对大家有所帮助

    Struts2整合Spring、JPA

    Struts2整合Spring和JPA是企业级Java应用开发中常见的技术组合,它们分别负责不同的职责:Struts2作为一款成熟的MVC框架,主要用于处理Web层的请求与响应;Spring作为一个全面的轻量级框架,提供了依赖注入(DI)和...

    sturts2+jpa+spring

    在构建企业级Java应用时,`Struts2`、`JPA`(Java Persistence API)和`Spring`框架的整合是常见的技术栈选择。这些框架分别负责不同的职责:`Struts2`作为MVC(Model-View-Controller)架构中的控制器,`JPA`用于...

    sturts2 hibernate spring

    ### Struts2、Hibernate与Spring整合开发知识点梳理 #### 一、基础知识概览 - **JavaEE应用概述**: - **分层模型**:JavaEE应用通常采用分层架构,包括表示层、业务逻辑层、数据访问层等。 - **组件**:JavaEE中...

    sturts2+spring+hibernate+dwr2

    结合上述四个框架,"sturts2+spring+hibernate+dwr2例子"很可能是展示如何在实际项目中整合这些技术的一个示例应用。"springch01"这个文件名可能代表了关于Spring的初步章节或者配置文件,包含了Spring容器的配置,...

    struts1.2+spring2.0+hibernate3.0所需要的包

    struts1.2+spring2.0+hibernate3.0所需要的包 struts1.2+spring2.0+hibernate3.0所需要的包 struts1.2+spring2.0+hibernate3.0所需要的包 struts1.2+spring2.0+hibernate3.0所需要的包

    关于sturts2,spring,ibatis

    Struts2、Spring和iBatis是Java Web开发中的三个重要框架,它们分别在MVC模式的控制器层、业务逻辑层和服务数据访问层扮演关键角色。这个例子旨在演示这三个框架如何协同工作,以构建高效、模块化的Web应用程序。 ...

    java开发常用架包,sturts2,spring,json,druid架包

    标题中的"java开发常用架包,sturts2,spring,json,druid架包"提到了几个在Java开发中非常关键的框架和技术。这里我们将深入探讨这些技术及其在Java Web开发中的应用。 1. **Struts2**:Struts2是基于MVC(Model-...

    sturts2 hibernate spring 小型项目

    在IT行业中,SSH2(Struts2、Hibernate、Spring)是一个经典的Java开发框架组合,用于构建企业级Web应用程序。这个小型项目"babasport"很可能是一个体育相关的网站或应用,利用SSH2框架来实现其功能。 **Struts2** ...

    学生信息系统(使用了Sturts+Spring+Hibernate技术)

    《基于Struts+Spring+Hibernate的学生信息系统解析》 在当今的Web开发领域,Struts、Spring和Hibernate这三大框架的组合应用已经成为了构建企业级应用的常见选择。本项目“学生信息系统”就是一个典型的实例,它...

    sturts2+spring2.5+hibernate3.5+c3p0+log4j整合示例项目

    本项目是一个基于Struts2、Spring2.5、Hibernate3.5的整合示例,其中还引入了c3p0作为数据库连接池,并使用了日志工具Log4j。这个项目的目的是帮助开发者理解如何在实际开发中快速、有效地整合这四个关键组件,从而...

    AutoCode代码生成器(SSH版)

    Sturts2.0配置--&gt; sturts.xml、struts.properties Spring2.0配置--&gt; applicationContext.xml Hibernate3.2配置--&gt; hibernate.cfg.xml JSP文件--&gt; 具有Struts2.0支持的增、删、改、查页面及自定义查询、自动分页等...

    jpetstore4.0 (spring+struts+ibatis)

    《基于Spring、Struts和iBatis的jpetstore4.0详解》 jpetstore4.0是一款经典的电子商务示例应用,它采用Spring、Struts和iBatis这三个核心框架构建,展示了如何在Java环境下实现一个完整的MVC(Model-View-...

Global site tag (gtag.js) - Google Analytics