Spring MVC Controller redirect using URL parameters instead of in response Spring MVC Controller redirect using URL parameters instead of in response java java

Spring MVC Controller redirect using URL parameters instead of in response


I had the same problem. solved it like this:

return new ModelAndView("redirect:/user/list?success=true");

And then my controller method look like this:

public ModelMap list(@RequestParam(required=false) boolean success) {    ModelMap mm = new ModelMap();    mm.put(SEARCH_MODEL_KEY, campaignService.listAllCampaigns());    if(success)        mm.put("successMessageKey", "campaign.form.msg.success");    return mm;}

Works perfectly unless you want to send simple data, not collections let's say. Then you'd have to use session I guess.


This problem is caused (as others have stated) by model attributes being persisted into the query string - this is usually undesirable and is at risk of creating security holes as well as ridiculous query strings. My usual solution is to never use Strings for redirects in Spring MVC, instead use a RedirectView which can be configured not to expose model attributes (see: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/RedirectView.html)

RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)

So I tend to have a util method which does a 'safe redirect' like:

public static RedirectView safeRedirect(String url) {    RedirectView rv = new RedirectView(url);    rv.setExposeModelAttributes(false);    return rv;}

The other option is to use bean configuration XML:

<bean id="myBean" class="org.springframework.web.servlet.view.RedirectView">   <property name="exposeModelAttributes" value="false" />   <property name="url" value="/myRedirect"/></bean>

Again, you could abstract this into its own class to avoid repetition (e.g. SafeRedirectView).


A note about 'clearing the model' - this is not the same as 'not exposing the model' in all circumstances. One site I worked on had a lot of filters which added things to the model, this meant that clearing the model before redirecting would not prevent a long query string. I would also suggest that 'not exposing model attributes' is a more semantic approach than 'clearing the model before redirecting'.


You can have processForm() return a View object instead, and have it return the concrete type RedirectView which has a parameter for setExposeModelAttributes().

When you return a view name prefixed with "redirect:", Spring MVC transforms this to a RedirectView object anyway, it just does so with setExposeModelAttributes to true (which I think is an odd value to default to).