在Struts 2中使用ActionForward和动态参数 [英] Using ActionForward with dynamic params in Struts 2
问题描述
将应用程序从Struts 1迁移到Struts 2时
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.
例如:如果 createType
为1则表示需要附加一个参数或 createType
是2意味着需要追加一些额外的参数,比如我需要使用 ActionForward
将动态参数传递给其他动作。
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>
行动类
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);
}
}
但是,我无法做同样的事情Struts 2.是否有可能在Struts 2中使用带动态参数的 ActionForward
?
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 ?
推荐答案
您可以使用带有结果
的动态参数,请参阅动态结果配置。
You could use a dynamic parameters with a result
, see the dynamic result configuration.
在操作中你应该为参数编写一个getter
In the action you should write a getter for the patrameter
private String actionUrl;
public String getActionUrl() {
return actionUrl;
}
并配置结果
<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.
这篇关于在Struts 2中使用ActionForward和动态参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!