"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Redirect to External URLs from Spring MVC Controller Actions?

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

Published on 2024-11-20
Browse:473

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3