Struts2

Struts2 Spring Integration Example

In this tutorial, it shows the integration between Struts 2 and Spring3. Why you want to integrate spring with struts 2? Spring provides some features which are not available in struts 2.Most powerful among them is dependency injection. To learn more about dependency injection, you can refer dependency injection in spring link.

There are following tool we need to create this application.
1. Strus2
2. Spring3
3. STS or Eclipse

Step 1: Project Structure

Step 2: There are following jars file need to be add

commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-lang-2.4.jar
commons-lang3-3.1.jar
commons-logging-1.0.4.jar
commons-logging-api-1.1.jar
freemarker-2.3.18.jar
javassist-3.0.jar
ognl-3.0.4.jar
spring-asm-3.0.1.RELEASE.jar
spring-beans-3.0.1.RELEASE.jar
spring-context-3.0.1.RELEASE.jar
spring-core-3.0.1.RELEASE.jar
spring-expression-3.0.1.RELEASE.jar
spring-jdbc-3.0.1.RELEASE.jar
spring-orm-3.0.1.RELEASE.jar
spring-tx-3.0.1.RELEASE.jar
spring-web-3.0.1.RELEASE.jar
spring-webmvc-3.0.1.RELEASE.jar
struts2-core-2.3.1.2.jar
struts2-dojo-plugin-2.3.15.jar
struts2-spring-plugin-2.3.15.jar
xwork-core-2.3.1.2.jar

Step 3: Struts 2 + Spring 3 Plugin

To integrate Struts 2 and Spring, get and include the “struts2-spring-plugin-xxx.jar” library into your project classpath. As already added above struts2-spring-plugin-2.3.15.jar.

Step 4: Spring Listener

Configure the Spring listener “org.springframework.web.context.ContextLoaderListener” in web.xml file.

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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2Spring3Intergration</display-name>
   <welcome-file-list>
        <welcome-file>User.jsp</welcome-file>
    </welcome-file-list>
   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>
   <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>
    
</web-app>

The important thing to note here is the listener that we have configured. The ContextLoaderListener is required to load the spring context file. Spring’s configuration file is called applicationContext.xml file and it must be placed at the same level as the web.xml file.

Step 5: Register Spring Bean

Register all the Spring’s Beans in the applicationContext.xml file, the Spring listener will locate this xml file automatically.
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:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 <context:component-scan base-package="com.dineshonjava.struts2.bean" />
 <bean id="user" class="com.dineshonjava.struts2.action.user.UserAction">
   </bean>
   <bean id="userBean" class="com.dineshonjava.struts2.bean.UserBean">
   </bean>
</beans>

Step 7: Create Action class and User bean.

UserAction.java

package com.dineshonjava.struts2.action.user;

import org.springframework.beans.factory.annotation.Autowired;

import com.dineshonjava.struts2.bean.UserBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author Dinesh Rajput
 *
 */
public class UserAction extends ActionSupport implements ModelDriven<UserBean>{

 private static final long serialVersionUID = 1L;
 
 @Autowired
 private UserBean userBean;

 public String execute()
 {
  return SUCCESS;
 }
 
 public String addUser()
 {
  return SUCCESS;
 }
 
 @Override
 public UserBean getModel() {
  return userBean;
 }
}

Here userBean property autowired with action class UserAction java it is also powerfull feature of Spring framework.

UserBean.java

package com.dineshonjava.struts2.bean;

/**
 * @author Dinesh Rajput
 *
 */
public class UserBean {
 private String userName;
 private int userAge;
 private String userGender;
 private String userJob;
 private String []userHobbies;
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public int getUserAge() {
  return userAge;
 }
 public void setUserAge(int userAge) {
  this.userAge = userAge;
 }
 public String getUserGender() {
  return userGender;
 }
 public void setUserGender(String userGender) {
  this.userGender = userGender;
 }
 public String getUserJob() {
  return userJob;
 }
 public void setUserJob(String userJob) {
  this.userJob = userJob;
 }
 public String[] getUserHobbies() {
  return userHobbies;
 }
 public void setUserHobbies(String[] userHobbies) {
  this.userHobbies = userHobbies;
 }
}

Step 8: Struts.xml

Declared all the relationship here.

<?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.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
 <package name="user" extends="struts-default">
        <action name="user" class="user" method="execute">
            <result name="success">/success.jsp</result>
            <result name="input">/User.jsp</result>
        </action>
    </package>
 </struts>

The important thing to note is that we are using the id user to refer to the class. This means that we are using spring to do the dependency injection for the User class.

Step 9: Create View

Next let us create the User.jsp in the WebRoot folder:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<style type="text/css">
b{color: blue;}  
</style>
<title>Struts2 - Spring integration | dineshonjava.com</title>
</head>
<body>

   <h1><span style="background-color: #FFFFcc">User From Struts2 - Spring integration</span></h1>
 <h2>Add User</h2><b>
    <s:form  action="user" method="addUser">
    <s:textfield name="userName" key="user.name" />
    <s:textfield name="userAge" key="user.age" value=""/>
    <s:radio name="userGender" key="user.gender" list="{'Male','Female'}" />
    <s:select name="userJob"  key="user.job" list="%{#{'Software':'Software','Hardware':'Hardware','Networking':'Networking','Marketing':'Marketing'}}"/>  
    <s:checkboxlist name="userHobbies" key="user.hobby" list="{'Cricket','Football','Drawing','Cooking','Driving','Movie'}" />  
    <s:submit key="submit" align="center"/>
 </s:form>
 </b>
</body>
</html>

Creating success.jsp file for after submit.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Struts2 - Spring integration | dineshonjava.com</title>
</head>
<body>

     <h1><span style="background-color: #FFFFcc">User From Struts2 - Spring integration</span></h1>
 <h2>List of User</h2>
    <ul>
   <li>User Name : <s:property value="userName" /></li>
   <li>User Age : <s:property value="userAge" /></li>
   <li>User Gender : <s:property value="userGender" /></li>
   <li>User Jobs : <s:property value="userJob" /></li>
   <li>User Hobbies : <s:property value="userHobbies" /></li>
 </ul> 
</body>
</html>

myapp.properties

user.name=User Name
user.age=User Age
user.gender=Gender
user.job=Job Type
user.hobby=Hobbies
submit=Add User

Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/User.jsp. 

This will give you following screen:

Clicking on “Add User” button then we will see following screen:

 

Download Source Code + Libs
Struts2Spring3Intergration.zip

<<Previous <<   || Index ||   >>Next >>

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago