Avoid redirecting SERVLET in JSP programming language

0

Good day, the situation is as follows: I have a modal bootstrap window where I insert information into the database (PostgreSQL), this action is done from a botón input and a onclick="valida_envia2()" that are inside the modal

This function is found in the jsp:

function valida_envia2() {

                if (document.f2.producto.value.length === 0) {
                    alert("Ingresar Nombre de Producto")
                    document.f2.producto.focus()
                    return 0;
                }
                if (document.f2.precio.value.length === 0) {
                    alert("Ingresar Precio")
                    document.f2.precio.focus()
                    return 0;
                }

                alert("DATOS GUARDADOS CORRECTAMENTE")

                document.f2.submit();
            }

these data are entered in the following modal :

<div class="container">
                    <div class="modal fade" id="myModal" role="dialog">
                        <div class="modal-dialog modal-lg">

                            <!-- Modal content-->
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                                    <h4 class="modal-title">Cambio de Costos</h4>
                                </div>
                                <div class="modal-body">
                                    <form name="f2" action="../cCambiocostos" method="POST" accept-charset="ISO-8859-1">
                                        <fieldset>

                                            <fieldset>

                                                <center>
                                                    <table width="800">

                                                        <tr>
                                                            <td colspan="2">
                                                                <br><br><label>Producto</label>
                                                                <br><input type="text" name="producto" id="producto" class="input" value="" size="30"/>
                                                            </td>
                                                            <td colspan="2">
                                                                <br><br><label>Precio con Descuento</label>
                                                                <br><input type="text" name="preciodes" id="preciodes" value=" " size="15">
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td>
                                                                <br><br><label>Precio</label>
                                                                <br><input type="text" name="precio" id="precio" value="" size="15">
                                                            </td>
                                                            <td>
                                                                <br><br><label>% Desc. 1</label>
                                                                <br><input type="text" name="des_uno" id=" des_uno" value="" size="15"> 
                                                            </td>
                                                            <td>
                                                                <br><br><label>% Desc. 2</label>
                                                                <br><input type="text" name="des_dos" id=" des_dos" value="" size="15"> 
                                                            </td>
                                                            <td>
                                                                <br><br><label>% Desc. 3</label>
                                                                <br><input type="text" name="des_tres" id=" des_tres" value="" size="15"> 
                                                            </td>
                                                        </tr>

                                                        <tr>
                                                            <td colspan="2" align="center">
                                                                <br><br><input type="button" value="Guardar" onclick="valida_envia2()">
                                                            </td>
                                                            <td colspan="2" align="center">
                                                                <br><br><input type="button" value="Cancelar">
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </center>
                                            </fieldset>
                                        </fieldset>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                </div>
                            </div>

                        </div>
                    </div>

                </div>




<div class="container">

                    <div class="modal fade" id="myModal1" role="dialog">
                        <div class="modal-dialog modal-lg">

                            <!-- Modal content-->
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                                    <h4 class="modal-title">Modal Header</h4>
                                </div>
                                <div class="modal-body">
                                    <form name="f2" action="../cCambiocostos" method="POST" accept-charset="ISO-8859-1">
                                        <fieldset>
                                            <%
                                                modelo.cambioC cCosto = (modelo.cambioC) session.getAttribute("cambioCost");
                                                String nombrePro = cCosto.getNombre();
                                                String precios = String.valueOf(cCosto.getPrecio());
                                                String desc_uno = String.valueOf(cCosto.getDes_uno());
                                                String desc_dos = String.valueOf(cCosto.getDes_dos());
                                                String desc_tres = String.valueOf(cCosto.getDes_tres());
                                                String PreCDes = String.valueOf(cCosto.getPrecioCDes());
                                            %>
                                            <fieldset>
                                                <legend>Cambio de Costos</legend>
                                                <center>
                                                    <table width="800">

                                                        <tr>
                                                            <td colspan="2">
                                                                <br><br><label>Producto</label>
                                                                <br><input type="text" name="producto" id="producto" class="input" value="<%=nombrePro%>" size="30"/>
                                                            </td>
                                                            <td colspan="2">
                                                                <br><br><label>Precio con Descuento</label>
                                                                <br><input type="text" name="preciodes" id="preciodes" value="<%=PreCDes%>" size="15">
                                                            </td>
                                                        </tr>
                                                        <tr>

                                                            <td>
                                                                <br><br><label>Precio</label>
                                                                <br><input type="text" name="precio" id="precio" value="<%=precios%>" size="15" >
                                                            </td>
                                                            <td>
                                                                <br><br><label>% Desc. 1</label>
                                                                <br><input type="text" name="des_uno" id=" des_uno" value="<%=desc_uno%>" size="15"> 
                                                            </td>
                                                            <td>
                                                                <br><br><label>% Desc. 2</label>
                                                                <br><input type="text" name="des_dos" id=" des_dos" value="<%=desc_dos%>" size="15"> 
                                                            </td>
                                                            <td>
                                                                <br><br><label>% Desc. 3</label>
                                                                <br><input type="text" name="des_tres" id=" des_tres" value="<%=desc_tres%>" size="15"> 
                                                            </td>
                                                        </tr>

                                                    </table>
                                                </center>
                                            </fieldset>
                                        </fieldset>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                </div>
                            </div>

                        </div>
                    </div>

                </div>

