Home >Java >javaTutorial >How to Redirect to External URLs in Spring MVC?

How to Redirect to External URLs in Spring MVC?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 17:10:03224browse

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;
}

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;
}

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);
}

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);
}

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!

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