Using ActionForward with dynamic params in Struts 2

人盡茶涼 提交于 2019-12-17 20:24:56

问题


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 use ActionForward with dynamic params in Struts 2 ?


回答1:


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.



来源:https://stackoverflow.com/questions/17838412/using-actionforward-with-dynamic-params-in-struts-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!