How to change ActionForward with dynamic params in Struts 2

john picture john · Jul 24, 2013 · Viewed 13.8k times · Source

While migrating the application from Struts 1 to Struts 2

In some of the places, the same action class has been used for different type of views, based on the request params.

For example: if the createType is 1 means need to append one param or if the createType is 2 means need to append some more extra params, like that I need to pass dynamic params to some other action using ActionForward.

struts-config.xml:

<action path="/CommonAction" type="com.example.CommonAction" scope="request">
    <forward name="viewAction" path = "/ViewAction.do"/>
</action>

Action class:

public class CreateAction extends Action
{
    public ActionForward execute(ActionMapping m, ActionForm f, HttpServletRequest req, HttpServletResponse res) throws ServletException, Exception
    {
            String actionPath = m.findForward("viewAction").getPath();
            String createType = req.getParameter("createType");
            String params = "&action=view";
            if("1".equals(createType)){
               params = params + "&from=list";
            }else if("2".equals(createType)){
               params = params + "&from=detail&someParam=someValue";
            }//,etc..
            String actionUrl = actionPath+"?"+params;
            return new ActionForward(actionUrl);
    }
}

But, I not able to do the same thing in Struts 2. Is there any possibilities to change ActionForward with dynamic params in Struts 2 ?

Answer

Roman C picture Roman C · Jul 24, 2013

You could use a dynamic parameters with a result, see the dynamic result configuration.

In the action you should write a getter for the patrameter

private String actionUrl;

public String getActionUrl() {
    return actionUrl;
}

and configure result

<action name="create" class="CreateAction">
    <result type="redirect">${actionUrl}</result>
</action>

So, the common sense would be rewrite the code like

public class CreateAction extends ActionSupport
{

    private String actionUrl;

    public String getActionUrl() {
        return actionUrl;
    }

    @Override
    public String execute() throws Exception
    {
            String actionPath = "/view";
            String createType = req.getParameter("createType");
            String params = "&action=view";
            if("1".equals(createType)){
               params = params + "&from=list";
            }else if("2".equals(createType)){
               params = params + "&from=detail&someParam=someValue";
            }//,etc..
            actionUrl = actionPath+"?"+params;
            return SUCCESS;
    }
}

If you need a better way to create the urls from action mapping, you could look at this answer.