Spring MVC Request Forwarding And Redirection

Spring MVC Request Forwarding And Redirection

In Spring MVC, you can control the flow of your application using request forwarding and redirection. Both techniques are used to send users from one URL to another, but they work a bit differently:

  • Forward: This is handled on the server-side without the client's knowledge. The URL in the browser remains the same, even though the resource being returned might be from a different URL.
  • Redirect: This sends an HTTP status back to the client (302 by default), instructing it to send a new request to the specified URL. As a result, the URL in the browser changes to the redirected URL.

Here's how you can implement both techniques:

  1. Forwarding:

    You can use the "forward:" prefix in the controller method's return string to forward a request:

    @GetMapping("/original")
    public String forwardRequest() {
        return "forward:/destination";
    }
    

    In this example, when a GET request is made to "/original", the request will be forwarded to "/destination".

  2. Redirection:

    Similarly, you can use the "redirect:" prefix in the controller method's return string to redirect a request:

    @GetMapping("/original")
    public String redirectRequest() {
        return "redirect:/destination";
    }
    

    In this example, when a GET request is made to "/original", the client will be redirected to "/destination".

Important Notes:

  • When you redirect, all original request parameters are lost since it's a completely new request. If you want to keep some parameters, you need to append them to the redirect URL or use flash attributes.
  • The "forward:" and "redirect:" prefixes can also be used with POST requests.
  • The "redirect:" prefix will use a relative path if you start the destination URL without a leading slash.
  • Forwarding keeps the original request method (GET, POST, etc.), while redirection always results in a GET request. If you need to keep the original request method and parameters, consider using forwarding. If you need to create a new request or send the client to a different domain, consider using redirection.
  • If you need to forward or redirect to another server (external URL), you can only use redirect. Forward only works within the same application because it's handled by the servlet container.

More Tags

submenu deserialization uirefreshcontrol sax tablecell build-definition reveal.js libsass mongodb heap-memory

More Programming Guides

Other Guides

More Programming Examples