Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

java - Redirecting to another action with unknown amount of parameters in Struts 2

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>

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>

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

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

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

To add parameters dynamically to redirectAction result you should use OGNL in a dynamic parameter.

<param name="actionName">${previousAction.name +'?'+ parameters}</param>

Supposed you have a getter for parameters and initialized it from session where you saved previous query string, action name, and namespace.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...