Spring integration in Struts2

Spring is an Open Source lightweight framework works with all tier software application layers. It provides container to manage bean and uses Dependency Injection(DI).
Click to get more informartion.

Struts 2 provides a plugin that enables Spring to inject into the ActionSupport classes any dependent objects. No need to register Spring Action in the container.

It has following features -
  • Allow Actions, Interceptors, and Results to be created by Spring
  • Struts-created objects can be autowired by Spring after creation
  • Provides two interceptors that autowire actions, if not using the Spring ObjectFactory
To enable this plug-in, you have to copy struts2-spring-plugin-x-x-x.jar in \WEB-INF\lib folder. I am using struts2-spring-plugin-2.3.12.jar in my example.

And add following configuration in web.xml -
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
The above listener reads WEB-INF\applicationContext.xml file.

You can specify more than one spring specific configuration file other than applicationContext.xml file as below -
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
</context-param>

The following software are used in this example : Database connection information
  • Driver class - com.mysql.jdbc.Driver
  • Database URL - jdbc:mysql://localhost:3306/test
  • User - root
  • password - root
  • Database name - test
Before running below example, create the below table -
create table emp
(
eid varchar(10) primary key,
name varchar(30),
city varchar(20),
salary double
);

Follow the following steps to create this project :

Step 1: Create a Dynamic Web Project in eclipse - "Struts2Spring1".

Step 2: Edit deployment descriptor web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Struts2Spring1</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>


Step 3: The following Struts2 and hibernate jar files required in WEB-INF\lib folder in your project.
aopalliance-1.0.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-logging-api-1.1.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
log4j-1.2.17.jar
mysql-connector-java-5.1.7-bin.jar
ognl-3.0.6.jar
spring-aop-3.2.4.RELEASE.jar
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-context-support-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
spring-jdbc-3.2.4.RELEASE.jar
spring-tx-3.2.4.RELEASE.jar
spring-web-3.2.4.RELEASE.jar
struts2-core-2.3.12.jar
struts2-spring-plugin-2.3.12.jar
xwork-core-2.3.12.jar

Step 4: Create a View page index.jsp :
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Struts2 Spring integration2</title>
</head>
<body>
<s:form action="EmpAction" method="post">
<s:textfield label="Enter Id" name="eid" value=""/>
<s:textfield label="Enter Name" name="name" value=""/>
<s:textfield label="Enter City" name="city" value=""/>
<s:textfield label="Enter Salary" name="salary" value="0"/>
<s:submit action="saveEmpAction" value="Save Emp"/>
<s:submit action="deleteEmpAction" value="Delete Emp"/>
<s:submit action="updateEmpAction" value="Update Emp"/>
<s:submit action="queryEmpAction" value="Query Emp"/>
<s:submit action="showallEmpAction" value="ShowAll"/>
</s:form>
<hr>
<s:property value="message"/>
<hr>
<table border="1">
<s:iterator value="emps">
<tr>
<td><s:property value="eid"/> </td>
<td><s:property value="name"/></td>
<td><s:property value="city"/></td>
<td><s:property value="salary"/></td>
</tr>
</s:iterator>
</body>
</html>

Step 5: Create action class EmpAction.java :
package techmyguru.actions;
// all import statements
public class EmpAction extends ActionSupport
implements ModelDriven<Employee>,Preparable
{
Employee emp;
private String message;
List<Employee> emps;
EmpDao empdao;

@Override
public Employee getModel() {
return emp;
}

public String getMessage() {
return message;
}

public List<Employee> getEmps() {
return emps;
}

// prepare method to prepare all global variables
@Override
public void prepare() throws Exception {
emp = new Employee();
message = "";
emps = new ArrayList<Employee>();
ServletContext ctx=ServletActionContext.getServletContext();
WebApplicationContext wctx = WebApplicationContextUtils.
getWebApplicationContext(ctx);
empdao=(EmpDao)wctx.getBean("empDao");
}

// save method
public String save() {
message = "Add method executed";
empdao.addEmployee(emp);
System.out.println("save" + message);
return SUCCESS;
}

// delete method
public String delete() {
message = "delete method executed";
empdao.deleteEmployee(emp.getEid());
System.out.println(message);
return SUCCESS;
}

// update method
public String update() {
message = "update method executed";
empdao.updateEmployee(emp);
return SUCCESS;
}

// query method
public String query() {
try
{
Employee emp2 = empdao.getEmployee(emp.getEid());
message = "query method executed";
emps.add(emp2);
}
catch(Exception e)
{
System.out.println("error in fetching data "+e);
message="Error in fetching employee record";
}
return SUCCESS;
}

// showall method
public String showall() {
message = "All Employees";
emps = empdao.getAllEmployees();
return SUCCESS;
}
}

