Question

I have several scenarios where a servlet needs to pass data to a form in a JSP from the retrieved records from the database. Currently, I'm storing this information in the request, using a RequestDispatcher to forward to the page, and all is well.

However, this is not fitting with the PRG pattern (AFAIK), and of course means that refreshing of the resulting JSP means re-running of the servlet, which is undesirable.

I could of course store these values in the session, but that would mean clearing them afterwards, and even using the session seems like a bit of a hack for displaying a record from the database.

I am simply wondering what would be the best practice in this situation? Should I continue using the request, use the session, or some other technique?

Thanks in advance.

Edit: After reading several articles and stack overflow answers, I can find nowhere that presents any other option than using the request and a dispatcher when passing data from a servlet to a JSP. It doesn't seem right to me, but neither does the session. Can anybody shed some light on this?

Was it helpful?

Solution

I'm not sure I fully understand the problem, but two patterns are best practices:

  1. Always go through a controller, which fills the model, stores it in the request, and dispatches to a view which displays the data in the model. That's the MVC pattern
  2. Always redirect after a successful non-idempotent request (i.e. a POST, if you respect the HTTP protocol). That's the post-redirect-get pattern.

So what it means is that you should have:

  • request 1 goes to a servlet.
  • servlet gets data to be displayed in the form and stores it in the request, then forwards to the JSP
  • the JSP displays the form
  • the form is submitted to a servlet (request 2)
  • servlet stores the data in the database, which generates an ID for the created data
  • servlet redirects to a URL like /product?id=<generatedId> or /product/<generatedId>
  • browser sends a request to this URL (request 3). This request goes to a servlet
  • servlet gets the data identified by the ID, from the database. It stores the data into the request, and forwards to a JSP
  • the JSP displays the data.

Of course, you could choose to redirect to some other page, like the list of products for example.

If what bothers you is to use the request to store data when forwarding from the servlet to the JSP, then that shouldn't bother you: it's the only clean way to do it. The data will be scoped to the request only, and be garbage-collected when the request has been processed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top