When trying to pass a table built with HTML in my servlet like that:
response.setContentType("text/html" );
PrintWriter out = response.getWriter();
out.println("<html>" );
out.println("<head>" );
out.println("<title>Imput OPC</title>" );
out.println("</head>" );
out.println("<body>" );
...
and then
response.sendRedirect("/xxx.jsp" );
But I did not found any table in the JSP.
A friend told me to use a Bean but how can i catch values from the form ( because I have a treatement with the form before constructing table)in a bean. I must use a servlet for that. So what I want is exactly to construct in the response a table then send it to jsp knowing that: .sendRedirect and
getServletContext().getRequestDispatcher("/xxx.jsp").forward(request, response);
gives nothing at all.
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
IllegalStateExceptionin 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 usingRequestDispatcher#forward()and iterate over the list of items using JSTLc:forEachtag (to install JSTL, just drop jstl-1.2.jar in/WEB-INF/lib).Basic kickoff example:
where
/WEB-INF/result.jsplook like this: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.