How to send HttpServletResponse in the PrintWriter

2020-08-05 11:26发布

问题:

I am trying to send a table in html code to a jsp using

response.setContentType("text/html");  
PrintWriter out = response.getWriter();
out.println("<html>").....

then using response.sendRedirect(jsp name) to send the table to the jsp;

But this is never worked with me and I have a doubt that the printwriter has a specific manipulation with servlet jsp communication.

Update: So to be more clear In one JSP I have various parameter wich I send all of them to a servlet. This one; the servlet build a table with all those parameter that catched with request.getParameter. when The html table is built with out.println 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>"); 
    out.println("<table border=1>"); 
 .
     .
     .
out.println("</body>");
out.println("</html>");

so I'd like to send this result:the html table to display into an other jsp

回答1:

It doesn't work that way. The HTML should be inside the JSP, not inside the Servlet. Repeat me: template text (HTML/CSS/JS) belongs in JSP and Java code belongs in Java classes (to start with a Servlet).

All the servlet need to do is to do the business job and put the data of interest in a suitable scope (request scope?) and finally forward the request to the JSP page and then use taglibs in JSP to control the page flow and use EL to access backend data.

E.g. the following in a doGet():

List<Person> persons = personDAO.list();
request.setAttribute("persons", persons); // This way it's accessible in JSP by ${persons}
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);

with the following in persons.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

...

<table>
    <c:forEach items="${persons}" var="person">
        <tr>
            <td>${person.name}</td>
            <td>${person.email}</td>
            <td>${person.age}</td>
        </tr>
    </c:forEach>
</table>

The c:forEach is part of JSTL. If it's not available in your environment, you can install it by simply dropping jstl-1.2.jar in /WEB-INF/lib folder (assuming you're using Servlet 2.5 container).



标签: servlets