top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can I pass data retrieved from a database by a servlet to a JSP page?

+1 vote
414 views
How can I pass data retrieved from a database by a servlet to a JSP page?
posted Nov 18, 2015 by Dominic

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

One of the better approaches for passing data retrieved from a servlet to a JSP is to use the Model 2 architecture as shown below:
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.

answer Nov 19, 2015 by Karthick.c
...