Redirect to an external URL from controller action in Spring MVC
You can do it with two ways.
First:
@RequestMapping(value = "/redirect", method = RequestMethod.GET)public void method(HttpServletResponse httpServletResponse) { httpServletResponse.setHeader("Location", projectUrl); httpServletResponse.setStatus(302);}
Second:
@RequestMapping(value = "/redirect", method = RequestMethod.GET)public ModelAndView method() { return new ModelAndView("redirect:" + projectUrl);}
You can use the RedirectView
. Copied from the JavaDoc:
View that redirects to an absolute, context relative, or current request relative URL
Example:
@RequestMapping("/to-be-redirected")public RedirectView localRedirect() { RedirectView redirectView = new RedirectView(); redirectView.setUrl("http://www.yahoo.com"); return redirectView;}
You can also use a ResponseEntity
, e.g.
@RequestMapping("/to-be-redirected")public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException { URI yahoo = new URI("http://www.yahoo.com"); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(yahoo); return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);}
And of course, return redirect:http://www.yahoo.com
as mentioned by others.
Looking into the actual implementation of UrlBasedViewResolver and RedirectView the redirect will always be contextRelative if your redirect target starts with /. So also sending a //yahoo.com/path/to/resource wouldn't help to get a protocol relative redirect.
So to achieve what you are trying you could do something like:
@RequestMapping(method = RequestMethod.POST)public String processForm(HttpServletRequest request, LoginForm loginForm, BindingResult result, ModelMap model) { String redirectUrl = request.getScheme() + "://www.yahoo.com"; return "redirect:" + redirectUrl;}