Redirecting to External URLs in Spring MVC
In Spring MVC, the redirect: prefix is often used to redirect users within the application. However, there might be instances where we need to redirect to external URLs.
Problem Statement
The following code snippet redirects users to a URL within the project:
@RequestMapping(method = RequestMethod.POST) public String processForm(..., String redirectUrl) { return "redirect:" + redirectUrl; }
Alternatively, the following code requires the specification of a protocol (HTTP/HTTPS) for external redirects:
@RequestMapping(method = RequestMethod.POST) public String processForm(..., String redirectUrl) { return "redirect:" + "http://" + redirectUrl; }
Solution
To redirect to an external URL without specifying the protocol or redirecting to a view, consider these solutions:
Method 1:
Set the Location header and the status code directly:
@RequestMapping(value = "/redirect", method = RequestMethod.GET) public void method(HttpServletResponse httpServletResponse) { httpServletResponse.setHeader("Location", projectUrl); httpServletResponse.setStatus(302); }
Method 2:
Use the ModelAndView to redirect to the external URL:
@RequestMapping(value = "/redirect", method = RequestMethod.GET) public ModelAndView method() { return new ModelAndView("redirect:" + projectUrl); }
The above is the detailed content of How to Redirect to External URLs in Spring MVC?. For more information, please follow other related articles on the PHP Chinese website!