Home > Java > javaTutorial > body text

How to Redirect to External URLs in Spring MVC?

Barbara Streisand
Release: 2024-11-11 17:10:03
Original
167 people have browsed it

How to Redirect to External URLs in Spring MVC?

Redirecting to External URLs in Spring MVC

In Spring MVC, the redirect: prefix is often used to redirect users within the application. However, there might be instances where we need to redirect to external URLs.

Problem Statement

The following code snippet redirects users to a URL within the project:

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

Alternatively, the following code requires the specification of a protocol (HTTP/HTTPS) for external redirects:

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

Solution

To redirect to an external URL without specifying the protocol or redirecting to a view, consider these solutions:

Method 1:

Set the Location header and the status code directly:

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

Method 2:

Use the ModelAndView to redirect to the external URL:

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

The above is the detailed content of How to Redirect to External URLs in Spring MVC?. 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