Redirect to an External URL from Controller Action in Spring MVC
When attempting to redirect to an external URL from a controller action in Spring MVC, it's important to understand the limitations of the default "redirect:" syntax. By default, Spring redirects to URLs within the application's context path.
Redirecting to Internal URLs
As demonstrated in the first code snippet:
@RequestMapping(method = RequestMethod.POST) public String processForm(...) { String redirectUrl = "yahoo.com"; return "redirect:" + redirectUrl; }
This code attempts to redirect to the URL "yahoo.com" but lacks a valid protocol (e.g., http:// or https://). As a result, Spring interprets it as an internal URL and redirects to "yahoo.com" within the application's context path.
Redirecting to External URLs with Protocol
To redirect to an external URL with a protocol, the following approach can be used:
@RequestMapping(method = RequestMethod.POST) public String processForm(...) { String redirectUrl = "http://www.yahoo.com"; return "redirect:" + redirectUrl; }
By specifying the protocol in the URL, Spring correctly redirects the user to the external website.
Redirecting to External URLs Without Protocol
To redirect to an external URL without a protocol using Spring MVC, two alternatives exist:
Method 1:
@RequestMapping(value = "/redirect", method = RequestMethod.GET) public void method(HttpServletResponse httpServletResponse) { httpServletResponse.setHeader("Location", projectUrl); httpServletResponse.setStatus(302); }
This method manually sets the "Location" header and the appropriate HTTP status code (302) in the response to trigger a redirect.
Method 2:
@RequestMapping(value = "/redirect", method = RequestMethod.GET) public ModelAndView method() { return new ModelAndView("redirect:" + projectUrl); }
This method uses the "ModelAndView" class to create a redirect response with the specified URL.
The above is the detailed content of How to Redirect to an External URL from a Spring MVC Controller Action?. For more information, please follow other related articles on the PHP Chinese website!