jsp, servlets and jstl

1

I have a question about the use of jstl.

In my project I'm using jstl, based on an example I found in the cloud. But I was surprised that it does not work properly for me, so I ask for your support.

The problem is that the list I send from my servlet through a request.setAttribute to my jsp, is not captured by my jstl or I do not really know what it can be.

Here is what I have implemented so that you have an idea of what I am talking about.

The post of my servlet

 private static String Factores = "/frmFactores.jsp";
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String forward="";
        String action = request.getParameter("action");
        List<Factor> factores = RiesgosNeg.Instancia().ListarFactores();
        if (action.equalsIgnoreCase("delete")){
            int userId = Integer.parseInt(request.getParameter("userId"));
            // dao.deleteUser(userId);
            forward = Factores;
            request.setAttribute("factores",factores);
        } else if (action.equalsIgnoreCase("edit")){
            //forward = INSERT_OR_EDIT;
            //int userId = Integer.parseInt(request.getParameter("userId"));
            //User user = dao.getUserById(userId);
            request.setAttribute("factores", factores);
        } else if (action.equalsIgnoreCase("listFactor")){
            forward = Factores;
            request.setAttribute("factores",factores);
        } else {
            request.setAttribute("factores",factores);
        }

        RequestDispatcher view = request.getRequestDispatcher(forward);
        view.forward(request, response);
    } catch (Exception ex) {
        ex.getMessage();
    }
}

The jsp

<c:if test="${!empty factores}">
    <c:forEach items="${factores}" var="f">
        <tr>                                          
            <td class="text-center"><c:out value="${f.Descripcion}"/></td>
            <td class="text-center">
                <c:choose>
                    <c:when test="${f.estado == 1}" >
                        <!-- <input type="checkbox" checked="checked" disabled="disabled"> -->
                        <i class="fa fa-check-square-o"></i>
                    </c:when>
                    <c:otherwise>
                        <!-- <input type="checkbox" disabled="disabled"> -->
                        <i class="fa fa-square-o"></i>
                    </c:otherwise>
                </c:choose>
            </td>
            <td class="text-center" data-id="<c:out value="${f.codigo}"/>">
                <a href="javascript:;" class="btn btn-primary btn-circle edit" title="Editar"><i class="fa fa-edit"></i></a>
                <a href="javascript:;" class="btn btn-danger btn-circle remove" title="Eliminar"><i class="fa fa-remove"></i></a>
            </td>
        </tr>
    </c:forEach>
</c:if>

My js where I call the servlet to call my servlet from the moment I select my page

$(window).load(function () {
    // Si en vez de por post lo queremos hacer por get, cambiamos el $.post por $.get
    $.post('../sRiesgos', {
        action: 'listFactor'
    }, function (responseText) {
        // $('#tblFactores').html(responseText);
    }); });
    
asked by Cesar David Guerrero Hidalgo 29.08.2016 в 09:00
source

2 answers

0

