Redirecting to External URLs from Spring MVC Controller Actions
In Spring MVC, redirecting to URLs within the project is straightforward using the redirect: prefix. However, redirecting to external URLs can be tricky, especially if the URL does not specify a valid protocol.
Consider the following code, which redirects to a URL within the project:
@RequestMapping(method = RequestMethod.POST) public String processForm(HttpServletRequest request, LoginForm loginForm, BindingResult result, ModelMap model) { String redirectUrl = "yahoo.com"; return "redirect:" + redirectUrl; }
This code will not redirect to the intended external URL but instead redirect to a view with the given name. To redirect to external URLs, one must include the protocol in the URL, as seen below:
@RequestMapping(method = RequestMethod.POST) public String processForm(HttpServletRequest request, LoginForm loginForm, BindingResult result, ModelMap model) { String redirectUrl = "http://www.yahoo.com"; return "redirect:" + redirectUrl; }
However, this method requires the presence of a valid protocol. To handle URLs without valid protocols, two approaches are available:
Approach 1:
@RequestMapping(value = "/redirect", method = RequestMethod.GET) public void method(HttpServletResponse httpServletResponse) { httpServletResponse.setHeader("Location", projectUrl); httpServletResponse.setStatus(302); }
In this approach, a HttpServletResponse object is used to set the location header and status code, forcing the redirect.
Approach 2:
@RequestMapping(value = "/redirect", method = RequestMethod.GET) public ModelAndView method() { return new ModelAndView("redirect:" + projectUrl); }
This approach employs a ModelAndView to redirect to the given URL.
The above is the detailed content of How to Redirect to External URLs from Spring MVC Controller Actions?. For more information, please follow other related articles on the PHP Chinese website!