Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaHow to Create a Project using Spring and Struts 2?

How to Create a Project using Spring and Struts 2?

Prerequisites:

In this article, we will discuss how the Spring framework can be integrated with the Struts2 framework to build a robust Java web application. Here I am going to assume that you know about Spring and Struts2 framework. The first question that will come to your mind is why should you integrate these two frameworks.

So let’s first discuss a little bit about Spring as well as Struts 2 framework and why we should integrate these two frameworks. As we all know, the Spring framework is used to develop enterprise web applications and The Struts2 framework is used to develop MVC (Model View Controller) based web applications. Both Spring & Struts2 uses MVC architecture for building Java web applications, and Struts2 is based on Java Servlet API. Therefore, When we integrate Spring and Struts2 framework then MVC functionality should not overlap. Instead, they should supplement each other. As we all know there is a very cool feature of Spring i.e. dependency injection management. So we can use it to manage business beans and Struts’ action beans. On the other side, We’ll be able to focus on our business logic implementation with Struts2 MVC architecture. This is a typical scenario for integrating Spring and Struts together, especially for legacy applications based on Struts.

How does Spring and Struts 2 integration work?

To integrate Spring and Struts 2 framework, we just have to add one jar file i.e. struts2-spring-plugin in the project’s classpath which is provided by the Struts 2 framework. With the Spring plugin enabled, the Spring framework manages all Struts’ action classes as well as other beans (business classed, DAO classes, etc) via its inversion of control container (declared in Spring’s application context configuration file).

You guys must be thinking about how much theory to read. If something happens in practice, then it will be fun. So let’s start the implementation of integration of Spring and Struts2 framework to develop a web application with login functionality. We will go step by step like below :

  1. Create a maven project & convert it to a Dynamic Web Project
  2. Add required Spring, Struts2, Java Servlet & JSP dependencies in pom.xml
  3. Add the Spring plugin i.e. struts2-spring-plugin dependency in pom.xml

XML




         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.gfg.technicalscripter</groupId>
  <artifactId>SpringStruts2Integration</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringStruts2IntegrationDemo</name>
  <description>Spring-Struts2 Integration Demo</description>
    
    <properties>
        <java-version>1.8</java-version>
        <org.springframework-version>4.1.2.RELEASE</org.springframework-version>
    </properties>
      
    <dependencies>
        
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
          
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
  
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
          
        <!-- Struts -->
        <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>        
          
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>    
        
    </dependencies>  
    
</project>


As we discussed earlier, we are going to implement only login functionality in the project to demonstrate the Spring and Struts2 integration. So, here we will create a User model class, UserDAO class, and UserAction class to process the login request.

Java




package com.gfg.technicalscripter;
  
public class User {
    private String username;
    private String email;
    private String password;
  
    public String getUsername() {
        return username;
    }
  
    public void setUsername(String username) {
        this.username = username;
    }
  
    public String getEmail() {
        return email;
    }
  
    public void setEmail(String email) {
        this.email = email;
    }
  
    public String getPassword() {
        return password;
    }
  
    public void setPassword(String password) {
        this.password = password;
    }
}


Java




package com.gfg.technicalscripter;
  
public class UserDAO {
    public boolean checkLogin(User user) {
        return user.getUsername().equals("pichu")
                && user.getPassword().equals("pikachu");
    }
}


Java




package com.gfg.technicalscripter;
  
import com.opensymphony.xwork2.ActionSupport;
  
public class LoginAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private UserDAO userDAO;
    private User user;
      
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
  
    public void setUser(User user) {
        this.user = user;
    }
      
    public User getUser() {
        return user;
    }
  
    public String execute() {
        if (userDAO.checkLogin(user)) {
            return SUCCESS;
        }
          
        return ERROR;
    }
}


Now comes the View part of MVC architecture. Here we will create three JSP pages i.e. LoginForm.jsp, LoginSuccess.jsp & LoginError.jsp 

LoginForm.jsp

XML




<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to Home Page</title>
</head>
<body>
    <div align="center">
        <h1>Hello Geeks</h1>
        <h1>Spring and Struts 2 Integration Demo</h1>
        <h2>Enter login credentials</h2>
        <s:form action="login" method="post">
            <s:textfield label="Username" name="user.username" />
            <s:password label="Password" name="user.password" />
            <s:submit value="Login" />
        </s:form>                
    </div>    
</body>
</html>


LoginSuccess.jsp

XML




<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Success</title>
</head>
<body>
    <div align="center">
        <h1>Welcome to Lazyroar !!!</h1>
    </div>
</body>
</html>


LoginError.jsp

XML




<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Error</title>
</head>
<body>
    <div align="center">
        <h1>Error login !! </h1>
        <h1>Wrong username/password</h1>
    </div>
</body>
</html>


Configuring Spring and Struts in web.xml. This part is the most important because of this configuration only the Spring and Struts 2 frameworks interact with each other. Spring acts as the dependency container and Struts acts as the MVC framework.

Java




<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                       "http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appContext.xml</param-value>
    </context-param>
      
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
      
    <filter>
        <filter-name>DispatcherFilter</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
  
    <filter-mapping>
        <filter-name>DispatcherFilter</filter-name>
        <url-pattern>.*</url-pattern>
    </filter-mapping>
  
</web-app>


Next, we configure how Struts processes the workflow of the application. Create an XML file named struts.xml under the project’s source folder with the following code:

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  
<struts>
    <package name="Struts2SpringDemo" extends="struts-default">
        <action name="login" class="loginActionBean">
            <result name="input">/LoginForm.jsp</result>
            <result name="success">/LoginSuccess.jsp</result>
            <result name="error">/LoginError.jsp</result>
        </action>
    </package>
</struts>


At last, we will create an XML file name appContext.xml under the /WEB-INF/spring directory where we define the beans which will be managed by the Spring IOC container by reading the appContext.xml file.

XML




<?xml version="1.0" encoding="UTF-8"?>
      
    <bean id="loginActionBean" class="com.gfg.technicalscripter.LoginAction">
        <property name="userDAO" ref="userDAO" />
    </bean>        
      
    <bean id="userDAO" class="com.gfg.technicalscripter.UserDAO" />
          
</beans>


Finally, the project is ready after a lot of hard work. The project structure will look like below:

project structure

 

To test the application, we have to integrate the apache tomcat server into IDE and run this application on the server. You don’t have to worry about that now. I will test the application on your behalf. I will demonstrate each screen one by one. So after deploying the project into the apache tomcat server, we have to hit the browser with the URL below to get the login screen

http://localhost:8080/SpringStruts2Integration/LoginForm.jsp

LoginForm.jsp Output:

LoginForm.jsp

 

Now we can test the login functionality by passing the correct and wrong credentials. So I will first pass the correct and then wrong credentials and display you the response page in both scenarios.

LoginForm.jsp

 

LoginSuccess.jsp Output:

LoginSuccess.jsp

 

LoginError.jsp Output:

LoginError.jsp

 

In this tutorial, we reviewed how to use the Struts 2 Spring plugin to integrate Spring and Struts. By using the Struts 2 Spring plugin you can have Spring manage the dependencies of your ActionSupport classes. Of course, you can also take advantage of the many other benefits (AOP, Spring JDBC) that the Spring framework provides.

RELATED ARTICLES

Most Popular

Recent Comments