在 Struts 2 中重定向到具有未知数量参数的另一个动作
我有一个登录操作,在成功执行后重定向到上一页(我将上一页存储在我的会话中,以便以后获取它).在 Struts2 中,我可以找到两种方法来进行这种重定向:
I have a login action which after successful execution redirects to the previous page (I store the previous page in my session so I can fetch it later). In Struts2, I can find two ways to do this redirection:
<action name="login" class="com.myapp.login.Login">
<result name="redirect" type="redirect">${previousAction.requestURL}</result>
</action>
在这个例子中,将调用 getPreviousAction().getRequestURL()
方法(这是一个自制的方法,它不是 Struts2 的原生方法),这将返回上一页的 URL意图,例如:
In this example, the getPreviousAction().getRequestURL()
method (this is a selfmade method, its not native to Struts2) will be invoked and this will return the URL of the previous page as intended, for example:
somenamespace/index.action
还有另一种类型的重定向:
There is also another type of redirection:
<action name="login" class="com.myapp.login.Login">
<result type="redirectAction">
<param name="actionName">${previousAction.name}</param>
<param name="namespace">/${previousAction.namespace}</param>
</result>
</action>
我想使用这种`redirectAction 结果类型,因为它更简洁.但是,当查询参数是 URL 的一部分时,我遇到了问题.例如:
I want to use this `redirectAction result type because it is much cleaner. But, I have a problem when query parameters are part of the URL. For example:
somenamespace/index.action?name=john&age=50
我知道我可以在我的 struts.xml
中添加这些硬编码的参数,但问题是我的登录操作应该重定向到 any 以前调用的操作,而我没有事先知道之前的操作有哪些查询参数.这与您确切知道要重定向到哪个操作的典型用例不同
I know I can add these params hardcoded in my struts.xml
, but the problem is my login action should redirect to any previously invoked action, and I do not know beforehand which query parameters the previous actions had. This is different from the typical usecase where you know exactly to which action you're redirecting to
我发现一个非常糟糕的解决方案是添加 every 可能的参数(我在 struts.xml
中的所有操作的所有参数的集合),然后使用以下选项:
A very bad solution I found was adding every param possible (the collection of all params of all my actions in struts.xml
) and then use the option:
<param name="suppressEmptyParameters">true</param>
推荐答案
您可以从 ActionMapping
中保存动作名称、命名空间和参数.
You can save action name, namespace, and parameters from the ActionMapping
.
ActionMapping mapping = ServletActionContext.getActionMapping();
您也可以保存查询字符串而不是参数映射.
You can also save query string instead of parameter map.
String params = request.getQueryString();
要将参数动态添加到 redirectAction
结果,您应该在动态参数中使用 OGNL.
To add parameters dynamically to redirectAction
result you should use OGNL in a dynamic parameter.
<param name="actionName">${previousAction.name +'?'+ parameters}</param>
假设您有一个用于 parameters
的 getter,并从保存先前查询字符串、操作名称和命名空间的会话中对其进行初始化.
Supposed you have a getter for parameters
and initialized it from session where you saved previous query string, action name, and namespace.
相关文章