Load data from a method list to Servlet

Asked

Viewed 815 times

0

Good afternoon people! I have this method in 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();
        });

On the screen below, I can already load what I have in html, only missing the information, marked in red, I want to take from Servlet.

inserir a descrição da imagem aqui

Thanks for the help :)

1 answer

2


I’ll try to help you. To solve your problem, let’s unblock into small problems:

  1. Identify what you want to return
  2. Identify which format you will return
  3. Create the logic for return
  4. Handle in Javascript

IDENTIFY WHAT YOU WANT TO RETURN

First of all, it’s not present in your code if you’re actually leaving the servlet somewhere. You can’t identify your object HttpServletResponse sending a .redirect() or .getWriter().print(). Also not able to identify if you’re giving a .getRequestDispatcher().forward() with your object HttpServletRequest.

Let’s assume from now on that you decided to send the return via object HttpServletResponse (It is much more logical and convenient to use this object since you are working with requests AJAX and do not want to reload a full 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 the DAO twice. Once to get the Moveable list and once to check if it was empty. No need to do this, just check using the List object.

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

IDENTIFY WHICH FORMAT YOU WILL RETURN

Just a word, JSON. Of course you can decide which format best suits your requirements, but I can tell 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’ll return in JSON. We will use a Google lib call GSON. A lib GSON helps you to transform your Java objects into JSON. Dai is very easy 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 turn the returned list of the bank into JSON 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 method .getWriter().print() class HttpServletResponse.

response.getWriter().print(json);

Our backend ta ready, let’s go to the treatment in Javascript, or step 4.

TREAT IN JAVASCRIPT

I noticed you using JQuery then it’ll get easier. Let’s make our requisition AJAX to recover 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, then you should be easy to understand that code. You will notice that the answer log will be an object Javascript containing 2 attributes.

  • The first, the message from backend, which can be "ok" or "Product unregistered".
  • The second is a array of objects, where each object a movement of equal stock of backend, that may be empty.

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

I hope very much that you can understand the flow. Any doubt post in the comments.

Browser other questions tagged

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