Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Struts2 Actions action


May 15, 2021 Struts2


Table of contents


Actions are at the heart of the Struts2 framework because they work with any Model View Controller framework. Each URL maps to a specific action that provides the processing logic needed to process requests from users.
But action has two other important features. F irst, action plays an important role in passing data from requests to views, whether JSP or other types of results. Second, action must assist the framework in determining which results should be presented in the view in response to the request.

Create Action

The only requirement for actions in Struts2 is that there must be an argumentless method to return the String or Result object, and that it must be POJO. If the no-argument method is not specified, the default is to use the execute() method.
You can also extend the ActionSupport class, which implements six interfaces, including the Action interface. Action's 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's take a look at the action method in the Hello World example:

package cn.w3cschool.struts2;

public class HelloWorldAction{
   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 key points of the action method control view, let's make the following changes to the execute method and extend the ActionSupport class as follows:

package cn.w3cschool.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport{
   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 use some logic in the execute method to look at the name properties. I f the property is equal to the string "SECRET", we return SUCCESS as a result, otherwise we return ERROR as the result. S ince we've extended ActionSupport, we can use the String constant, SUCCESS, and ERROR. N ow, let's modify the .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="cn.w3cschool.struts2.HelloWorldAction"
            method="execute">
            <result name="success">/HelloWorld.jsp</result>
            <result name="error">/AccessDenied.jsp</result>
         </action>
      </package>
</struts>

Create a view

Let's create the following jsp file HelloWorld in the WebContent folder of your eclipse .jsp. R ight-click the WebContent folder in Project Explorer, and then select "New" and "JSP File." I f the return result is THATSS will call this file (this string constant "success" is defined in the 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>

If the result of action is ERROR, that is, the string constant is "error", the following file will be called by the framework. Here's what AccessDenied .jsp do:

<%@ 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 an index file in the Webcontent .jsp folder. T his file will be used as the initial action URL, which the user can click to command the Struts 2 framework to call the execute method of the HelloWorldAction class and render a view of the helloworld .jsp system.

<%@ 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>

This does not change the .xml the web file, so we can use the web file we created earlier in the Hello World .xml section. N ow we're ready to run our Hello World application using the Struts 2 framework.

Execute the application

Right-click on the project name, and then click "Export" and "WAR File" to create a WAR file. T he WAR file is then deployed in Tomcat's webapps directory. F inally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp. T he illustration shown is as follows:

Struts2 Actions action

Let's enter a word as "SECRET" and you'll see the following page:

Struts2 Actions action

Now enter any word other than "SECRET" and you'll see the following page:

Struts2 Actions action

Create multiple Actions

You will need to frequently define multiple actions to handle different requests and provide users with different URLs, so you will define different classes as follows:

package cn.w3cschool.struts2;
import com.opensymphony.xwork2.ActionSupport;

   class MyAction extends ActionSupport{
      public static String GOOD = SUCCESS;
      public static String BAD = ERROR;
   }

   public class HelloWorld extends ActionSupport{
      ...
      public String execute()
      {
         if ("SECRET".equals(name)) return MyAction.GOOD;
         return MyAction.BAD;
      }
      ...
   }

   public class SomeOtherClass extends ActionSupport{
      ...
      public String execute()
      {
         return MyAction.GOOD;
      }
      ...
   }

You will configure these actions .xml the struts 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="cn.w3cschool.struts2.HelloWorld" 
         method="execute">
         <result name="success">/HelloWorld.jsp</result>
         <result name="error">/AccessDenied.jsp</result>
      </action>
      <action name="something" 
         class="cn.w3cschool.struts2.SomeOtherClass" 
         method="execute">
         <result name="success">/Something.jsp</result>
         <result name="error">/AccessDenied.jsp</result>
      </action>
   </package>
</struts>

As you can see in the example above, the results of action ARECESS and ERROR are repeated. To solve this problem, we recommend that you create a class that contains the results.