• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Struts2 » Struts 2 Actions
Next →
← Prev

Struts 2 Actions

By Dinesh Thakur

If you are working on Struts2, Actions are the heart and soul of the Struts2 MVC web framework. A user sends a HTTP request from its web browser which is in the form of a URL and it represents an Action. The framework selects an appropriate Action class based on the mappings available in struts.xml.

The term “action” refers to an associate operation that the application is able to perform. Struts2 actions has default entry point are execute () method, where the execution of an action class start. An action is a servlet (controller) i.e. is used to receive the request and invoke business related function for a given URL, and then mapping the response into a model. An action can also return more than one kind of results depending on the complexity of the business logic. It is used to invoke actions from JSP page.

Optionally we can extend the ActionSuppport class which implements six interfaces including Action interface. The Action interface is as follows

Field Name

Description

public static final String SUCCESS= “success”;

Execution of action was successful

public static final String NONE = “none”;

Successful execution but no view.

public static final String ERROR= “error”;

Execution of action failed.

public static final String INPUT = “input”;

The action execution requires more input in order to succeed.

public static final String LOGIN = “login”;

The Action execution needs that user is not logged in.

public String execute() throws Exception;

 

We have to extend ActionSuppport class which implements action interface, so we can use String constants SUCCESS and ERROR like this.

Role of action:

• Actions provide Encapsulation:

  The role of this encapsulation is to hold the business logic. Actions are invoked by calling the execute ()   method.

• Action helps to carry data

• Action returns control string

• Struts2 supports using POJOs as Actions, which enable us to create action classes without implementing any interface and extending and class.

We’ll be covering the following topics in this tutorial:

  • Strust2 Action Example
  • Execute the Application

Strust2 Action Example

The Application’s first Page is the default.jsp; in which user input his name, email and address.

The default.jsp (Client View) uses a struts2 HTML/JSP tags, which is used to generate the content of the default.jsp page. In the Client view code, the Action attribute of <s:form /> tag’s is represents the URL to which the form will be submitted. The Action attribute is used to find the action mapping in the struts.xml configuration file.

Here is the code for default.jsp

<%@ 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>
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
     <title>Struts2 Action Example</title>
  </head>
   <body>
        <table border='0' width='480px' cellpadding='0' cellspacing='0' align='center'>
          <tr>
              <td></td>
              <td align='left'><h2>Enter Client Detail</h2></td>
          </tr>
          <s:form action="ClientAction" method="Post" theme="simple">
             <tr>
                 <td align='right'><b>Name : &nbsp;&nbsp;</b></td>
                 <td><s:textfield key="name" theme="simple" /></td>
             </tr>
                 <tr> <td>&nbsp;</td> </tr>
             <tr>
                 <td align='right'><b>Email : &nbsp;&nbsp;</b></td>
                 <td><s:textfield key="email" theme="simple" /></td>
             </tr>
                 <tr> <td>&nbsp;</td> </tr>
             <tr>
                 <td align='right'><b>Address : &nbsp;&nbsp;</b></td>
                 <td><s:textfield key="address" theme="simple" /></td>
             </tr>
                 <tr> <td>&nbsp;</td> </tr>
             <tr>
                 <td></td>
                 <td align='left'><s:submit value="Submit" theme="simple"></s:submit></td>
              </tr>
            </s:form>
        </table>
   </body>
</html>

In this Application, we have some logic in the execute method. If client enter the String attribute value of name, email and address, we return SUCCESS as the result otherwise we return ERROR as the result. Now, let us see our struts.xml file as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
            "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
            "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.ui.templateDir" value="template" /> 
    <constant name="struts.ui.theme" value="simple" />
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <package name="default" extends="struts-default">
                        <action name= "ClientAction" class= "com.ecomputernotes.ClientAction" method="execute">
             <result name="success">/client.jsp</result>
             <result name="error">/error.jsp</result>
        </action>
      
    </package>
</struts>

In our Application’s Action Class, we will embed some Business logic in the execute method. When execute () method completes, it return a string value either “SUCCESS” or “ERROR”. This string value is used for result element in struts.xml file. Now, let us see our ClientAction.java file as follows:

package com.ecomputernotes;
import com.opensymphony.xwork2.ActionSupport;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ClientAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private String email;
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address=address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String execute() throws Exception {
if(getName().equals("") || getName()==null  || getAddress().equals("") || getAddress()==null || getEmail().equals("") || getEmail()==null) {
            return ERROR;
}
else
{
return SUCCESS;
}
}
}

The Error result is shown by error.jsp. When the user leaves any field empty in the default.jsp, then error.jsp page is displayed. This page displays only when there is some error on default.jsp. Now, let us see our error.jsp file as follows:

<%@ 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>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>Struts2 Action Example</title>
   </head>
        <body>
           <h1>Error</h1>
           <hr/>
              <a href="default.jsp">HOME</a>
              <br/> <br/> <br/>
              <b>Error</b>
                  This Reasons for shown this error page is:
              <ul class ="bold">
                 <li>Any Field left blank.</li>
              </ul>
        </body>
</html>

When the client submit name, email and address from default.jsp, then client.jsp page is displayed. Now, let us see our client.jsp file as follows:

<%@ 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>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Struts2 Action Example</title>
    </head>
       <body>
          <h1>Client Information</h1>
          <hr/>
          <a href="default.jsp">HOME</a>
          <br/> <br/> <br/>
          <b>Thanks You</b>
          <center>
             <table border="1">
                <tr>
                  <td>Name</td>
                  <td>Email</td>
                  <td>Address</td>
                <tr>
                  <td><s:property value="name"></s:property></td>
                  <td><s:property value="email"></s:property></td>
                  <td><s:property value="address"></s:property></td>
             </table>
           </center>
       </body>
</html>

Execute the Application

Finally, start Tomcat and try to access URL https://ecomputernotes.com:8080/Struts2_Action_Example/. This will give you following screen:

      Enter Client Information

Let us enter Name, Email and Address and you should see the following page:

      After Success Page Output

Now leaves any field empty and you should see the following Output:

      After Leaving Blank Field

You’ll also like:

  1. Struts 2 Overview
  2. Struts 2 Examples
  3. Struts 2 Framework Architecture
  4. Mouse Actions in Java Swing Example
  5. What actions trigger the initialize and the terminate event of the object
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Structs Tutorials

Structs Tutorials

  • Struts - MVC Architecture
  • Struts - Framework Architecture
  • Struts - Struts2 Vs Struts1
  • Struts - Examples
  • Struts - Actions
  • Struts - Overview
  • Struts - Framework

Other Links

  • Structs - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW