Actions are the core of the Struts2 framework, as they are for any MVC (Model View Controller) framework. Each URL is mapped to a specific action, which provides the processing logic necessary to service the request from the user.

But the action also serves in two other important capacities. First, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result. Second, the action must assist the framework in determining which result should render the view that will be returned in the response to the request.

Create Action:

The only requirement for actions in Struts2 is that there must be one no-argument method that returns either a String or Result object and must be a POJO. If the no-argument method is not specified, the default behavior is to use the execute() method.

Optionally you can extend the ActionSupport class which implements six interfaces including Action interface. The Action interface is as follows:

public interface Action {
   public static final String SUCCESS = "success";
   public static final String NONE = "none";
   public static final String ERROR = "error";
   public static final String INPUT = "input";
   public static final String LOGIN = "login";
   public String execute() throws Exception;
}

Let us take a look at the action method in the Hello World example:

package com.dineshonjava.struts2.action;

/**
 * @author Dinesh Rajput
 *
 */
public class HelloWorldAction {
 private static final long serialVersionUID = 4956157388836635122L;
 private String name;

    public String execute() throws Exception {
       return "success";
    }  

    public String getName() {
       return name;
    }

    public void setName(String name) {
       this.name = name;
    }
}

To illustrate the point that the action method controls the view, let us make the following change to the execute method and extend the class ActionSupport as follows:

package com.dineshonjava.struts2.action;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Dinesh Rajput
 *
 */
public class HelloWorldAction extends ActionSupport {
 private static final long serialVersionUID = 4956157388836635122L;
 private String name;

   public String execute() throws Exception {
            if ("SECRET".equals(name))
            {
                return SUCCESS;
            }else{
               return ERROR;  
            }
          }

    public String getName() {
       return name;
    }

    public void setName(String name) {
       this.name = name;
    }
}

In this example, we have some logic in the execute method to look at the name attribute. If the attribute equals to the string “SECRET”, we return SUCCESS as the result otherwise we return ERROR as the result. Because we have extended ActionSupport, so we can use String constants SUCCESS and ERROR. Now, let us modify our struts.xml file as follows:

<?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.devMode" value="true" />
   <package name="helloworld" extends="struts-default">
      <action name="hello" class="com.dineshonjava.struts2.action.HelloWorldAction" method="execute">
         <result name="success">/success.jsp</result>
          <result name="error">/error.jsp</result>
      </action>
   </package>
 </struts>

Create a View-

Let us create the below jsp file success.jsp in the WebRoot folder in your eclipse project. To do this, right click on the WebRoot folder in the project explorer and select New >JSP File. This file will be called in case return result is SUCCESS which is a String constant “success” as defined in Action interface

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   Hello World, <s:property value="name"/>
</body>
</html>

Following is the file which will be invoked by the framework in case action result is ERROR which is equal to String constant “error”. Following is the content of error.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Access Denied</title>
</head>
<body>
   You are not authorized to view this page.
</body>
</html>

We also need to create index.jsp in the WebRoot folder. This file will serve as the initial action URL where the user can click to tell the Struts 2 framework to call the execute method of the HelloWorldAction class and render the success.jsp view.

<%@ 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>Hello World</title>
</head>
<body>
   <h1>Hello World From Struts2</h1>
   <form action="hello">
      <label for="name">Please enter your name</label><br/>
      <input type="text" name="name"/>
      <input type="submit" value="Say Hello"/>
   </form>
</body>
</html>

That’s it, there is no change required web.xml file, so let us use same web.xml which we had created in Examples chapter. Now we are ready to run our Hello World application using Struts 2 framework.

Execute the Application-

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/. This will give you following screen:

Let us enter a word as “SECRET” and you should see the following page:

Now enter any word other than “dinesh” and you should see the following page:

Download Source Code
Struts2Action.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