the programming model is MVC therefore I have a model and controller:

MODEL:

package modelo;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

/**
 *
 * @
 */
public class mCambiocostos {

    int idCambiocostos;
    String nombreproducto;
    double precio;
    double descuentounopro;
    double descuentodospro;
    double descuentotrespro;
    double preciocdes;

    public mCambiocostos() {

    }

    public static int getIdCambiocostos() {
        int claveCambCost = 0;
        try {
            modelo.conexion obj1 = new modelo.conexion();
            Connection conexion = obj1.conection();
            Statement st = conexion.createStatement();

            ResultSet rs = st.executeQuery("select ultimoregistrotcambiocosto();");

            while (rs.next()) {
                claveCambCost = rs.getInt(1);
            }
            conexion.close();

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

        return claveCambCost;

    }

    public String getNombreproducto() {
        return nombreproducto;
    }

    public void setNombreproducto(String nombreproducto) {
        this.nombreproducto = nombreproducto;
    }

    public double getPrecio() {
        return precio;
    }

    public void setPrecio(double precio) {
        this.precio = precio;
    }

    public double getDescuentounopro() {
        return descuentounopro;
    }

    public void setDescuentounopro(double descuentounopro) {
        this.descuentounopro = descuentounopro;
    }

    public double getDescuentodospro() {
        return descuentodospro;
    }

    public void setDescuentodospro(double descuentodospro) {
        this.descuentodospro = descuentodospro;
    }

    public double getDescuentotrespro() {
        return descuentotrespro;
    }

    public void setDescuentotrespro(double descuentotrespro) {
        this.descuentotrespro = descuentotrespro;
    }

    public double getPreciocdes() {
        return preciocdes;
    }

    public void setPreciocdes(double preciocdes) {
        this.preciocdes = preciocdes;
    }

The following Model is used to perform the operation that calculates the discount percentage.

package modelo;

/**
 *
 * 
 */
public class cambioC {
    String nombre;
    double precio, des_uno, des_dos, des_tres, PrecioCDes;

    public cambioC() {
    }

    public cambioC(String nombre,double precio, double des_uno, double des_dos, double des_tres, double PrecioCDes) {
        this.nombre = nombre;
        this.precio = precio;
        this.des_uno = des_uno;
        this.des_dos = des_dos;
        this.des_tres = des_tres;
        this.PrecioCDes = PrecioCDes;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public double getPrecio() {
        return precio;
    }

    public void setPrecio(double precio) {
        this.precio = precio;
    }

    public double getDes_uno() {
        return des_uno;
    }

    public void setDes_uno(double des_uno) {
        this.des_uno = des_uno;
    }

    public double getDes_dos() {
        return des_dos;
    }

    public void setDes_dos(double des_dos) {
        this.des_dos = des_dos;
    }

    public double getDes_tres() {
        return des_tres;
    }

    public void setDes_tres(double des_tres) {
        this.des_tres = des_tres;
    }

    public double getPrecioCDes() {
        return PrecioCDes;
    }

    public void setPrecioCDes(double PrecioCDes) {
        this.PrecioCDes = PrecioCDes;
    }

}

and finally the SERVLET:

package controlador;

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;
import modelo.cambioC;
import modelo.mCambiocostos;

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

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            int claveCambCost = mCambiocostos.getIdCambiocostos();

            String NombProduc = request.getParameter("producto");

            String opproducto = request.getParameter("producto");
            String claveproduc = modelo.mProducto.getIdProducto(opproducto);

            String Preciopro = request.getParameter("precio");
            double var = Double.parseDouble(Preciopro);

            double var1=0, var2=0, var3=0, PrecioCDes = var;

            String DesUnopro = request.getParameter("des_uno");
            if (DesUnopro.equals("")||DesUnopro.equals("0.0")) {

            } else {
                var1 = Double.parseDouble(DesUnopro);
                PrecioCDes = var - ((var * var1) / 100);
            }

            String DesDospro = request.getParameter("des_dos");

            if (DesDospro.equals("")||DesDospro.equals("0.0")) {

            } else {
                var2 = Double.parseDouble(DesDospro);
                PrecioCDes = PrecioCDes - ((PrecioCDes * var2) / 100);
            }
            String DesTrespro = request.getParameter("des_tres");
            if (DesTrespro.equals("")||DesTrespro.equals("0.0")) {

            } else {
                var3 = Double.parseDouble(DesTrespro);

                PrecioCDes = PrecioCDes - ((PrecioCDes * var3) / 100);
            }

            cambioC Datos = new cambioC();
            Datos.setNombre(opproducto);
            Datos.setPrecio(var);
            Datos.setDes_uno(var1);
            Datos.setDes_dos(var2);
            Datos.setDes_tres(var3);
            Datos.setPrecioCDes(PrecioCDes);
            request.getSession().setAttribute("cambioCost", Datos);
            String consulta = "INSERT INTO cambiocostos(\n"
                    + "            idcamcosto, codigointerno,nombreproducto, preciopro, descuentounopro, descuentodospro, descuentotrespro, preciocondescuento)\n"
                    + "    VALUES (" + claveCambCost + ",'" + claveproduc + "','" + NombProduc + "'," + var + "," + var1 + "," + var2 + "," + var3 + "," + PrecioCDes + ")";

            modelo.conexion obj1 = new modelo.conexion();
            obj1.registro(consulta);
            response.sendRedirect("Compras/cambiodecosto.jsp");
        }
    }

This code already allows me to enter the information to the database now I need help to send me to the next modal that sees the code and then prevent the servlet redirecting me to another jsp. (do not perform another action servlet , JSP programming language)

I do not know if this is important, but I have to mention that this modal is generated by means of a button that is inside a table

function add () {

            cont++;
            var fila = '<tr class="selected" id="fila' + cont + '"onclick="seleccionar(this.id) "><div id="contenido" ><form><td><input type="text" name="codigointerno[]" id="codigointerno' + cont + '" size="10" readonly="true" disabled="true"/></td>';
            fila += '<td><input type="text" name="producto[]" id="producto' + cont + '" size="30" onchange="combodetallecompra(' + cont + ')"/></td>'
            fila += '<td><select name="presentacion[]" id="presentacion' + cont + '">';
            fila += sel_tipopresentacion;
            fila += '< /select></td>';
            fila += '<td><input name="Costo_ult_compra[]" id="Costo_ult_compra' + cont + '"/></td><td><input name="Costo_prome[]" id="Costo_prome' + cont + '"/></td>';
            fila += '<td><input type="text" name="Costo_lis[]" id="Costo_lis' + cont + '" size="20"/></td><td><input type="text" name="Cantidad_Ord[]" id="Cantidad_Ord' + cont + '"></td>';
            fila += '<td> <input type="text" name="Unidad_grat[]"  id="Unidad_grat' + cont + '" size="10"/></td><td><input type="text" name="costo_sin_iva[]"  id="costo_sin_iva' + cont + '" size="10" disabled="true"/></td>';
            fila += '<td> <input type="text" name="Total_rec[]" id="Total_rec' + cont + '" size="10" disabled="true"/></td>';
            fila += '<td> <input type="text" name="Importe_bruto[]" id="Importe_bruto' + cont + '" size="10" disabled="true"/></td>';
            fila += '<td><input type="text" name="Importe_iva[]" id="Importe_iva' + cont + '" class="input" size="10" disabled="true"/></td>';
            fila += '<td><input type="text" name="Importe_total[]" id="Importe_total ' + cont + '" size="8" disabled="true"/></td>\n\n'
            fila += '<td><button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Costo</button></td></form></div></tr>';
            $('#tablaordcomp').append(fila);
        }  

and effectively when sending the submit () the servlet immediately requests a view, so I require that only the modal be closed and continue within that table.

    
asked by Jazz 03.03.2017 в 18:56
source

4 answers

0

GOOD DAY TO ALL THANK HIS HELP AND THE SOLUTION TO WHAT I NEEDED WAS THE FOLLOWING:

INSIDE THE TABLE THE BUTTON LINE SHOWN BELOW IS CHANGED

