Database result in inputText

Asked

Viewed 100 times

1

I am developing a web application in JSP and would like to take the maximum code of products registered in the database and put in the text field.

<input type="text" name="codigo" id="codigo"/>

But I’m not getting it.

This is my JSP:

  <%

    Connection con = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

    try {
        con = Conecta.conexao();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Produtos.class.getName()).log(Level.SEVERE, null, ex);
    }

    Produtos pro = new Produtos();

    try {

        String sql = "SELECT max(prod_cod) AS prod_cod FROM tb_produtos";
        pst = con.prepareStatement(sql);
        rs = pst.executeQuery();
        if (rs.next()) {
            pro.setProd_codigo(Integer.parseInt(rs.getString("prod_cod")) + 1);

        } else {
            pro.setProd_codigo(1);
        }

    } catch (Exception e) {
        System.out.println("Erro" + e);
    }


%>

<form method="get" action="CadastroProdutos2" >

    <div class="row">
        <div class="col-6 col-md-4"></div>
        <div class="col-6 col-md-4"><h2>Cadastro de Produtos</h2></div>
        <div class="col-6 col-md-4"></div>
    </div>

    <div class="container-fluid">
        <div class="conteudo_cadastro"> 

            <div class="row">

                <div class="col-sm-6 col-md-4">
                    Nome do produto:<input type="text" id="nome_produto2" name="nome_produto"><br/><br/>
                </div>

                <div class="col-sm-6 col-md-4">
                    Descrição:<input type="text" id="descricao" name="descricao"><br/><br/>
                </div>

                <div class="col-sm-6 col-md-4">
                    Valor:<input type="text" id="valor" name="valor"><br/><br/>
                </div>
            </div>

            <div class="row">
                <div class="col-sm-6 col-md-4">
                    Cor:<input type="text" id="cor" name="cor"><br/><br/>
                </div>

                <div class="col-sm-6 col-md-4">
                    Marca:<input type="text" id="marca" name="marca"><br/><br/>
                </div>

                <div class="col-sm-6 col-md-4">
                    Tamanho:<input type="text" id="tamanho" name="tamanho"><br/><br/>

                </div>

                <div class="col-sm-6 col-md-4">
                    Parcelas:<input type="text" id="parcelas" name="parcelas"><br/><br/>

                </div>

                <div class="col-sm-6 col-md-4">
                    Tecido:<input type="text" id="tecido" name="tecido"><br/><br/>

                </div>

                <div class="col-sm-6 col-md-4">
                    Codigo:<input type="text" name="codigo" id="codigo" value="${pro.getProd_codigo()}"/> <br/><br/>

                </div>

                <div class="col-sm-6 col-md-4">
                    <input type="file" name="file" id="file"/> <br/><br/>

                </div>


            </div>
        </div>
    </div>

    <button type="submit">Cadastrar</button> 

</form> 
  • What is the problem ? An exception is being made ?

  • no exception

  • The field is just blank, right ?

  • yes, this totally white

1 answer

1


I’m going to base myself on my answer to your other question.

There are two possible alternatives, to calculate the value of the next code when loading the page or using autoincrement.

Loading the value of the next code

In class ListagemProdutoServlet, let’s change the method doGet to look like this:

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException
    {
        List<Produto> produtos = ProdutoDAO.instancia().listarTodos();
        request.setAttribute("produtos", produtos);

        int proximo = produtos.stream().mapToInt(Produto::getCodigo).max().orElse(0) + 1;
        request.setAttribute("proximo", proximo);

        RequestDispatcher dispatcher = request.getRequestDispatcher("/produtos.jsp");
        dispatcher.forward(request, response);
    }

In JSP, you would use this:

            <div class="col-sm-6 col-md-4">
                Código: <input type="text" name="codigo" id="codigo" value="<c:out ${proximo}" />
            </div>

However, this is not a good approach. If you open the registration/listing screen simultaneously in two tabs in the browser, both get the same code. By saving the first one, everything will go well, but it won’t work when trying to save the second.

The cause of the problem is that you’re putting the product code on JSP for a product that doesn’t even exist yet. The correct one would be to define the code when the product is created. Therefore, I recommend the next approach, based on autoincrement.

Using autoincrement

First, in the database, you set the field prod_cod table tb_produtos as autoincrement.

Then, you delete from your JSP the code field in the registration part.

Then, in your DAO, the method salvar gets like this:

    private static final String INSERT_SQL = "INSERT INTO tb_produtos (prod_nome, prod_desc, prod_valor, prod_marca, prod_tamanho, prod_parcelas, prod_tecido, prod_tipo_imagem, prod_imagem) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

    public void salvar(Produto pro, ImagemProduto im) {
        try (
            Connection con = Conecta.conexao();
            PreparedStatement ps = con.prepareStatement(INSERT_SQL);
        ) {
            ps.setString(1, pro.getNome());
            ps.setString(2, pro.getDescricao());
            ps.setDouble(3, pro.getValor());
            ps.setString(4, pro.getMarca());
            ps.setString(5, pro.getTamanho());
            ps.setInt(6, pro.getParcelas());
            ps.setString(7, pro.getTecido());
            ps.setString(8, im.getFormato());
            ps.setBytes(9, im.getConteudo());
            ps.execute();
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }

And then in class SalvarProdutoServlet, you exchange that line:

    int id = Integer.parseInt(request.getParameter("id"));

That’s why:

    int id = 0; // O id ainda é desconhecido e não foi gerado ainda.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.