Using ActionForward with dynamic parameters in Struts 2

When porting an application from Struts 1 to Struts 2

In some places, the same class of actions was used for different types of views based on query parameters.

For example: if createType is 1, you need to add one parameter, or if createType is 2, you need to add some more additional parameters, for example, I need to pass dynamic parameters to other actions using ActionForward .

<strong> 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 can’t do the same in Struts 2. Is it possible to use ActionForward with dynamic parameters in Struts 2?

+4
source share
1 answer

You can use dynamic parameters with result , see dynamic configuration of the result .

In action, you must write a getter for the parameter

 private String actionUrl; public String getActionUrl() { return actionUrl; } 

and adjust the result

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

So, common sense will rewrite 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 URLs from action mappings, you can see this answer.

+4
source

Source: https://habr.com/ru/post/1493237/


All Articles