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) {
}
}
Comments
-
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 about 12 yearsThanks a lot, just tested it and it worked. Had to change the method return type from
ModelAndView
toString
. -
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 over 8 years@TomaszNurkiewicz I found the answer here: stackoverflow.com/a/32406090/1385441
-
jzheaux about 7 yearsNote 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/…