views:

11185

answers:

3

I'm trying to have my struts2 app redirect to a generated url. In this case, I want the url to use the current date, or a date I looked up in a database. So /section/document becomes /section/document/2008-10-06

What's the best way to do this?

+1  A: 

I ended up subclassing Struts' ServletRedirectResult and overriding it's doExecute() method to do my logic before calling super.doExecute(). it looks like this:

public class AppendRedirectionResult extends ServletRedirectResult {
   private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

  @Override
  protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    String date = df.format(new Date());
    String loc = "/section/document/"+date;
    super.doExecute(loc, invocation);
  }
}

I'm not sure if this is the best way to do it, but it works.

Sietse
+9  A: 

Here's how we do it:

In Struts.xml, have a dynamic result such as:

<result name="redirect" type="redirect">${url}</result>

In the action:

private String url;

public String getUrl()
{
 return url;
}

public String execute()
{
 [other stuff to setup your date]
 url = "/section/document" + date;
 return "redirect";
}

You can actually use this same technology to set dynamic values for any variable in your struts.xml using OGNL. We've created all sorts of dynamic results including stuff like RESTful links. Cool stuff.

Johnny Wey
Thanks a lot, that works nicely! Is there some way to do the change to the xml so that it doesn't need to be applied to each and every action i've got? I'd ideally like that to be applicable to all my actions.
Chris
You might try a global result. I haven't experimented with this for dynamic variables, but, as long as the action returns the result, I don't see any reason it wouldn't work.
Johnny Wey
+1  A: 

One can also use annotations and the Convention plug-in to avoid repetitive configuration in struts.xml:

@Result(location="${url}", type="redirect")

The ${url} means "use the value of the getUrl method"

Ivan

Ivan Morales