Spring MVC's redirect: prefix is a powerful and concise way to perform an HTTP redirect from your controller method. When you return a String starting with redirect:, Spring understands you want the browser to issue a new request to the specified URL.
A common and important use case for this is redirecting to external URLs, including those with http:// or https:// protocols. Unlike internal forwards, which remain within your application's DispatcherServlet and retain the original request attributes, a redirect: sends an HTTP 302 (Found) status code back to the client, along with a Location header containing the new URL. The client then initiates a completely fresh request to that location.
@Controller
public class MyController {
@GetMapping("/external-link")
public String redirectToExternalSite() {
// This will redirect the user's browser to Google's homepage
return "redirect:http://www.google.com";
}
@GetMapping("/secure-redirect")
public String redirectToSecureExternalSite() {
// Redirect to an HTTPS site
return "redirect:https://www.secure-app.com/login";
}
}
This flexibility makes redirect: invaluable for scenarios like:
- OAuth/SSO callbacks: Redirecting users to an identity provider's login page and back.
- Payment gateways: Sending users to external payment processing sites.
- Linking to external resources: Directing users to documentation, partner sites, or other web applications.
Key takeaway: When you need the client's browser to make a fresh request to an entirely different URL, even one on a different domain or protocol, Spring MVC's redirect: prefix with a full URL (including http:// or https://) is the simple and correct approach.
No comments:
Post a Comment