Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to an external URL from controller action in Spring MVC

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,

like image 384
Jake Avatar asked Jul 30 '13 19:07

Jake


People also ask

How redirect external URL from view in MVC?

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.

How do I redirect a URL in spring?

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.


2 Answers

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); } 
like image 119
Rinat Mukhamedgaliev Avatar answered Oct 03 '22 03:10

Rinat Mukhamedgaliev


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.

like image 44
matsev Avatar answered Oct 03 '22 04:10

matsev