Search code examples
sessionservletshttp-redirectsendrequestdispatcher

Why use requestDispatcher to pass request instead of just storing in session?


As in the title, is there a reason we use requestDispatcher forward() method to pass around the requestScope object? Isn't it also doable by utilizing sessionScope and sendRedirect() method from response object?

Can you please give some samples of when one would be better than the other?


Solution

    • With Servlet dispatching mechanism the same request is "processed" by many service components (servlets,JSPs,etc).

    • With redirection mechanism you force the browser to make another request.

    It all depends on what you have to achieve.

    In a typical MVC context the Servlet represents the controller component used, for example, to retreive data from the persistance layer. This data is request scoped data used by your JSP to present it to the user. So it would make no sense to make it session data when it's not session scoped data.