Well when reading your comments, which I appreciate a lot =). And doing some research next to my precious cup of coffee. I found a way to do my jsp with ajax, unfortunately I could not use the jstl = (.

My jsp:

<table class="table table-striped table-bordered table-hover" id="tblFactores">
                        <button type="button" class="btn btn-primary" name="btnAdd" id="btnAdd"> Agregar</button>                            
                        <thead>
                            <tr>                                    
                                <th>Factor</th>                                    
                                <th>Estado</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>

                      <tbody>

                        <%
                            List<Factor> listafactores = FactorNEG.Instancia().Listar();

                            for (int i = 0; i < listafactores.size(); i++) 
                            {
                                int tipo = listafactores.get(i).getCodigo();
                                out.println("<tr>");
                                out.println("<td class='text-center'>" + listafactores.get(i).getDescripcion() + "</td>");
                                if (listafactores.get(i).getEstado()== 1) {
                                    out.println("<td class='text-center'><i class='fa fa-check-square-o'></i></td>");
                                } else {
                                    out.println("<td class='text-center'><i class='fa fa-square-o'></i></td>");
                                }
                               %> 
                         <td class="text-center" data-id="<%=listafactores.get(i).getCodigo()%>" >


                        <a href="javascript:;" class="btn btn-primary btn-circle edit" title="Editar"><i class="fa fa-edit"></i></a>
                        <a href="javascript:;" class="btn btn-danger btn-circle remove " title="Eliminar"><i class="fa fa-remove"></i></a>

                        </td>
                        </tr>
                        <%
                                 }
                                 %>
                          </tbody>  

                    </table>

My servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
           String action = request.getParameter("action"); 
           Factor f = new Factor();
        if (action.equalsIgnoreCase("registrar")) {
           // Factor f = new Factor();
            f.setCodigo(Integer.parseInt(request.getParameter("codigo")));
            f.setDescripcion(request.getParameter("descripcion"));
            f.setEstado(Integer.parseInt(request.getParameter("estado")));
            int valor = FactorNEG.Instancia().Registrar(f);

            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-cache");
            Map<String, String> data = new HashMap<String, String>();
            data.put("codigo",String.valueOf(valor));
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(data);
            response.getWriter().write(json);
        }
        if(action.equalsIgnoreCase("delete"))
        {
            f.setCodigo(Integer.parseInt(request.getParameter("codigo")));

            Boolean respuesta =  FactorNEG.Instancia().delete(f.getCodigo());
            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-cache");
            Map<String, String> data = new HashMap<String, String>();
            data.put("codigo",String.valueOf(respuesta));
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(data);
            response.getWriter().write(json);
        }

    } catch (Exception ex) {
        Logger.getLogger(sFactor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

my jsFactor

var oTable;
$(function () {
oTable = fn_iniciarDT(oTable, "tblFactores");
$("#btnAdd").on("click", function () {
    fn_Add();
});
oTable.on("click", ".edit", function () {
    fn_Edit(this);
});

oTable.on("click", ".save", function () {
    fn_save(this);
});

oTable.on("click", ".remove", function () {
    var elem = this;
    bootbox.confirm("\u00BFEst\u00e1 seguro de eliminar esta factor?\u003F",    function (result) {
        if (result) {
            oTable.fnDestroy();
            fn_Delete(elem);
        }
    });

});
oTable.on("click", ".cancel", function () {
    fn_Cancel(this);
});
});
function fn_Add() {
$("#tblFactores tbody").prepend("<tr>" +
        "<td><input type='text' class='form-upload input-sm' style='width: 100%'/></td>" +
        "<td class='text-center'><input type='checkbox' checked='checked'/></td>" +
        "<td class='text-center'>" +
        "<a class='btn btn-info btn-circle save' href='javascript:;' title='Guardar' ><i  class='fa fa-save'></i></a>" +
        "<a class='btn btn-danger btn-circle cancel' href='javascript:;' title='Cancelar' ><i class='fa fa-ban'></i></a>" +
        "</td></tr>");
};
var fn_save = function (elem) {
var par = $(elem).parent().parent();
var tdnombre_factor = par.children("td:nth-child(1)");
var tdestado = par.children("td:nth-child(2)");
var tdbuttons = par.children("td:nth-child(3)");
var id_codigo = tdbuttons.attr('data-id') === undefined ? 0 :tdbuttons.attr('data-id');

var data = {'codigo': id_codigo, 'descripcion': tdnombre_factor.children("input[type=text]").val(),
    'estado': tdestado.children("input[type=checkbox]").is(":checked") ? 1 : 0
};
var success = function (res) {
    if (res.codigo > 0)
    {
        tdnombre_factor.html(tdnombre_factor.children("input[type=text]").val());
        tdestado.html(res.estado === 1 ? '<i class="fa fa-check-square-o"></i>' : '<i class="fa fa-square-o"></i>');
        tdbuttons.html('<a class="btn btn-primary btn-circle edit"><i class="fa fa-edit"></i></a><a class="btn btn-danger btn-circle remove"><i class="fa fa-remove"></i></a>');
        tdbuttons.attr("data-id", res.codigo);
    }
 };
var error = function () {

    alert("error");
};
console.log(data);
fn_callmethod(base_url + "../sFactor?action=registrar", data, success, error);
};

var fn_Delete = function (elem) {

var codigo = $(elem).parent().attr('data-id') === undefined ? 0 : $(elem).parent().attr('data-id');
if (codigo !== 0) {
    var success = function (res) {
        if (res) {
            var par = $(elem).parent().parent();
            par.remove();
            oTable = fn_iniciarDT(oTable, "tblFactores");
        }
    };
    var error = function () {
    };
    fn_callmethod(base_url + "../sFactor?action=delete", {codigo: codigo}, success, error);
}
};

function fn_Edit(elem) {

var par = $(elem).parent().parent();
var tdnombre_factor = par.children("td:nth-child(1)");
var tdestado = par.children("td:nth-child(2)");
var tdbuttons = par.children("td:nth-child(3)");
var estado;

tdnombre_factor.html("<input type='text' id='txtdescripcion' class='form-control input-sm' style='width: 100%' value='" + tdnombre_factor.html() + "'/>");
estado = tdestado.children("i").hasClass("fa-square-o") ? "<input type='checkbox'/>" : "<input type='checkbox'  checked='checked'/>";
tdestado.html(estado);
tdbuttons.html('<a class="btn btn-primary btn-circle save"><i class="fa fa-save " title="Guardar"></i></a><a class="btn btn-danger btn-circle cancel" title="Cancelar"><i class="fa fa-ban"></i></a>');
}
;
var fn_Cancel = function (elem) {


var par = $(elem).parent().parent();
var tdbuttons = par.children("td:nth-child(3)");
var id = tdbuttons.attr('data-id') === undefined ? 0 : tdbuttons.attr('data-id');

if (id === 0) {
    par.remove();
} else {
    var par = $(elem).parent().parent();
    var tdnombre_factor = par.children("td:nth-child(1)");
    var tdestado = par.children("td:nth-child(2)");

    tdnombre_factor.html(tdnombre_factor.children("input[type=text]").val());
    tdestado.html((tdestado.children("input[type=checkbox]").is(":checked") ? '<i class="fa fa-check-square-o"></i>' : '<i class="fa fa-square-o"></i>'));
    tdbuttons.html('<a class="btn btn-primary btn-circle edit"><i class="fa fa-edit"></i></a><a class="btn btn-danger btn-circle remove"><i class="fa fa-remove"></i></a>');
}
};

services js:

var fn_callmethod = function(url, data, success, error) {
$.ajax({
    type: "POST",
    url: url,
    data: data,
    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    dataType: "json",
    success: success,
    error: error
});
};
var fn_callmethod_get = function(url, data, success, error) {
$.ajax({
    type: "GET",
    url: url,
    data: data,
    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    dataType: "json",
    success: success,
    error: error
});
};
function combo(url, id) {
$.ajax({
    type: "GET",
    url: base_url + url,
    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    dataType: "json",
    success: function(data) {
        var option = "<option value='0'>----Seleccione----</option>";
        var tam = data.length;
        $("#" + id).append(option);
        for (var i = 0; i < tam; i++)
        {
            var option = $(document.createElement('option'));
            option.text(data[i].Descripcion);
            option.val(data[i].Codigo);
            $("#" + id).append(option);
        }
    }
});
}
var fn_iniciarDT = function(oTable, idtable) {
oTable = $("#" + idtable).dataTable({
    "iDisplayLength": 25,
    "aLengthMenu": [[15, 25, 50, 100, -1], [15, 25, 50, 100, "All"]],
    "language": {
        "lengthMenu": "Mostrar _MENU_ registros por p&aacute;gina",
        "zeroRecords": "Nada encontrado - lo siento",
        "info": "Mostrando la p&aacute;gina _PAGE_ de _PAGES_",
        "infoEmpty": "No hay registro disponibles.",
        "infoFiltered": "(Filtrado _MAX_ registros en total)",
        "sSearch": "Buscar:",
        "oPaginate": {
            "sFirst": "Primero",
            "sLast": "Ultimo",
            "sNext": "Siguiente",
            "sPrevious": "Anterior"
        }
    }
});
return oTable;
};

PD:  The only detail that I still can not discover are:

1) how to validate (in the add and edit function I create text boxes and select), the question is how can I validate them.  2) How to know if you send me a succes or error (ie if you pass a cath in my servlet as send it as an error)

    
answered by 05.09.2016 / 10:14
source
0

For you to work what you want to do you need to write in the request session, because as I see in your code the same request you send is the same as you are writing and it will not work because when you finish the request you wrote the values they get lost so you'll have to do something like this:

request.getSession().setAttribute("factores",factores);

Now it should work for you.

In my humble opinion, I think that what you are doing is wrong even if it works for you, simply because you make an AJAX request when you are using JSP.

If you are going to use JSP and JSTL the best you can use is to make a binding between your controller and your JSP so that the variables that you have in your controller are the same that you have exposed in your JSP and you can access natively to them.

If you prefer to use AJAX in your application, it is best to leave JSP aside and switch to frameworks and libraries made for it, such as Angular, Ember, etc.

    
answered by 31.08.2016 в 19:54