        fila += '<td><button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Costo</button></td></form></div></tr>'; 

BY THE NEXT LINE

        fila += '<td><a href="cambiodecosto.jsp" target="_blank"onClick="window.open(this.href, this.target","width=300,height=400"); return false;> Costos </a></td></form></div></tr>';

THIS IS HOW JSP WORKS INDEPENDENTLY FACILITATING TO PERFORM MORE FUNCTIONS I HOPE THIS IS USEFUL TO SOMEONE ELSE.

GREETINGS AND THANKS AGAIN

    
answered by 14.03.2017 / 18:57
source
0

First of all I have an observation, The first, when you use a form and a .submit (), what it does is redirect to that action of your servlet, consequently what is expected to load a view.

Now I could suggest a couple of things, I'm not sure if it could work hehe, but you could try, after your .submit () for a false return, and that's how you continue the flow.

Second, you could also make your request with Ajax, so it would be easier to avoid redirecting.

Greetings.

    
answered by 03.03.2017 в 19:56
0

Use ajax. You can find the documentation here: link

Your request would look something like this:

$("#idFormulario").submit(function(){
    var data = $(this).serialize(); //O algo así era
    $.ajax({
       url: '/urlDelServlet',
       data: data,
       type: 'POST', //o GET
       error: function() { //En caso que haya error por parte de ajax
          $('#info').html('<p>An error has occurred</p>');
       },
       success: function(data) { //En caso que no lo haya y todo vaya bien
          //data trae la respuesta del servlet. Digamos que en el servlet regresaste un "Ok" si todo se procesó correctamente.
          if(data == "Ok"){
             alert("Todo salió bien, ahora voy a mostrar el otro modal");
             //Cerrar modal 1
             //Poner aquí el código para mostrar el siguiente modal
          } else {
            alert("Algo salió mal en el servlet, no se guardó la info");
          }
       }

    });
});

The only thing that you change in your servlet is to validate if everything went well and return an "Ok" for when it goes well or something else for when it goes wrong. In order to write a response to ajax you need to implement these lines in code instead of your redirect:

 response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(variableDelaRespuestaQueContieneOkUOtraCosa);

If you still have questions you can read this post: link

    
answered by 03.03.2017 в 21:47
0

@Jazz No, the ajax you add in your jsp, you only need to invoke it from the click event of your button, the syntax is like this:

$.ajax({ 
url: 'nombre del servlet', 
type: 'POST', // tambien puede ser de tipo GET, depende de ti
data: {parametro1: valor1, parametro2: valor2}, //si tu método recibe parámetros los pones con esa sintaxis, si no tienes parámetros lo dejas vacío'
success: function( respuesta ){ 
  // Si tu petición se concreto bien, aquí puedes validar tu respuesta o mostrar un mensaje o realizar otra acción 
 }, 
  error: function(error){ // si hubo algún error entra aquí 
 } 
});

and since this is done dynamically (in the background), you can even put some kind of animation in which you run your event.

and even alternatively you can use the following link link

I hope you find it useful.

    
answered by 03.03.2017 в 22:58