Spring-MVC controller redirect to "previous" page?

One option, of course, would be to open the edit form in a new window, so all the user has to do is close it and they're back where they were.

There are a few places in my current application where I need to do something complicated, then pass the user to a form, and then have them return to the starting point. In those cases I store the starting point in the session before passing them off. That's probably overkill for what you're doing.

Other options: 1) you can store the "Referer" header and use that, but that may not be dependable; not all browsers set that header. 2) you could have javascript on the confirmation page after the form submission that calls "history.go(-2)".


My answer is alike to Sam Brodkins´s (i recomended it also). But having in count that the "Referer" value may not be available i made this function to use it in my controllers

/**
* Returns the viewName to return for coming back to the sender url
*
* @param request Instance of {@link HttpServletRequest} or use an injected instance
* @return Optional with the view name. Recomended to use an alternativa url with
* {@link Optional#orElse(java.lang.Object)}
*/
protected Optional<String> getPreviousPageByRequest(HttpServletRequest request)
{
   return Optional.ofNullable(request.getHeader("Referer")).map(requestUrl -> "redirect:" + requestUrl);
}

So in your controller caller function you should return something like this:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
String testRedirection(HttpServletRequest request)
{
      //Logic....
      //Returns to the sender url
      return getPreviousPageByRequest(request).orElse("/"); //else go to home page
}

Yes I think Jacob's idea for the form in a new window may be a good option. Or in a hidden div. Like a dojo dialog. http://dojocampus.org/explorer/#Dijit_Dialog_Basic


Here's how to do it boys (Note this is RESTful Spring 3 MVC syntax but it will work in older Spring controllers):

@RequestMapping(value = "/rate", method = RequestMethod.POST)
public String rateHandler(HttpServletRequest request) {
    //your controller code
    String referer = request.getHeader("Referer");
    return "redirect:"+ referer;
}