I'm studying JSP on my own and I'm getting into lots of trouble!
Here is what my small application does.
index.jsp -> servlet -> result.jsp
1. I get values (say, no: of products) from index.jsp page.
2. The servlet creates a connection with a DB table to update the no: of products. Database is updated.
3. In result.jsp I would like to print the products, their quantity and the cost (no: of products selected * cost of each product)
My problem is with 3rd task.
I was successful in creating Connection object as a session attribute in servlet. Then I used scriptlets to obtain the connection object in jsp page.
This model is no more used. What is the appropriate way to use DB connections in JSP?
My friend says you could pull all data from DB in servlet and use that data in a attribute to be accessed in a JSP. But when I google, i found an example where they create a whole new connection within the JSP page itself and print values from table using JSTL.
Please suggest me the appropriate JDBC model to be used.
There isn't an appropriate way of updating a database from a JSP, not in 2011 anyway. Sure, you can find examples of anything on the internet, but it just isn't a good practice any more.
And neither is using a database connection per session, which is what you did when you put a connection into your session.
So here's what you should do. You want your JSP to output a list of product data, where product data comprises something like description, quantity, and cost? Then first create a Product bean which has those three things as properties. Second, your JDBC processing should create a List of Product objects; an ArrayList would be suitable. Put that List into request scope and then forward to the JSP.
Then your JSP would use <c:forEach> to iterate through the List and it would use the EL to extract the properties from each of the beans and output them. Rough example: