Create a Javabean class which represents each item (row) of the table. Create a DAO class which returns a list of those items using JDBC. Then in the servlet, just put the list of items in the request scope using HttpServletRequest#setAttribute()
, forward the request to a JSP file using RequestDispatcher#forward()
and iterate over the list of items using JSTL (just drop jstl-1.2.jar in /WEB-INF/lib
) c:forEach
tag.
Basic kickoff example:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Item> items = itemDAO.list();
request.setAttribute("items", items); // It's now available as ${items} in EL.
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
}
where result.jsp
look like this:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<table>
<c:forEach items="${items}" var="item">
<tr>
<td>${item.someProperty}</td>
<td>${item.anotherProperty}</td>
</tr>
</c:forEach>
</table>
For more hints and examples you may find this article an useful starting point.
It's a Good Thing that you asked this. Putting presentation logic in a Servlet class is a bad practice. Any of those out.println()
statements inside a Servlet class needs to be eliminated. It belongs in a JSP file.
To go some steps further, you can also use a MVC framework so that you basically end up with only a Javabean class and a JSP file (i.e. the role of the servlet have been taken over by the MVC framework).