JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Struts 2 + Spring Integration Example

December 15, 2013 by Krishna Srinivasan Leave a Comment

Struts 2 provides plug-ins for integration to any other frameworks. If you are using Spring for your bean management, then it is very easy for you to integrate Spring container to Struts 2 application. Spring can manage the beans and struts actions classes as beans. You have to just specify the bean name in the struts configuration file. The following steps to be taken for the Struts 2 and Spring integration.

  1. Download the Struts2-Spring-plugin.jar. It is the library which integrates both the frameworks.
  2. Add Spring libraries into the lib folder
  3. Add context loader in the web.xml for loading the spring configuration file.

Struts 2 Spring JAR Files

The above steps are the additional tasks which you have to do with the Struts 2 application for enabling the integration. This tutorial shows a very simple example for the integration. Lets look at the example code.

1. Action Class and Bean

Write a action class and declare a bean which will be injected from the spring container with default values.

[code lang=”java”]
package javabeat.net.struts2;
public class Struts2SpringIntegrationAction {
//Spring Injection
private UserDetails userDetails;

public UserDetails getUserDetails() {
return userDetails;
}

public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}

public String execute(){
return "success";
}
}
[/code]

UserDetails.java

[code lang=”java”]
package javabeat.net.struts2;

public class UserDetails {
private String userName;

public String getUserName() {
return userName;
}

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

}
[/code]

2. Spring Configuration File

It is the traditional spring configuration file for declaring the spring beans. Note that here I have declared Struts action class as the spring beans and injected UserDetails beans to the action class.

applicationContext.xml

[code lang=”xml”]
<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">
<bean id="userDetails" class="javabeat.net.struts2.UserDetails">
<property name="userName" value="Rahul Dravid"/>
</bean>
<bean id="struts2Spring" class="javabeat.net.struts2.Struts2SpringIntegrationAction">
<property name="userDetails" ref="userDetails"/>
</bean>
</beans>[/code]

3. Struts 2 Configuration File

Struts 2 configuration file would use the spring’s bean name in the class attribute of the action mapping.

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="uitagsdemo" extends="struts-default">
<action name="Struts2Spring" class="struts2Spring" >
<result name="success">Result.jsp</result>
</action>
</package>
</struts>[/code]

4. JSP File

Write a simple JSP to print the values.

Result.jsp

[code lang=”xml”]
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<h2>JavaBeat – Struts 2 Spring Integration Demo</h2>
<h4>
<s:push value="userDetails">
User Name : <s:property value="userName" /><br>
</s:push>
</h4>
</body>
</html>
[/code]

5. Web.xml

There are two entries in the web.xml

  1. Struts 2 filter and
  2. Spring configuration loader

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<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>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>

[/code]

6. Struts 2 Spring Integration Demo

If you access the application using URL http://localhost:8080/Struts2App/Struts2Spring, you would see the following output.

Struts 2 Spring Integration Example

Filed Under: Struts Tagged With: Spring Integration, Struts 2 Tutorials, Struts Integration

Struts 2.0 and JPA Integration

February 28, 2011 by Krishna Srinivasan Leave a Comment

Struts 2.0 is the popular Open Source Presentation Tier framework developed by Apache Group. It is based on MVC Model 2 design pattern. Dispatcher Filter is the front controller for the struts2 based applications. Struts 2.0 has simplified web development for its users by introducing POJO based actions, interceptors, flexible validation and support for many different result types.

also read:

  • Struts 2 Tutorials
  • Struts Interview Questions
  • Struts and Spring Integration

Struts can be used to build the user interface tier of the enterprise application. Whereas, any of the popular ORMs like Hibernate, JPA, iBatis can be used for the persistence tier of the application. Struts2 provides easy integration with these persistence tier frameworks.

This article demonstrates the integration of Struts 2.0 applications with the Java Persistence API (JPA). The concept is explained with the help of a sample application. Knowledge of JPA and Struts 2.0 is the prerequisite for this article.

Development Environment

  • NetBeans IDE 6.8
  • GlassFish V2.x
  • Apache Derby Database

Project Structure

The sample application developed in this article is “StrutsJPADemo” where an employee details are persisted to the database with the help of JPA.

