I am accessing a db in a servlet and want to display all the rows of a table in a jsp, to divide the presentation from the logic. Essentially I want to pass an object (ResultSet rs) from the servlet to the jsp, so within the jsp I can call something like: < tr> while(rs.next()) < td>< %=Record.firstfield%>< /td> < td>< %=Record.secondfield>< /td> < /tr>
I am unclear on the use of a directive (syntax < @ page...%> to import the needed packages as well as the classes and objects (like the ResultSet) instantiated in a separate servlet held in the same container. I corrected the table stuff to prevent display problems.
[This message has been edited by Carl Trusiak (edited December 12, 2001).]
The real Question is how to import a package in Jsp and how to pass an Object from a Controller servlet to the Jsp it forwards to right? To import a package or class is easy, You have to have the following statement before any use of the class or package you need: < %@page import="java.sql.*" %> or < %@page import="java.sql.ResultSet" %> Any object you want to pass from a controller servlet to a JSP page it forwards to can be placed in the HttpServletRequest Object as an attribute. In your servlet : request.setAttribute("rs", rs); To obtain it in your JSP its < % ResultSet rs = (ResultSet)request.getAttribute("rs"); %> And there you have it. I think you need to rethink this a little. Trying to maintain a ResultSet seperate from the Connection Object that created it can have Huge problems. If the Connection is closed before you use it, the ResultSet is invalid! If the Connection is reused by another process before you use it, the ResultSet is invalid! This exception will seemingly be random in a multi-user environment. Map a Java Object to the results you want off the ResultSet and return an array of these object to the JSP page the exact same way I show for a ResultSet.
Actually,getting the ResultSet onto ur jsp page is a very very bad way of programming,what i would suggest is that u could try using two vectors in ur bean,do all the database related Queries in the bean itself and put the values of the resultSet into the bean vectors,use these vectors to display onto the jsp page, u could also use Hashtable if required. As u wish u can try doing it,but preferrably try not to pull the ResultSet onto ur jsp page.Make life easy for the guys who are gonna do the maintanance of ur code man .
subject: newbie: passing an object from a servlet to a jsp