Step 6: Create POJO class Employee.java:
package techmyguru.actions;
public class Employee {
private String eid;
private String name;
private String city;
private double salary;
public Employee() { }
public Employee(String eid, String name, String city, double salary) {
this.eid = eid;
this.name = name;
this.city = city;
this.salary = salary;
}
// all getter and setter methods
@Override
public String toString() {
return eid + " " + name + " " + city + " " + salary;
}
}


Step 7: Create DAO class EmpDao.java :
package techmyguru.actions;
// all import statements
public class EmpDao
{
JdbcTemplate jdbctemplate;

public void setJdbctemplate(JdbcTemplate jdbctemplate)
{
this.jdbctemplate = jdbctemplate;
}

public void addEmployee(Employee emp)
{
jdbctemplate.update("insert into emp values(?,?,?,?)", new Object[] {
emp.getEid(), emp.getName(), emp.getCity(), emp.getSalary() });
}

public void updateEmployee(Employee emp)
{
jdbctemplate.update("update emp set city=?, salary=salary+?
where eid=?", new Object[] {emp.getCity(), emp.getSalary(),emp.getEid()});
}

public void deleteEmployee(String code)
{
jdbctemplate.update("delete from emp where eid=?",new Object[] { code });
}

public Employee getEmployee(String eid)
{
Employee emp = jdbctemplate.queryForObject("select * from emp
where eid = ?", new Object[]{eid},new RowMapper<Employee>()
{
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException
{
Employee emp1 = new Employee();
emp1.setEid(rs.getString("eid"));
emp1.setName(rs.getString("name"));
emp1.setCity(rs.getString("city"));
emp1.setSalary(rs.getDouble("salary"));
return emp1;
}
});
return emp;
}

// use of RowMapper
public List<Employee> getAllEmployees()
{
List<Employee> employees = jdbctemplate.query("select * from emp",
new RowMapper<Employee>()
{
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException
{
Employee emp = new Employee();
emp.setEid(rs.getString("eid"));
emp.setName(rs.getString("name"));
emp.setCity(rs.getString("city"));
emp.setSalary(rs.getDouble("salary"));
return emp;
}
});
return employees;
}
}

Step 8: Create struts configuration file src\struts.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="*EmpAction" class="techmyguru.actions.EmpAction" method="{1}">
<result name="success">index.jsp</result>
<result name="input">index.jsp</result>
<result name="error">index.jsp</result>
</action>
</package>
</struts>

Step 9: Create spring configuration file WEB-INF\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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

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

<!-- jdbc template injection -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- bean - EmployeeDao -->
<bean id="empDao" class="techmyguru.actions.EmpDao">
<property name="jdbctemplate" ref="jdbcTemplate" />
</bean>
</beans>

Step 10: Verify the project directory structure.
Hibernate plug-in integration with Struts2

Step 11: Run the project and get output.
Hibernate  plug-in integration with Struts2

Previous Download Source Code Next

Comment by : Umesh N. Bhosale December 13th, 2013
Comment : Hello sir,I found your tutorial is very well descriptive as per real time programming requirment. I request u that plz upload tutorial for Hibernate as well so your sit will be perfect pkg of right t


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code