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?
return "redirect:/books"; returns http://localhost:8080/books?
return "jsp/books/booksList"; returns http://localhost:8080/request-list?
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??
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.
return RedirectToAction()To redirect to a different action which can be in the same or different controller. It tells ASP.NET MVC to respond with a browser to a different action instead of rendering HTML as View() method does. Browser receives this notification to redirect and makes a new request for the new action.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With