Struts 2 + Spring 2 + JPA + AJAX

Source: Internet
Author: User
Tags aop documentation prepare apache tomcat
Added by Musachy Barroso, last edited from Ted Husted on, and 2007 (view change)

On this tutorial we'll demonstrate how to setup Struts 2 in Eclipse, and make it work with Spring, Java persistence API (using Hibernate) and Struts 2 Ajax tags.

Note:following This tutorial verbatim'll require use of a Struts 2 deployment greater than 2.0.3 show me the code

can just download the zipped Eclipse Project, add the required dependencies to the Lib folder under The/webconten T/web-inf/lib folder (relative to project "s root folder) and import it into Eclipse. Prerequisites Struts 2 Tomcat 5.5 eclipse Eclipse WTP Hibernate Core Hibernate annotations Hibe Rnate Entity Manager mysql Server mysql JDBC Driver Spring 2.0 Tomcat

Install Tomcat before going forward. Installation Guide If you are have any problem installing it. MySql

Install and configure MYSQL. Create a database named "QuickStart" and run the script below to create the "person" table. Later, on Applicationcontext.xml, we'll use ' root ' as the user name and password for the database, remember to replace tho SE values with the right ones for your database.

CREATE TABLE ' QuickStart '. Person ' (
' ID ' INTEGER UNSIGNED not NULL auto_increment,
' FirstName ' VARCHAR not NULL,
' LastName ' VARCHAR not NULL,
PRIMARY KEY (' id ')
)
ENGINE = InnoDB;
Create Eclipse Project Open Eclipse. Seriously, you are 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. The project would be running inside Tomcat and 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 a installed JRE (1.5 is required) Now you should being 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.

from
Jar
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's jars that we just added). Domain

Our domain model would 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 would 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'll let the provider know so this class can is persisted. @Id marks the "Id" field as the primary key for T His class. @GeneratedValue would cause the ID field to is generated by the provider (Hibernate). Classes and fields are by default mapped to tables and columns with the same name, and then the JPA ' s documentation for more detail S. Person service.

We'll now write the class that would take care of the 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 N Amespace. 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'll make Spring inject a entitymanager into the service as it is instantiated. The @PersistenceContext annotation can is placed on the field, or on the setter method. If the class is annotated as @Transactional, Spring'll make sure it 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 is set on this file. On this example it'll be empty because the datasource configuration'll be on the Spring configuration file. Spring Update The content of Web.xml Under/webcontent/web-inf/web.xml to: web.xml /c8>

<?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'll make the container redirect all requests to Struts "Filterdispatcher" class. The "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>

The

Note this "class" attribute of the Bean "Personaction" is set to the name of the action class, and the "Personse" Rvice "Bean would 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 further details on the rest of the beans on this file, to the documentation of Spring. The "Scope" attribute is new in Spring 2, and it means that Spring would create a new Personaction object every time a obj ECT of that type is requested. In Struts 2 A new Action object are created to serve each request, that ' s why we need scope= ' prototype '. Struts

We'll now create a simple struts action that wraps personservices methods, and we'll 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 me action is a simple pojo!
The "Preparable" interface instructs Struts to called the "prepare" method if the "Prepareinterceptor" was applied to the Act Ion (by default, it is). The constructor of the action takes a "Personservice" as a parameter, which Spring would take care of passing when the ACTI On is instatiated. Create a new file named "Struts.xml" under "src" folder. and set its content to:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.