从Servlet内的数据库返回列表



我试图从数据库中返回一个列表,但没有JSTL,而是通过这种方式(在servlet中添加一些html。这是我的学校任务(。这是我的代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Connection conexao = (Connection) new ConexaoFactory().getConnection();
Cliente cliente = new Cliente();
PreparedStatement estrutura = conexao
.prepareStatement("SELECT * FROM TB_MOVTIN_CLIENTE");

ResultSet resultadoDados = estrutura.executeQuery();
while(resultadoDados.next()) {
cliente.setId(resultadoDados.getInt("ID_CLIENTE"));
cliente.setNome(resultadoDados.getString("NOME"));
request.setAttribute("message",
"<h1>Retorno da seleção</h1>" 
+ "<table border=1> "
+ "<tr> "
+ "<td>Identificação</td>"
+ "<td>Nome</td> " 
+ "</tr>" 
+ "<tr> "
+ "<td>" + cliente.getId() + "</td>" 
+ "<td>" + cliente.getNome() + "</td>" 
+ " </tr> </table>");
}
resultadoDados.close();
estrutura.close();
} catch (SQLException e) {
System.out.print("Erro: ");
e.printStackTrace();
}
RequestDispatcher dispatcher = request.getRequestDispatcher("selecionaCliente.jsp");
dispatcher.forward(request, response);
}

你应该更具体地回答这个问题
1.如果您需要创建列表:为了返回列表,您应该提前创建客户端列表。在while循环中,首先初始化一个新的Cliente对象,然后使用set方法设置该对象的属性。最后将最近创建的对象添加到列表中
2.如果不是:请使用PrintWriter替换request.setAttribute。你可以在这里查找的示例

final PrintWriter writerA = response.getWriter();
writerA.println("A1");

最新更新