Redirect to dynamic URL in Spring MVC

90,310

Solution 1

Try this:

@RequestMapping("/redirectToSite")
protected String redirect(@RequestParam("redir_url") String redirectUrl) 
{
    return "redirect:" + redirectUrl;
}

This is explained in 16.5.3.2 The redirect: prefix of Spring reference documentation. Of course you can always do this manually:

response.sendRedirect(redirectUrl);

Solution 2

@RequestMapping(value="/redirect",method=RequestMethod.GET)
void homeController(HttpServletResponse http){
  try {
    http.sendRedirect("Your url here!");
  } catch (IOException ex) {

  }
}
Share:
90,310
Gruber
Author by

Gruber

This about me is currently blank

Updated on July 18, 2022

Comments

  • Gruber
    Gruber almost 2 years

    I want my Spring MVC application to redirect to a dynamic URL (submitted by the user). So if I have code like this,

    @RequestMapping("/redirectToSite")
    protected ModelAndView redirect(
        @RequestParam("redir_url") String redirectUrl,
        HttpServletRequest request, 
        HttpServletResponse response) 
    {
        // redirect to redirectUrl here
        return ?
    }
    

    what should I write to redirect to the submitted URL? For instance http://mySpringMvcApp/redirectToSite?redir_url=http://www.google.com should redirect to Google.

  • Gruber
    Gruber about 12 years
    Thanks a lot, just tested it and it worked. Had to change the method return type from ModelAndView to String.
  • Ram Patra
    Ram Patra over 8 years
    @TomaszNurkiewicz this method preserves the query parameters in the url, how do I get rid of the query parameters and redirect just to the url without query parameters?
  • Ram Patra
    Ram Patra over 8 years
    @TomaszNurkiewicz I found the answer here: stackoverflow.com/a/32406090/1385441
  • jzheaux
    jzheaux about 7 years
    Note that this code as it stands is not verifying the redirect url to ensure it's legit. I realize that this question wasn't about security, but would remind folks to not just lift this code as is. Never trust the client to always specify urls that you are okay with redirecting to. owasp.org/index.php/…