Libraries/Jar Files Required

  • Struts 2.0 jar files
  • JPA jar files
  • Jar file for the database driver (derbyclient.jar, in our case) The complete application structure is shown below:
  • The User Interface (JSP pages) is created in the “Web Pages” directory. The java classes (Actions, Entities, Service classes, Resource Bundles, struts.xml) are created in the “Source Packages” directory. The required jar files are present in the “Libraries” directory. The web application deployment descriptor “web.xml” is created by the IDE in the “WEB-INF” subdirectory of “Web Pages”. This sample application stores the employee details into the Derby database.

Environment Set Up

Once the web application is created and all the required libraries are added to the classpath, we can start working on the different components of the application.

Before we start working on the different application components like JSP pages and Java classes, we must first configure the following resources in the application server:

  1. javax.transaction.UserTransaction
  2. In our application, we have created a UserTransaction and bound the same in JNDI with the name “UserTransaction”. The snapshot given below shows the same.
  3. Connection Pool & DSN
  4. For the database, we have created a connection pool in the application server to connect to ScrambleDatabase in the local machine running at port number 1527. The connection pool is bound to the name “scramblePool” as shown in the snapshot below.
  5. The next step is to configure the DSN in the application server. Our DSN is bound to the name “jdbc/scramdleDSN” in JNDI. This is shown below in the snapshot. This DSN will use “scramblePool”created in the previous step.

Create Entity Class in JPA

The entity class for our application “Employee.java” is created in the package “com.model.entities”.PFB the code of
“Employee.java”

[code lang=”java”]package com.model.entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Employee {
@Id
private String empid;
private String password;
private String password1;
private String empname;
private int age;
private String city;
private String email;
//getters & setters for all the attributes
}[/code]

Service Layer

The service layer exposes an interface “EmployeeService” and an implementation class “EmployeeServiceImpl” to the users. These classes are defined in the package “com.service”

EmployeeService.java

[code lang=”java”]package com.service;
import com.model.entities.Employee;
import java.util.List;
public interface EmployeeService {
public void save(Employee user);
}[/code]

EmployeeServiceImpl.java

