I am learning Servlets/JSP/MVC and have a question about architecting a simple application. I have a site where people can vote on products.
-
In the Application Context I have an ArrayList of the Products (model class is called Product)
-
I have a home Servlet that draws all the Products (reads list from context, forwards as attribute to JSP). The items are drawn out using JSTL.
-
I have another servlet called ProductRate that can be called when viewing a Product. On doPost() is supposed to record the rating the user gives to a product (specified in a form) and saves this in Session.
I want to be able to join the information on the Home servlet to show not only the product information (stored in Application Context), but also any vote that the user as given to it. If there is no value, then I don’t show any thing saying “Thanks for your vote of X” or similar.
Should I add a field to my Product model class called “userRating” or something, and when reading the list on the Home Servlet, look at any session values stored for it and assign the vote value to the “userRating” Model value?
So in effect, I have a fixed list of objects the application always uses, but when drawing them out in a JSP, I want a nice clean way to marry any information stored in session (vote value) so handling the Model in the JSP is a breeze
You could store the rankings in a map in the session with the product ID as the key and then the jsp would look something like:
In your POST servlet/controller:
If you are interested in keeping the users’ ratings or all for the products to be managed by the web app, I would use a database rather than store data in config files and the session. Consider the following database tables:
Product: id, description, etc..
Rating: id, stars, comments, productId, userId
User: id, name, email, etc…
If you go with a database, use an ORM tool, like Hibernate to map your tables to objects. Your objects corresponding to the tables listed above would look like:
Then with hibernate, you would query for the product and get all of the information associated with it in object form for you to work with. You could pass the necessary info on to the view. Of course there is some configuration you would have to do to set hibernate up.
You mentioned MVC. Are you using an MVC framework? I would look into Spring MVC or Struts. That will help you separate the layers of your app.
The flow you mentioned seems right. Servlet/controller handles GET request to main page. Fetches all products (or specifics) along with their votes from the database. Sets them as parameters. JSP displays content using JSTL.
Have fun!