Once in a while, even a blind squirrel finds a nut.
Struts Redirect w/Parameters
If you have a Struts Action servlet and you want to redirect to another page, the standard Struts technique is to return an ActionForward and setup an appropriate forward entry in struts-config.xml:
1
returnmapping.findForward("success");
Unfortunately, this doesn’t provide a mechanism for passing request parameters to the target. So what can you do if you want to redirect to another page and pass some parameters along? You use an additional class:
publicclassForwardParameters{privateMapparams=null;publicForwardParameters(){params=newHashMap();}/** * Add a single parameter and value. * * @param paramName Parameter name * @param paramValue Parameter value * * @return A reference to this object. */publicForwardParametersadd(StringparamName,StringparamValue){params.put(paramName,paramValue);returnthis;}/** * Add a set of parameters and values. * * @param paramMap Map containing parameter names and values. * * @return A reference to this object. */publicForwardParametersadd(MapparamMap){Iteratoritr=paramMap.keySet().iterator();while(itr.hasNext()){StringparamName=(String)itr.next();params.put(paramName,paramMap.get(paramName));}returnthis;}/** * Add parameters to a provided ActionForward. * * @param forward The ActionForward object to add parameters to. * * @return ActionForward with parameters added to the URL. */publicActionForwardforward(ActionForwardforward){StringBufferpath=newStringBuffer(forward.getPath());Iteratoritr=params.entrySet().iterator();if(itr.hasNext()){//add first parameter, if avaliableMap.Entryentry=(Map.Entry)itr.next();path.append("?"+entry.getKey()+"="+entry.getValue());//add other parameterswhile(itr.hasNext()){entry=(Map.Entry)itr.next();path.append("&"+entry.getKey()+"="+entry.getValue());}}returnnewActionForward(path.toString());}}
Here are some examples of using ForwardParameters:
As someone just pointed out to me this morning, you can use the ActionRedirect class instead of my ForwardParameters class. According to the JavaDocs, ActionRedirect was added in Struts 1.2.7 and is:
… a subclass of ActionForward which is designed for use in redirecting requests, with support for adding parameters at runtime.