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

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

Patricia Arquette
Release: 2024-11-12 00:04:02
Original
1075 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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);
}
Copy after login

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);
}
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template