http-redirectstruts2strutsendpointactionresult

In Apache Struts, how can I redirect to an external URL without writing an Action class?


In my Struts application, I need to create an endpoint (URL) which simply tells the user's browser to redirect to an external URL.

It looks like this can be done by creating a new Action class and defining a new <result type='redirect'> result, but that seems like overkill. I don't need an Action class to do any kind of processing on my end, just a simple redirect.

Is there a way I can set up an endpoint simply with a line or two in a configuration file?


Solution

  • You can create the endpoint using an action configuration and without the Action class. Then add a redirect result type. You can use it with any package that extends a struts-default.

    <package name="default" namespace="/" extends="struts-default">
      <action name="redirect_to_outside_website/*">
            <result type="redirect">{1}</result>
        </action>
    </package>
    

    You can see more details here.


    To use slashes in action name you should use these constants

    <constant name="struts.enable.SlashesInActionNames" value="true"/>
    <constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
    
    

    The example above can redirect to any URL using a wildcard mapper (which is a default mapper in Struts 2). If you need to fix the URL in the configuration file, then you can place a fixed URL directly to the <result> tag.

    <package name="default" namespace="/" extends="struts-default">
      <action name="redirect_to_outside_website">
            <result type="redirect">https://server_domain/my_fixed_location</result>
        </action>
    </package>