How can I pass data retrieved from a database by a servlet to a JSP page?
Created May 4, 2012
Basically, you need to first design a bean which can act as a wrapper for storing the resultset returned by the database query within the servlet. Once the bean has been instantiated and initialized by invoking its setter methods by the servlet, it can be placed within the request object and forwarded to a display JSP page as follows:
com.foo.dbBean bean = new com.foo.dbBean(); //call setters to initialize bean req.setAttribute("dbBean", bean); url="..."; //relative url for display jsp page ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(req, res);
The bean can then be accessed within the JSP page via the useBean tag as:
<jsp:useBean id="dbBean" class="com.foo.dbBean" scope="request"/> ... <% //iterate through the rows within dbBean and //access the values using a scriptlet %>
Also, it is best to design your application such that you avoid placing beans into the session unless absolutely necessary. Placing large objects within the session imposes a heavy burden on the performance of the servlet engine. Of course, there may be additional design considerations to take care of - especially if your servlets are running under a clustered or fault-tolerant architecture.