redirect to a servlet from an ajax passing values

2

Hello, what I want to do is redirect to a servlet from a jsp using ajax, since I have to send data that are not in the form, but should not be seen in the url colo are mascot, age and the token since the latter expires every so often, so it must be sent to know if it is still valid and if so in the servlet make use of the data written by the user and sent anonymously

This is the code in js

 $("#forma").submit(function () {
                var name = $('#nombre').val();
                var ape = $('#apellido').val();
                $.ajax({
                    url: '/TomarValor',
                    type: 'POST', 
                    data: {nombre: name, apellido: ape, mascota: yuki, edad:22, token:qwerty123}
                });
            });

este es el código html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>submit demo</title>
        <style>
            p {
                margin: 0;
                color: blue;
            }
            div,p {
                margin-left: 10px;
            }
            span {
                color: red;
            }
        </style>
        
    </head>
    <body>

        <p>datos del usuario</p>
        <form id="forma">
            <div>
                <input type="text" id="nombre" placeholder="nombre">
                <input type="text" id="apellido" placeholder="apellido">
                <button type="submit" >enviar</button>
            </div>
        </form>
        <span></span>
        
   
    </body>
</html>

import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

@WebServlet (name="TakeValue", urlPatterns = {"/ TomarValor"}) public class TomarValor extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String nombre = request.getParameter("nombre");
    String apellido = request.getParameter("apellido");
    String edad = request.getParameter("edad");
    String mascota = request.getParameter("mascota");
    String token=request.getParameter("token");
    try (PrintWriter out = response.getWriter()) {

        if(token.equals("qwerty123")){
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Valores por post jquery</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("nombre " + nombre);
        out.println("apellido " + apellido);
        out.println("edad " + edad);
        out.println("mascota " + mascota);
        out.println("</body>");
        out.println("</html>");
        }else{
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Error</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("El token esta mal");
        out.println("<a href='generarToken'>generar nuevo token</a>");
        out.println("</body>");
        out.println("</html>");
        }
    }
}


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    String nombre = request.getParameter("nombre");
    String apellido = request.getParameter("apellido");
    String edad = request.getParameter("edad");
    String mascota = request.getParameter("mascota");
    String token=request.getParameter("token");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        if(token.equals("qwerty123")){
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Valores por post jquery</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("nombre " + nombre);
        out.println("apellido " + apellido);
        out.println("edad " + edad);
        out.println("mascota " + mascota);
        out.println("</body>");
        out.println("</html>");
        }else{
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Error</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("El token esta mal");
        out.println("<a href='generarToken'>generar nuevo token</a>");
        out.println("</body>");
        out.println("</html>");
        }
    }
}

}     @Override     public String getServletInfo () {         return "Short description";     } //

}

    
asked by Emmanuel 14.12.2018 в 19:47
source

2 answers

1

This example was used with spring framework. You just have to adjust the logic to your requirements. This performs the query asynchronously without refining the html completely but the interest part. It also consumes a RESTful type service. The result is a JSON that is subsequently desglozado to fill the fields of a table within the body of html5.

function datos1(pagina){
var ajaxRequest;
var base = "https://localhost:8443/BeautySalon/";

//Identificando el tipo de navegador y ajustando la libreria a usar
if(window.XMLHttpRequest) ajaxRequest = new XMLHttpRequest();
else ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

// Cuando se halla cargado el ajax se activa la funcion
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){ // 4 Peticion finalizada, 200 http ok

        var stringJson = JSON.parse(ajaxRequest.responseText);          
        var tablaLocales = document.getElementById("localesUsuario");
        var filasTotales = tablaLocales.rows.length;

        // Borrando todo el contenido de la tabla
        for(var fila=1; fila < filasTotales; fila++){               
            tablaLocales.deleteRow(-1); // borrando desde la ultima fila
        }

        // Recorriendo el JSON
        for(var i in stringJson){ // Recorriendo por bloque JSON

            // Datos de interes
            var idLocal = stringJson[i].local.idLocal,
                foto = stringJson[i].local.imagen,
                nombreLocal = stringJson[i].local.empresa,
                personal = stringJson[i].personal,
                direccion = stringJson[i].local.direccion;
            // Estructura Tabla
            var row = tablaLocales.insertRow(-1),
                celdaIdLocal = row.insertCell(0),
                celdaFotoyNombre = row.insertCell(1),
                celdaPersonal = row.insertCell(2),
                celdaDireccion = row.insertCell(3);

                // Agregando informacion
                celdaIdLocal.innerHTML = idLocal;
                celdaFotoyNombre.innerHTML = "<img src=\""+foto+"\" width=\"50\" height=\"50\" style=\"vertical-align:middle\"/>\n"+
                                  "&nbsp;&nbsp;\n"+
                                  "<span>"+nombreLocal+"</span>";
                celdaPersonal.innerHTML = personal;
                celdaDireccion.innerHTML = direccion;

        }


    }
}

// Creando una peticion GET hacia una URL destino de forma asincrona
ajaxRequest.open("GET",base+"admin/dashboard/recargar/locales?paginaNro="+pagina, true);


// Enviando la peticion
ajaxRequest.send();

   }
    
answered by 15.12.2018 в 02:58
0

It seems to me that there are a couple of things that need to be clarified so that you can solve your question:

1) If you submit the form, the page is refreshed by loading the html that the servlet answers.

2) If you make the ajax call, the html returned by the servlet is received in a variable inside the javascript and you must manipulate the DOM to replace the existing html with the one received (there is no update of the page)

3) Additional pet, age, and token fields can be sent in the form as <input type="hidden"> , or the first and last name fields can be sent in the ajax as two attributes in the data field.

4) If the choice to send the ajax is so that the fields do not come out in the url, you are basing the decision on an incorrect premise. Whether the data goes in the url or in the body depends on the method of the call. That is, if you make a POST with either the form or with ajax, the fields will travel in the body and not in the url. The inverse is also valid if you use the GET method. In this case, either with a form or with ajax, the fields are added to the URL. (In your example, the method was not set, so it defaulted to GET )

5) In <input> the attribute name is the one that defines the name with which the servlet can find the parameter. This attribute was missing in nombre as in apellido so the servlet should not be able to raise that data.

Because you have armed the servlet that returns html (vs returning only data) it seems to me that what you really want is to send the form with the hidden fields and method POST .

<form id="forma" method="POST" action="/TomarValor">
     <div>
        <input type="text" id="nombre" name="nombre" placeholder="nombre">
        <input type="text" id="apellido" name="apellido" placeholder="apellido">
        <input type="hidden" id=mascota name="mascota" value="yuki" />
        <input type="hidden" id="edad" name="edad" value="22"/>
        <input type="hidden" id="token" name="token" value="qwerty123" />
        <button type="submit" >enviar</button>
     </div>
  </form>
    
answered by 15.12.2018 в 14:58