Home > Java > javaTutorial > How to Redirect to an External URL from a Spring MVC Controller Action?

How to Redirect to an External URL from a Spring MVC Controller Action?

Linda Hamilton
Release: 2024-11-29 14:47:10
Original
358 people have browsed it

How to Redirect to an External URL from a Spring MVC Controller Action?

Redirect to an External URL from Controller Action in Spring MVC

When attempting to redirect to an external URL from a controller action in Spring MVC, it's important to understand the limitations of the default "redirect:" syntax. By default, Spring redirects to URLs within the application's context path.

Redirecting to Internal URLs

As demonstrated in the first code snippet:

@RequestMapping(method = RequestMethod.POST)
public String processForm(...) {
    String redirectUrl = "yahoo.com";
    return "redirect:" + redirectUrl;
}
Copy after login

This code attempts to redirect to the URL "yahoo.com" but lacks a valid protocol (e.g., http:// or https://). As a result, Spring interprets it as an internal URL and redirects to "yahoo.com" within the application's context path.

Redirecting to External URLs with Protocol

To redirect to an external URL with a protocol, the following approach can be used:

@RequestMapping(method = RequestMethod.POST)
public String processForm(...) {
    String redirectUrl = "http://www.yahoo.com";
    return "redirect:" + redirectUrl;
}
Copy after login

By specifying the protocol in the URL, Spring correctly redirects the user to the external website.

Redirecting to External URLs Without Protocol

To redirect to an external URL without a protocol using Spring MVC, two alternatives exist:

Method 1:

@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void method(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", projectUrl);
    httpServletResponse.setStatus(302);
}
Copy after login

This method manually sets the "Location" header and the appropriate HTTP status code (302) in the response to trigger a redirect.

Method 2:

@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView method() {
    return new ModelAndView("redirect:" + projectUrl);
}
Copy after login

This method uses the "ModelAndView" class to create a redirect response with the specified URL.

The above is the detailed content of How to Redirect to an External URL from a Spring MVC Controller Action?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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