I have noticed the following code is redirecting the User to a URL inside the project,
@RequestMapping(method = RequestMethod.POST) public String processForm(HttpServletRequest request, LoginForm loginForm, BindingResult result, ModelMap model) { String redirectUrl = "yahoo.com"; return "redirect:" + redirectUrl; }
whereas, the following is redirecting properly as intended, but requires http:// or https://
@RequestMapping(method = RequestMethod.POST) public String processForm(HttpServletRequest request, LoginForm loginForm, BindingResult result, ModelMap model) { String redirectUrl = "http://www.yahoo.com"; return "redirect:" + redirectUrl; }
I want the redirect to always redirect to the URL specified, whether it has a valid protocol in it or not and do not want to redirect to a view. How can I do that?
Thanks,
You can redirect to an external URL by using Redirect Method() or via Json Result. Asp.net MVC redirect to URL: You can do URL redirect in mvc via Controller's Redirect() method. The following example, I have given redirection to google page.
We can use a name such as a redirect: http://localhost:8080/spring-redirect-and-forward/redirectedUrl if we need to redirect to an absolute URL.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With