[code lang=”java”]package com.service;
import com.model.entities.Employee;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
@PersistenceContext(name = "persistence/myStrutsJPA", unitName = "StrutsJPAPersistenceUnit", type = PersistenceContextType.EXTENDED)
@javax.ejb.TransactionManagement(javax.ejb.TransactionManagementType.BEAN)
public class EmployeeServiceImpl implements EmployeeService {
private EntityManager em;
@Resource
private UserTransaction utx;
private EntityManagerFactory emf = null;
public UserTransaction getUtx() {
return utx;
}
public void setUtx(UserTransaction utx) {
this.utx = utx;
}
public EmployeeServiceImpl() {
try {
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
em = (EntityManager) envCtx.lookup("persistence/myStrutsJPA");
utx = (UserTransaction) envCtx.lookup("UserTransaction");
} catch (NamingException ex) {
System.out.println("PU Not found");
ex.printStackTrace();
}
}
public void setEntityManager(EntityManager em) {
this.em = emf.createEntityManager();
System.out.println(em);
}
public void save(Employee Employee) {
try {
System.out.println("Tx Status in save:=" + utx.getStatus());
if (utx.getStatus() == 6) { // Incase there’s no active Transaction, we’ll start one
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
utx = (UserTransaction) envCtx.lookup("UserTransaction");
utx.begin();
}
em.persist(Employee);
utx.commit();
} catch (NotSupportedException ex) {
ex.printStackTrace();
} catch (SystemException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void setEm(EntityManager em) {
this.em = em;
}
public void setEmf(EntityManagerFactory emf) {
this.emf = emf;
}
public EntityManager getEm() {
return em;
}
public EntityManagerFactory getEmf() {
return emf;
}
private EntityManager getEntityManager() {
return em;
}
}[/code]

Action Class

Struts does the request processing with the help of Action classes. Here’s the code for the EmployeeAction.java which handles the request to create a new Employee. This class is created in the package
“com.actions”.

EmployeeAction.java

[code lang=”java”]package com.actions;
import com.model.entities.Employee;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.service.EmployeeServiceImpl;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;

public class EmployeeAction extends ActionSupport implements ModelDriven, Preparable, ServletRequestAware {
private Employee emp;
private HttpServletRequest req;
private EmployeeServiceImpl empService;
public EmployeeAction() {
this.empService=new EmployeeServiceImpl();
}
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
public EmployeeServiceImpl getEmpService() {
return empService;
}
public void setEmpService(EmployeeServiceImpl empService) {
this.empService = empService;
}
public String execute() throws Exception {
empService.save(emp);
return SUCCESS;
}
public Object getModel() {
return emp;
}
public void prepare() throws Exception {
emp=new Employee();
}
public void setServletRequest(HttpServletRequest hsr) {
this.req=hsr;
}
}[/code]

Please note that there’s no validation logic in the action class. We have put the validation logic in the
“EmployeeAction-validation.xml” file kept in the “com.actions” package. Please note that the validation.xml file should always be kept in the same package where your action class is present.

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="empid">
<field-validator type="requiredstring">
<message>Employee Id is a mandatory field</message>
</field-validator>
<field-validator type="regex">
<param name="expression">
<![CDATA[([E][m][p][0-9][0-9][0-9])]]>
</param>
<message>Valid Employee Id required e.g. Emp001</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">20</param>
<param name="max">80</param>
<message>Age needs to between ${min} and ${max}</message>
</field-validator>
</field>
<field name="empname">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>User Name is required</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message>Password is required</message>
</field-validator>
<field-validator type="stringlength">
<param name="maxLength">10</param>
<param name="minLength">5</param>
<param name="trim">true</param>
<message>
Enter password between 5 and 10 characters
</message>
</field-validator>
</field>
<field name="password1">
<field-validator type="fieldexpression">
<param name="expression">(password==password1)</param>
<message>
Password and Re-enter password must be same
</message>
</field-validator>
</field>

<field name="city">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>You can not leave city as blank</message>
</field-validator>
</field>
<field name="email">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>You can not leave email as blank</message>
</field-validator>
<field-validator type="email">
<message>
The email address you entered is not valid.
</message>
</field-validator>
</field>
</validators>[/code]

Let us understand the request processing in the action class. The Action class has implemented the following interfaces:

  1. ServletRequestAware:This simplifies access to the HttpServletRequest object representing the request.
  2. ModelDriven:This enables the use of a POJO class to contain the data (similar to ActionForm of Struts1, with an exception that the class here is a POJO and doesn’t extend from any framework specific classes/interfaces). In our case, the entity class “Employee.java” created inside the “com.entities” package acts
    as the model.
  3. PreparableThis prepares the action class for use.

The data validation is performed with the help of “EmployeeAction-validation.xml” file. Different validation routines
are configured for the different entity attributes.

The User Interface Tier

The user interface part of the application is created in JSP. The home page of the application is “RegisterEmp.jsp”, where a form is displayed to the users asking for few details for the registration
purpose. PFB the code of “RegisterEmp.jsp”

[code lang=”html”]<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Add Employee Details Using Field Validators</title>
</head>
<body>
<h1>Struts2 and JPA Integration Demo</h1>
Enter the Employee Details Here
<s:form action="addEmployee">
<s:textfield name="empid" key="app.empid" />
<br>
<s:textfield name="empname" key="app.empname" />
<br>
<s:password key="app.password" name="password" />
<br>
<s:password key="app.password1" name="password1" />
<br>
<s:textfield name="city" key="app.city" />
<br>
<s:textfield name="age" key="app.age" />
<br>
<s:textfield name="email" key="app.email" />
<br>
<br>
<s:submit value="Add Employee" />
</s:form>
<s:actionerror/>
</body>
</html>[/code]

Once the user fills in the required details and clicks on the “Submit” button, the request is submitted to the action class. Upon successful validation, a new employee record is inserted in the database and user is navigated to
“RegisterEmp_Success.jsp”page. Here’s the code of “RegisterEmp_Success.jsp”.

[code lang=”html”]<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Employee Registration Success Page</title>
</head>
<body>
<h1>Employee Details saved Successfully</h1>
Employee Name:
<s:property value="empname" />
<br>
<br>
Password:
<s:property value="password" />
<br>
<br>
Employee Id:
<s:property value="empid" />
<br>
<br>
Age:
<s:property value="age" />
<br>
<br>
City:
<s:property value="city" />
<br>
<br>
E-Mail:
<s:property value="email" />
<br>
<br>
</body>
</html>[/code]

Struts 2.0 and JPA Configuration Files

  • Here’s the configuration added in the “web.xml” file:

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<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>
<persistence-context-ref>
<persistence-context-ref-name>
persistence/myStrutsJPA
</persistence-context-ref-name>
<persistence-unit-name>
StrutsJPAPersistenceUnit
</persistence-unit-name>
</persistence-context-ref>
<resource-env-ref>
<resource-env-ref-name>UserTransaction</resource-env-ref-name>
<resource-env-ref-type>javax.transaction.UserTransaction</resource-env-ref-type>
</resource-env-ref>
<resource-env-ref>
<resource-env-ref-name>jdbc/scrambleDSN</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>RegisterEmp.jsp</welcome-file>
</welcome-file-list>
</web-app>[/code]

In the deployment descriptor, we have added the following configurations:

  • The Welcome File of the application
  • Struts2 Dispatcher Filter (Controller element of Struts2 applications)
  • UserTransaction
  • PersistenceUnit
  • Here’s the configuration added in the “struts.xml” file kept in the default package in the “Source Packages” directory.

[code lang=”xml”]<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="addEmployee" class="com.actions.EmployeeAction">
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="chain"/>
<interceptor-ref name="debugging"/>
<interceptor-ref name="profiling"/>
<interceptor-ref name="model-driven"/>
<interceptor-ref name="params"/>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="validation"/>
<interceptor-ref name="workflow"/>
<result name="success">RegEmp_Success.jsp</result>
<result name="error">RegisterEmp.jsp</result>
<result name="input">RegisterEmp.jsp</result> </action>
</package>
</struts>[/code]

  • The labels of various UI components on the JSP page are not hard coded and instead being derived from the resource bundle “ApplicationResources.properties” kept in the “com.messages” package in the “Source Packages” directory.

Here’s the code of “ApplicationResources.properties”
file:

[code lang=”java”]app.title=Struts2 JPA Integration Application
app.welcome=Welcome to Struts2 Application
app.username=User Name
app.city=City
app.age=Age
app.email=E-Mail
button.save=Save
app.username.blank=Please enter User Name
app.email.blank=Please enter City
app.age.blank=Please enter Age
app.city.blank=Please enter city
app.empid=Employee Id
app.password=Password
app.password1=Reenter Password
app.empname=Employee Name
app.doj=Date of joining[/code]

We configure “ApplicationResources.properties” as the default resource bundle for our application by configuring an entry in the “struts.properties” file kept in the default package in the “Source Packages” directory.

  • Here’s the configuration to be added in the “struts.properties”
    file:

[code lang=”java”]struts.custom.i18n.resources=com.messages.ApplicationResources[/code]

Executing The Application using Struts 2.0 and JPA

Finally, we are ready to execute the application. Deploy the application to the container and execute. Depending on the configuration in the Persistence Unit to create/update/drop-create the database, the database schema is generated/updated.
In our application, we have set the configuration to create the database from scratch.Before executing the application here’s the database schema:No table with the name “Employee” is present.

Open the Register.jsp page.

Enter some invalid data, The snapshot given below shows the validation error messages

Once, all the validation error messages have been rectified, the user is forwarded to RegisterEmp_Success.jsp page, where the correct data submitted is displayed.

Check the database structure, by refreshing the database schema. A new table “Employee” is created with one record in the database.

Conclusion

Thus, any Struts application can seamlessly integrate with JPA easily.

Filed Under: Struts Tagged With: JPA, Struts 2.0, Struts Integration

Integrating Struts 2.0 applications with Hibernate

February 19, 2011 by Krishna Srinivasan Leave a Comment

Struts 2.0 is one of the popularly used Presentation tier framework for Java web Applications.It is based on the WebWork2 technology.Struts 2.0 framework implements MVC 2 architecture by centralizing the control using a Front Controller strategy. The extensible and flexible nature of Struts 2.0 makes it the favourite choice of Java web developers. The major features of Struts 2.0 are user interface tags, Interceptor, result and validation.

also read:

  • Struts 2 Tutorials
  • Struts Interview Questions
  • Struts and Spring Integration

A strong persistence framework is critical to the success and scalability of any application that we develop. Today we have a lot of data access frameworks like Hibernate, JDBC, JPAs, etc available in the market. Sturts can be integrated easily with any of these popularly used data access frameworks.

This article demonstrates the integration of Struts 2.0 applications with the Hibernate. The concept is explained with the help of a sample application. There are pluggins also available for integrating Struts 2.0 with Hibernate. The sample application used in this articile does not use any pluggins.

The author asuumes readers of this article have basic knowledge of Struts 2.0 and Hibernate.If you are beginner in learning Struts and hibernate, please read Introduction to Struts 2.0 and Introduction to Hibernate. The sample is created in NetBens IDE. Sample project struture is displayed in the next section.

Project Structure

This application which is discussed here stores the registration details of an employee to an Oracle DB table using struts 2 and hibernate.Includ the hibernate jar files and struts 2.0 jar files to the project class path. Since we are using Oraccle we need to load the classes12.jar/odbc5.jar also to the class path.

Create the domain model Employee.java as below.This class will be used as the hibernate model object.Hence we need to have the hibernate mapping files created for this as listed in the next section.

The same is used to push the form data to the valuestack.ValueStack, as you know already , is ,one of the powerful features of Struts 2.ValueStack can be defined as a storage structure where the data associated with the current request is stored.

The properties of this bean is directly accessible from the JSP pages using OGNL expresion language.

Listing 1. Employee.java

[code lang=”java”]public class Employee {
private int empno;
private String name;
private String jobtitle;
private String unit;//business unit – Retail,Testing, etc
private String technology;//current working technology
// getter &amp; setter methods
}[/code]

Struts 2.0 Action Class Registration.java

As you are already aware of , Struts 2 do not have the ActionForm concept. But those of you ,who would like to use such a feature in Struts 2, they can create a POJO that holds the form data in its properties and then create an Action class that implements the ModelDriven interface. This is what we have done in the sample described here.

Please note that when you implement ModelDriven interface, you need to get the model object using the getModel() method. The Preparable interface is implemented here so that the action class can prepare itself. If you don’t have anything to prepare, there’s no reason to implement Preparable. Here we are initializing the instance of the Employee object with the prepare() method of the Preparable interface.

Listing 2 : Model Driven Action class – Registration.java

[code lang=”java”]package com.myaction;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Registration extends ActionSupport implements ModelDriven, Preparable {

Employee employee;
SessionFactory sessionFactory = null;
Session session = null;

public String execute() {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(employee);
transaction .commit();
System.out.println("Record Inserted Successfully");
} catch (HibernateException hibernateException) {
System.out.println(hibernateException.getMessage());
session.close();
return "ERROR";
}
return "SUCCESS";
}

@Override
public Employee getModel() {
return employee;
}
@Override
public void prepare() throws Exception {
employee = new Employee();
}
}[/code]

In this action class we are obtaining the SessionFactory instance from the hibernate configuration. Once the SessionFactory instance is obtained, you can create the Session object and invoke the necessary methods for insertion / updation of the records in the table.

JSP Pages

We use three JSP pages in this application. The first one is the index.jsp page that accepts the registration details of the employee. Upon submiting this form, the action class’ execute method is invoked and data is strored in the database. Success.jsp(Listed next) will be shown to the user upon successful insertion of the data.

If an error occurs during insertion , Error.jsp is displayed.

Listing 3 :index.jsp

[code lang=”html”]<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<center>
<!– <img src="PDT_TVM_SMall.JPG"/> –>
<h1>Registration Form</h1>
<s:form action="Registration">
<table bgcolor="pink">
<tr>
<td>
<s:textfield name="empno" label=" Employee Id " value="" />
</td>
<td>
<s:textfield name="name" label=" Name" />
</td>
<td>
<s:textfield name="jobtitle" label=" Job Title " />
</td>
<td>
<s:combobox label=" Business Unit " name="unit"
headerValue="— Please Select —"
headerKey="1"
list="{‘Retail’,’HR’,’Quality’,’R&D’,’Testing’,’Facilities’}" />
</td>
<td>
<s:combobox label=" Current Technology Area" name="technology"
headerValue="— Please Select —"
headerKey="1"
list="{‘Java’,’J2EE’,’.NET’,’Main Frame’,’Others’}"/>
</td>
<td colspan="0"><s:submit label="Register"/></td>
</tr>
</table>
</s:form>
</center>
</body>
</html>
[/code]

Listing 4 : Success.jsp

[code lang=”html”]<%@page contentType="text/html" pageEncoding="UTF-8" import="com.myaction.Employee"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body><center>
<br> <br> <br> <br>
<h1 style="color:chocolate"> <s:property value="name"/> registered successfully !!</h1>
</center>
</body>
</html>[/code]

Listing 5 : Error.jsp

[code lang=”html”]
<%@page contentType="text/html" pageEncoding="UTF-8" errorPage="Error.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error Page</title>
</head>
<body>
<h1>Some Error Occurred !! </h1>
</body>
</html>
[/code]

Oracle Database table structure

Listing 6 : web.xml

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>[/code]

Hibernate and Struts 2 configuration files

Listing 7 : Struts.xml

[code lang=”xml”]<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<!– Configuration for the default package. –>
<package name="default" extends="struts-default">
<action name="Registration" class="com.myaction.Registration">
<result name="SUCCESS">/Success.jsp</result>
<result name="ERROR">/Error.jsp</result>
</action>
</package>
</struts>
[/code]

Listing 8 : hibernate.cfg.xml – Hibernate configuration file

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle8iDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@10.154.117.76:1521:oracle</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
[/code]

Listing 9 : Employee.hbm.xml – hibernate mapping file

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.myaction.Employee" table="StrutsHibEmployee">
<id column="EMPNO" name="empno" type="int">
<generator class="assigned"/>
</id>
<property column="EMPNAME" name="name" type="string"/>
<property column="ROLE" name="jobtitle" type="string"/>
<property column="UNIT" name="unit" type="string"/>
<property column="TECHNOLOGY" name="technology" type="string"/>
</class>
</hibernate-mapping>[/code]

Run the application. Sample screen shots are shown below.

Output can be verified in the database as below.

Summary

Integrating Struts 2.0 with Hibernate is very simple. From the sample explained in the article, you can see that there is no need of using any separate pluggins for this. What is required is to get the SessionFactory object in the Action class and use it the way you use it in normal Java Applications.

Filed Under: Struts Tagged With: Hibernate, Struts 2.0, Struts Integration

Struts 2.0 and Spring

October 2, 2008 by Krishna Srinivasan Leave a Comment

In this post, I will describe how to do the same using Struts 2.0. The only major step that needs to be done here is to override the default Struts 2.0 OjbectFactory. Changing the ObjectFactory to Spring give control to Spring framework to instantiate action instances etc. Most of the code is from the previous post, but I will list only the additional changes here.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

1)Changing the default Object factory: In order to change the Ojbect factory to Spring, you have to add a declaration in the struts.properties file.

