1) Introduction
Action classes will be defined to handle requests. Actions exists between the Model and View of an application. This article will cover all of the standard actions and the helper methods of the Action class.
The struts-config.xml file designates the Action classes that handle requests for various URLs. The Action objects do
- Invoke the appropriate business
- Data-accesslogic
- Store the results in beans
- Designate the type of situation (missing data, database error etc.)
The struts-config.xml file then decides which JSP page should apply to that situation. Generally Actions do
- Invoke business rules
- Return Model objects to the View to display.
Actions also prepare error messages to display in the View. We can also create utility actions. Utility actions can be linked to other actions using action chaining. This allows us to extend the behavior of an action without changing an action or having deeply nested class hierarchies of actions.
Actions have a life cycle similar to servlets. They are like servlets and they're multithreaded. We must be careful when working with member variables of an action because they are not thread safe. Struts has a servlet called the ActionServlet. The ActionServlet inspects the incoming request and delegates the request to an action based on the incoming request path. The object that relates the action to the incoming request path is the Action Mapping. Our actions are part of the Struts Controller.
2) Using Action classes
Typically There are 3 steps to create an Action
-
1. Create an action by subclassing org.apache.struts.action.Action
import org.apache.struts.action
public class ExampleAction extends Action { … }
-
2. Override the execute() method : This is the method where we define the behavior of the current action. It contains business logic and the way to next action. The general structure of the execute() method is as follows:
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
The Action Mapping contains everything configurable in the action element of the Struts config file. The ActionForm represents the incoming request parameters. The HttpServletRequest references the current request object. No compulsary use for HttpServletResponse. The execute() method returns an ActionForward. The ActionForward is the logical next View or the logical next step.
-
3. Configure the Action in the Struts config file. As follows
<action
path="/ExampleAction "
type="ExampleAction ">
<forward name="success" path="/Example.jsp"/>
</action>
The path attribute specifies the incoming request path that this action will handle.Here we have the Major Classification of Struts Actions.
- org.apache.struts.actions
- Forward Action
- IncludeAction
- SwitchAction
- DispatchAction
Here mainly we are going to discuss about the above 5 actions.
|