Search This Blog

Thursday 12 July 2012

Action classes


What is Action Class?

An Action class in the struts application extends Struts 'org.apache.struts.action.Action" Class. Action class acts as wrapper around the business logic and provides an inteface to the application's Model layer. It acts as glue between the View and Model layer. It also transfers the data from the view layer to the specific business process layer and finally returns the procssed data from business layer to the view layer.

An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it. Then the struts controller (ActionServlet) slects an appropriate Action and creates an instance if necessary, and finally calls execute method.

To use the Action, we need to  Subclass and overwrite the execute() method. In the Action Class don't add the business process logic, instead move the database and business process logic to the process or dao layer.

The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

Developing our Action Class?

Our Action class (Ex.java) is simple class that only forwards the Ex.jsp. Our Action class returns the ActionForward  called "test", which is defined in the struts-config.xml file


 Here is code of our Action Class:

Ex.java


package mypackage.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class Ex extends Action
{
  public ActionForward execute(
  ActionMapping mapping,
  ActionForm form,
  HttpServletRequest request,
  HttpServletResponse response) throws Exception
  {
  return mapping.findForward("test");
  }
}


the signature of the Action Class.

the signature of the Action Class.

public ActionForward execute(ActionMapping mapping,
                             ActionForm form,
                             javax.servlet.http.HttpServletRequest request,
                             javax.servlet.http.HttpServletResponse response)
                      throws java.lang.Exception

Adding the Action Mapping in the struts-config.xml
To test the application we will add a link in the index.jsp 
<html:link page="/Ex.do">Test the Action</html:link>

Following code under the <action-mappings> tag is used to for mapping the TestAction class.

   <action
      path="/Ex"
      type="mypackage.net.Ex">
      <forward name="test" path="/pages/Ex.jsp"/>
   </action>    



No comments:

Post a Comment