[code lang=”java”]
struts.objectFactory = spring
struts.devMode = true
[/code]

2)The Action class: Here is the code for the action class

[code lang=”java”]
package actions;

import java.util.List;

import business.BusinessInterface;

import com.opensymphony.xwork2.ActionSupport;

public class SearchAction extends ActionSupport {
private BusinessInterface businessInterface;

private String minSalary;

private String submit;

private List data;

public String getSubmit() {
return submit;
}

public void setSubmit(String submit) {
this.submit = submit;
}

public BusinessInterface getBusinessInterface() {
return businessInterface;
}

public String execute() throws Exception {
try {
long minSal = Long.parseLong(getMinSalary());
System.out.println("Business Interface: " + businessInterface + "Minimum salary : " + minSal);
data = businessInterface.getData(minSal);
System.out.println("Data : " + data);

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

return SUCCESS;
}

public void setBusinessInterface(BusinessInterface bi) {
businessInterface = bi;
}

public String getMinSalary() {
return minSalary;
}

public void setMinSalary(String minSalary) {
this.minSalary = minSalary;
}

public List getData() {
return data;
}

public void setData(List data) {
this.data = data;
}
}
[/code]

  • The Action class here does not have access to the HttpServetRequest and HttpServletResponse. Hence the action class itself was changed to the session scope for this example (see below)
  • In order for the action class to be aware of the Http Session, the action class has to implement the ServletRequestAware interface, and define a setServletRequest method, which will be used to inject the ServletRequest into the action class.
  • The BusinessInterface property is injected by Spring framework.

3)The struts Configuration:

