【问题标题】:Return a List from database within a Servlet从 Servlet 中的数据库返回列表
【发布时间】:2020-10-06 00:13:01
【问题描述】:

我正在尝试从我的数据库中返回一个列表,但没有 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);
    }

【问题讨论】:

    标签: sql list jsp servlets oracle-sqldeveloper


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-11-29
      • 2021-10-13
      • 1970-01-01
      • 2018-10-11
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多