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.

TestAction.java

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) {
		this.name = name;
	}

	@Override
	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.

login.jsp

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

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

</body>
</html>

home.jsp

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

struts.xml

<?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.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>
</action>

</package>

</struts>

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


 


Download this example code

Related Tags for Implementing Actions in Struts 2:

Advertisements

Ads

 
Advertisement null

Ads