[code lang=”html”]
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="Struts2Spring" namespace="/actions" extends="struts-default">
<action name="search" class="actions.SearchAction">
<result>/search.jsp</result>
</action>
</package>
</struts>
[/code]
The action’s class attribute has to map the id attribute of the bean defined in the spring bean factory definition.

4)The Spring bean factory definition:

[code lang=”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.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
default-autowire="autodetect">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@localhost:1521:orcl</value>
</property>
<property name="username">
<value>scott</value>
</property>
<property name="password">
<value>tiger</value>
</property>
</bean>

<!– Configure DAO –>
<bean id="empDao" class="data.DAO">
<property name="dataSource">
<ref bean="dataSource"></ref>
</property>
</bean>
<!– Configure Business Service –>
<bean id="businessInterface" class="business.BusinessInterface">
<property name="dao">
<ref bean="empDao"></ref>
</property>
</bean>
<bean id="actions.SearchAction" name="search" class="actions.SearchAction" scope="session">
<property name="businessInterface" ref="businessInterface" />
</bean>
</beans>
[/code]

  • The bean definition for the action class contains the id attribute which matches the class attribute of the action in struts.xml
  • Spring 2’s bean scope feature can be used to scope an Action instance to the session, application, or a custom scope, providing advanced customization above the default per-request scoping.

5)The web deployment descriptor:

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" 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>Struts2Spring</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>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
[/code]
The only significant addition here is that of the RequestContextListener. This listener allows Spring framework, access to the HTTP session information.

