将应用程序从 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 change ActionForward
with dynamic params in Struts 2 ?
您可以使用带有 result
的动态参数,请参阅 动态结果配置.
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;
}
}
如果您需要更好的方法从操作映射创建 url,您可以查看 这个答案.
If you need a better way to create the urls from action mapping, you could look at this answer.
这篇关于如何在 Struts 2 中使用动态参数更改 ActionForward的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!