A redirect let the client fire a new request. It trashes the current request and response you're working on. You get a fresh new request and response on the specified URL. You don't want to send a redirect whenever you want to pass request scoped information from servlet to JSP. Use a forward instead.
Printing HTML in a servlet is a big no-no. You should also not write something to the response body whenever you want to forward the request to a JSP later. You would face an IllegalStateException
in the server logs (and indeed a blank page in the webbrowser). Printing HTML is a task which is to be done by JSP, not by servlet.
In a servlet you just need to do the business stuff. E.g. collecting information which is to be displayed in a table. First create a Javabean class which represents each item (row) of the table. Then create a DAO class which returns a list of those items from the datastore (a database?). 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 c:forEach
tag (to install JSTL, just drop jstl-1.2.jar in /WEB-INF/lib
).
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 /WEB-INF/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 those tutorials useful. 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), for example JSF.