Home  >  Article  >  Java  >  How to Redirect to External URLs from Spring MVC Controller Actions?

How to Redirect to External URLs from Spring MVC Controller Actions?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 00:04:02996browse

How to Redirect to External URLs from Spring MVC Controller Actions?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn