Implementing Actions in Struts 2
Posted on: November 24, 2010 at 12:00 AM
In this tutorial you will learn about the struts Action interface and also learn how to use it in writing own Action class

Implementing Actions in Struts 2

Package com.opensymphony.xwork2 contains the many Action classes and interface, if you want to make an action class for you then you should implement or extend its classes or interface respectively. Actions the contains the execute() method. All the business logic is present in this method. When an action is called the execute method is executed. You can make many action classes depending on your application need. And these action classes must be mapped into the struts.xml file.

Suppose you are writing the following Action class by implementing Action interface.

package net.roseindia;

import com.opensymphony.xwork2.Action;

public class TestAction implements Action {
	String control = LOGIN;
	String name;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String execute() throws Exception {
		// TODO Auto-generated method stub
		if (name.length() > 0 && name.equalsIgnoreCase("web")) {
			control = SUCCESS;
		} else {
			control = ERROR;
		return control;

In the above code TestAction is implementing the Action interface and implementing its execute() method. This execute() method forwarding the control of the application to their respected pages.


<%@ taglib prefix="s" uri="/struts-tags" %>
<h1>Action Example</h1>

<h2>Please Enter Your Name</h2>
<s:form action="testAction" >
<s:textfield name="name" label="Name" value=""/>
<s:submit />



<%@ taglib prefix="s" uri="/struts-tags" %>
<body >
<h1> This is your Home Page</h1>
<font color=green size=15 face=modern> Welcome : <s:property value="name" /></font><br>


<?xml version="1.0" encoding="UTF-8" ?>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"


<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />

<package name="roseindia" extends="struts-default">

<action name="testAction" 
class="net.roseindia.TestAction" >
<result name="error">/jsp/login.jsp</result>
<result name="success">/jsp/home.jsp</result>



When you run this application it will display message as shown below:


Download this example code

Related Tags for Implementing Actions in Struts 2:



Advertisement null