How to use ForwardAction in Struts

In this tutorial you will learn the use of struts framework in-build Action ForwardAction class.

The struts framework ForwardAction class provides a mechanism for forwarding to a specified URL. In an MVC Web application, all requests to the application are supposed to flow through the Controller servlet. This will ensure that the Controller layer of the application has an opportunity to prepare any resources that may be needed to handle the request meaning selecting the correct module and so on. The struts framework ForwardAction is provided as a simple utility action that can be used for scenarios in which you simply want to link to a JSP page.

Even you can do the same linking directly to the JSP page, but that would be violation of MVC principle, because all requests are supposed to be going through the Controller.

The struts framework ForwardAction can be used to create links to JSPs so that you don’t have to create an action whose only responsibility is to forward a request every time you want to link to a JSP. With ForwardAction, you simply create an action mapping in the Struts configuration

To use struts ForwardAction, you need to simply create action mapping entries in the Struts configuration file, as shown below:

action path="/home" type="org.apache.struts.actions.ForwardAction"
            parameter="/home.jsp" />

For each page to which you want to link, you must create an action mapping. Each action mapping uses ForwardAction, but each specifies a different path for the action. The parameter attribute specifies the URL that will be forwarded to when the specified path is accessed.

Forward without any action class in struts

You can forward any action without having any action class in struts, there is an alternative solution to using ForwardAction or if you don’t want to use any action class either created by struts framework or your own class, in which you forward your action to any other JSP page or other action. In this case you can use the forward attribute of the action tag in the Struts configuration file, as shown below:

<action path="/home" forward="/home.jsp"/>

These two approaches effectively generate the same results.