6)The JSP file: The JSP file is shown below. The only change here is that the action class, instead of the Data list is accessed from the session.
[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://displaytag.sf.net" prefix="display"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page import="actions.SearchAction,beans.Employee,business.Sorter,java.util.List,org.displaytag.tags.TableTagParameters,org.displaytag.util.ParamEncoder"%>
<html>
<head>
<title>Search page</title>
<link rel="stylesheet" type="text/css" href="/StrutsPaging/css/screen.css" />
</head>
<body bgcolor="white">
<s:form action="/actions/search.action">
<table>
<tr>
<td>Minimum Salary:</td>
<td><s:textfield label="minSalary" name="minSalary" /></td>
</tr>
<tr>
<td colspan="2"><s:submit name="submit" /></td>
</tr>
</table>
</s:form>
<jsp:scriptlet>

SearchAction action = (SearchAction)session.getAttribute("actions.SearchAction");
session.setAttribute("empList", action.getData());
if (session.getAttribute("empList") != null) {
String sortBy = request.getParameter((new ParamEncoder("empTable")).encodeParameterName(TableTagParameters.PARAMETER_SORT));
Sorter.sort((List) session.getAttribute("empList"), sortBy);

</jsp:scriptlet>

<display:table name="sessionScope.empList" pagesize="4" id="empTable" sort="external" defaultsort="1" defaultorder="ascending" requestURI="">
<display:column property="empId" title="ID" sortable="true" sortName="empId" headerClass="sortable" />
<display:column property="empName" title="Name" sortName="empName" sortable="true" headerClass="sortable" />
<display:column property="empJob" title="Job" sortable="true" sortName="empJob" headerClass="sortable" />
<display:column property="empSal" title="Salary" sortable="true" headerClass="sortable" sortName="empSal" />
</display:table>
<jsp:scriptlet>
}
</jsp:scriptlet>

</body>
</html:html>
[/code]

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

7)The Other required classes: The following other classes have been used for the example, and they can be obtained from the previous posts (1, 2).

  • Employee.java
  • BusinessInterface.java
  • Sorter.java
  • DAO.java
  • EmpMapper.java

Filed Under: Spring Framework Tagged With: Spring Integration, Struts, Struts Integration

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved