Load data from a list of a method in the servlet

0

Good afternoon person! I have this method in the servlet that returns a list of values. How do I load the values it has with jquery?

@WebServlet({"/ControleMovEstoque","/template/buscaMaterialExist.html","/template/cadEntradaEstq.html"})
public class ControleMovEstoque extends HttpServlet {
    private static final long serialVersionUID = 1L;


protected void verificaExistencia(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try{

        String codigo = request.getParameter("codigo");
        String query = "select M from MovimentacaoEstoque M where M.codigo = " + codigo;
        List<MovimentacaoEstoque> listamovestoque = new MovimentacaoDao().existCadastrado(query);

        if (new MovimentacaoDao().existCadastrado(query).isEmpty()){
            request.setAttribute("modalEntrada", "<Strong>Este produto não está cadastrado no estoque</strong>");
        }
        else{
            request.setAttribute("modalEntrada", listamovestoque);
        }


    }catch(Exception e){
        e.printStackTrace();
    }

I have a Modal window that already pays some values with html jquery:

<td><a href="entradaMateriais"
    class="btn btn-xs btn-info entradaMateriais"
    data-toggle="modal" data-id="${list.id_material }" >Entrada</a> </td>

The jquery:

$(".entradaMateriais").on('click', function(){
            var id = $(this).data('id'); $("#fid").val(id);

            var nome =      $('#nome' + id).text();     $("#fnome").val(nome);
            var codigo =    $('#codigo' + id).text();       $("#fcodigo").val(codigo);
            var categoria = $('#categoria' + id).text();   $("#fcategoria").val(categoria);

            $("#entradaMateriais").modal();
        });

In the screen below, I can already load what I have in the html, just missing the information, marked in red, that I want to get from the servlet.

Thanks for the help:)

    
asked by anonymous 31.03.2017 / 21:40

1 answer

2

I'll try to help you. To solve your problem, let's unravel in small problems:

  • Identify what you want to return
  • Identify which format you will return
  • Create logic for return
  • Treat in JavaScript
  • IDENTIFY WHAT YOU WANT TO RETURN

    First, it's not present in your code if you're actually exiting from servlet to somewhere. You can not identify your HttpServletResponse object by sending a .redirect() or .getWriter().print() . You also can not identify if you are giving .getRequestDispatcher().forward() to your HttpServletRequest object.

    Let's assume from now on that you have decided to send the return via object HttpServletResponse (It is much more logical and convenient to use this object, since you are working with AJAX requests and do not want to reload a whole page)

    If code would look something like this:

    protected void verificaExistencia(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      try{
        String codigo = request.getParameter("codigo");
        String query = "select M from MovimentacaoEstoque M where M.codigo = " + 
          codigo;
        List<MovimentacaoEstoque> listamovestoque = new 
          MovimentacaoDao().existCadastrado(query);
        String retorno;
        if (listamovestoque.isEmpty()){
          retorno = "Produto não cadastrado";
        } else{
          retorno = "ok";
        }    
     } catch(Exception e){
        e.printStackTrace();
     }
     /*Lógica para realizar o retorno*/
    

    Note that you were also running DAO twice. One to pick up the Move list and another check to see if it was empty. You do not need to do this, just check using the List object.

    Well, now that you know (or not) if you have a move list, let's go to step 2.

    IDENTIFY WHAT FORMAT YOU WILL RETURN

    Just one word, JSON . Of course, you can decide which format best fits your requirements, but I'll give you JSON (almost) will always work for everything. It's lightweight, easy to manipulate, and you can deal with JavaScript with a single line of code.

    Let's assume you're going to return in JSON . We'll use a Google lib called GSON . GSON helps you transform your Java Objects into JSON. Dai is very good to be able to return.

    The structure of your JSON will be as follows.

    • MESSAGE
    • CONTENT

    Just these two is enough. So let's go to step 3.

    CREATE LOGIC FOR RETURN

    We will first transform the returned list of the bank into JSON by doing so:

    Gson g = new Gson(); //cria um objeto gson
    JsonObject g = (JsonObject) gson.toJsonTree(listamovestoque); //você terá um json com sua lista de movimentacao de estoque.
    g.addProperty("mensagem", retorno); //adiciona o retorno
    String json = g.toString(); //aqui você tem seu json prontinho pra ser enviado
    

    Just send the return using the .getWriter().print() method of the HttpServletResponse class.

    response.getWriter().print(json);
    

    Our backend ta ready, let's treat it in JavaScript, or step 4.

    TREAT JAVASCRIPT

    I noticed that you are using JQuery so it will be even easier. Let's make our request AJAX to retrieve the data we need.

    $("sua-app/template/buscaMaterialExist.html", {
      data: {id: id},
      success: function(retorno){
        var resposta = retorno;
        console.log(resposta); //aqui terá o retorno do backend
      }
    });
    

    I also noticed that you have some knowledge in JS , so it should be easy to understand this code. You will notice that the response log will be a JavaScript object containing 2 attributes.

    • The first, the backend message, which can be either "ok" or "Product not registered ".
    • The second is an array of objects, where each object moves a backend , which may be empty.

    Now just manipulate this data to put in the fields you want.

    I really hope you can understand the flow. Any questions post in the comments.

        
    11.04.2017 / 00:54