Struts 2 Spring Integration

Struts 2 Spring Integration

Here you will see how to integrate Struts 2 with Spring and get data using spring dependency injection.

Note: This is extension of previous tutorial Struts 2 Maven Hello World . So all eclipse tomcat and maven configuration is same. Please use this tutorial to configure eclipse maven and tomcat.

Below are steps:

  • Create Maven project name: StrutsMavenHelloWorld (If you are not sure how to create maven project in eclipse please use this tutorial)
  • Complete project structure:

Struts 2 Spring Integration

Important: To integrate Struts 2 with Spring you need below:

  • Include listener in web.xml
<listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
</listener>
  • struts2-spring-plugin dependent jars. Here we are using maven project so adding below dependency will automatically include all jars in application class-path.
<dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.3.16.3</version>
</dependency>
  • Lastly you will have to do bean mapping with spring context and struts configuration file as below:
<!-- applicationContext.xml: -->

<bean id="person" class="com.javahonk.bean.PersonImpl" />
 
<bean id="strutsSpringAction" class="com.javahonk.action.StrutsSpringAction">
    <property name="person" ref="person" /> 
</bean>

<!--struts.xml: -->

<action name="strutsSpringAction" class="com.javahonk.action.StrutsSpringAction">
  <result name="error">/WEB-INF/jsp/index.jsp</result>
  <result name="input">/WEB-INF/jsp/index.jsp</result>
  <result name="success">/WEB-INF/jsp/success.jsp</result>          
</action>

 

That’s it lets see details dynamic web application example below:

  • Add below dependency in pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javahonk</groupId>
    <artifactId>StrutsMavenHelloWorld</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>StrutsMavenHelloWorld Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.16.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.3.16.3</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>StrutsMavenHelloWorld</finalName>
    </build>
</project>

  • web.xml inside WEB-INF folder:
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <filter>
        <filter-name>struts2Maven</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2Maven</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

</web-app>

  • Please create jsp folder inside \webapp\WEB-INF\
  • Create index.jsp inside jsp folder
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Struts 2 Maven Hello world!!!</title>
        <s:head/>
    </head>
 
    <body>
        <h1 style="color: red"><s:text name="label.welcome" /></h1>
        <s:if test="hasActionErrors()">
            <div id="fieldErrors">
                <s:actionerror/>
            </div>
        </s:if>
        
        <s:form action="strutsSpringAction" namespace="/" method="post" name="strutsForm">
            <s:textfield name="firstName" size="30" maxlength="50" key="label.firstName"/>
            <s:textfield name="lastName" size="30" maxlength="50" key="label.lastName"/>
            <s:submit key="Submit" align="right"/>
        </s:form>
    </body> 
</html>  
  • Create success.jsp inside jsp folder:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Struts 2 Maven Welcome page!</title>
    </head>
    <body>
        <h2 style="color: red">Value from spring: <s:property value="userName"/></h2>
        <h2 style="color: red">Value you entered:</h2>
        <p>
            First Name: <s:property value="firstName" />
        </p>
        <p>
            Last Name: <s:property value="lastName" />
        </p>       
    </body>
</html>
  • Create applicationContext.xml file inside WEB-INF folder and copy paste below code:
<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="person" class="com.javahonk.bean.PersonImpl" />
 
    <bean id="strutsSpringAction" class="com.javahonk.action.StrutsSpringAction">
        <property name="person" ref="person" /> 
    </bean>
 
</beans>
  • Create ApplicationResources.properties file inside resource folder:
label.welcome = Struts Spring Integration successful!!!
label.firstName =  First Name
label.lastName =  Last Name
error.firstName.required = First Name is required!
error.lastName.required = Last Name is required!

  • Create struts.xml inside resource folder:
<?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>
    <include file="struts-default.xml"/>
    
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.custom.i18n.resources" value="ApplicationResources" />
    
    <package name="default" extends="struts-default">
        <action name="">
            <result>/WEB-INF/jsp/index.jsp</result>
        </action>
       <action name="strutsSpringAction" class="com.javahonk.action.StrutsSpringAction">
          <result name="error">/WEB-INF/jsp/index.jsp</result>
          <result name="input">/WEB-INF/jsp/index.jsp</result>
          <result name="success">/WEB-INF/jsp/success.jsp</result>          
       </action>
    </package>
</struts>
  • Create interface Person.java inside com.javahonk.bean package:
package com.javahonk.bean;

public interface Person {

    public String userName();

}

  • Create class PersonImpl.java inside com.javahonk.bean package which will implements Person interface:
package com.javahonk.bean;

public class PersonImpl implements Person{

    public String userName() {
        return "Java Honk";
    }

}

  • Finally create action class StrutsSpringAction.java inside com.javahonk.action package:
package com.javahonk.action;

import com.javahonk.bean.Person;
import com.opensymphony.xwork2.ActionSupport;

public class StrutsSpringAction extends ActionSupport{

    private static final long serialVersionUID = 1L;
    //Value from spring dependency injection
    Person person;
    private String userName;
    private String firstName;
    private String lastName;

    @Override
    public String execute() throws Exception {
        userName = person.userName();
        return ActionSupport.SUCCESS;
    }
    
    @Override
    public void validate() {
        if (null == firstName || firstName.length() == 0)
            addActionError(getText("error.firstName.required"));
        if (null == lastName || lastName.length() == 0)
            addActionError(getText("error.lastName.required"));     
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public String getUserName() {
        return userName;
    }

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

    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;
    }
    
    
    
}

 

  • Now we are ready to run this project.To run this project right click project –> Click Run As –> Run on Server as below: (Note: Before run this application you will have to configure tomcat server in eclipse. Please follow link to install and configure tomcat in eclipse)
  • You will see below welcome page:

Struts 2 Spring Integration

  • Remember we have added form validation as well. To check if validation is working or not click Submit button without entering anything in input field you will see below page with validation error message:

Struts 2 Spring Integration

  • Now enter data and click Submit button. You will see below page with both value from Spring and input field entered value as below:

Struts 2 Spring Integration download Download Project:  Struts 2 Spring Integration

For more information please visit Apache official web site here
That’s it Struts 2 Spring Integration

Leave a Reply

Your email address will not be published. Required fields are marked *