Spring MVC Controller: what is the difference between "return forward", "return redirect" and "return jsp file"

39,836

The first question is: I am not sure about correctness this button. It works well, but I have question mark after press this button.

Ok, it's insert a question mark because you use GET http method. You need to use POST method to pass the data in the request payload.


return "redirect:/books";

It returns to the client (browser) which interprets the http response and automatically calls the redirect URL

return "jsp/books/booksList";

It process the JSP and send the HTML to the client

return "forward:/books";

It transfer the request and calls the URL direct in the server side.


To decide which one to use you have to consider some aspects of each approach:

Forward: is faster, the client browser is not involved, the browser displays the original URL, the request is transfered do the forwarded URL.

Redirect: is slower, the client browser is involved, the browser displays the redirected URL, it creates a new request to the redirected URL.

Share:
39,836
Argamidon
Author by

Argamidon

Updated on July 09, 2022

Comments

  • Argamidon
    Argamidon almost 2 years

    I don't understand what I should use. I have two pages - intro.jsp(1) and booksList.jsp(2). For each page I created one Controller Class. The first page has button which opens second page:

    <form method="GET" action="/request-list">
            <input type="submit"/>
    </form>
    

    The first question is: I am not sure about correctness this button. It works well, but I have question mark after press this button.

    The second question is: When I press that button, method with next annotation is called (Controller for the second page):

    @RequestMapping(value = "/books")
    @Controller
    public class BooksListController {
    
       @RequestMapping
       public String booksList() {
          return "jsp/books/booksList";
       }
    }
    

    What should I return by this method? In other words how can I jump from first page to second one?

    1. return "redirect:/books"; returns http://localhost:8080/books?
    2. return "jsp/books/booksList"; returns http://localhost:8080/request-list?
    3. return "forward:/books"; returns http://localhost:8080/request-list?

    I see that result is the same: all these Strings gave me the same page (page 2 was opened). In which cases I should use "redirect", "forward", "page.jsp"?

    Also I've read Post/Redirect/Get article. Do I have to use "redirect" after POST method handling??