0

JSP: submit ignorando input

Estoy realizando un proyecto de Librería con JSP, Servlets, MySQL y Apache Tomcat 8.0 EXCLUSIVAMENTE!

El problema es que tengo un form en un jsp en el cual el submit está ignorando el primer input.

Lo curioso esque me funcionaba perfectamente hasta que hice algún ajuste en la base de datos, pero he revisado todo y parece ok (Quizás se me pase algo?).

Aquí tenéis el jsp. Todo funciona ok, pinta los formularios y se ve todo correcto. Concretamente el input ignorado es <input id="ide" type="text" name="id" value="<%= libro.getIdLibro()%>"disabled>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="javax.servlet.http.HttpSession"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Iterator"%>
<%@page import="model.LibroVO"%>
<%@page import="model.LibroDAO"%>
<%@page import="model.CarritoVO"%>
<%@page import="model.CarritoDAO"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link href="styles.css"
  rel="stylesheet" type="text/css">
<style type="text/css">
    div{
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        width: 100%;
    }

    form{
    width: 50%;
    }
    input{
        float: left;
        margin: 5px;
        width: fit-content; 
    }
</style>
<title>Libros</title>
</head>
<body>
    <div>               

<%

HttpSession sesion;

sesion = request.getSession();

ArrayList<LibroVO> lista;

lista = new ArrayList<LibroVO>();

if(request.getAttribute("listaLibros")!=null){

    lista =(ArrayList<LibroVO>) request.getAttribute("listaLibros");

    sesion.setAttribute("lista", lista);
} else {

    if(sesion.getAttribute("lista")!=null){
    
        lista =(ArrayList<LibroVO>) sesion.getAttribute("lista");
    }
}

    Iterator<LibroVO> itLista = lista.iterator();

    LibroVO libro;

    libro = new LibroVO(); 

    while (itLista.hasNext()) {
    
    
        libro = itLista.next();
        %>
         <form method="POST" action="frontend">
            <label for="ide">ID</label>
            <input id="ide" type="text" name="id" value="<%= libro.getIdLibro()%>" disabled>
            <label for="titulo">Título</label>
            <input id="titulo" type="text" name="titulo" value="<%= libro.getTitulo()%>" disabled>
            <label for="paginas">Número pág.</label>
            <input id="paginas" type="text" name="numPag" value="<%= libro.getNumPag()%>" disabled>
            <label for="edicion">Edición</label>
            <input id="cateediciongoria" type="text" name="edicion" value="<%= libro.getEdicion()%>" disabled>
            <label for="categoria">Categoría</label>
            <input id="categoria" type="text" name="categoria" value="<%= libro.getCategoria()%>" disabled>
            <label for="precio">Precio</label>
            <input id="precio" type="text" name="precio" value="<%= libro.getPrecio()%>" disabled>
            <label for="isbn">ISBN</label>
            <input id="isbn" type="text" name="isbn" value="<%= libro.getIsbn()%>" disabled>
            <label for="cantidad">Cantidad</label>
            <input id="cantidad" type="number" name="cantidad" min="1" max="10"> 
            <input type="submit" name="submit" value="Añadir al carrito">
          </form><br>
<%  
}


%>

        <a href="frontend">Ir al Carrito</a>
    
   </div>
  </body>
</html>

Aquí está el servlet. El cual he revisado 20 veces y no consigo ver porqué el parámetro id es devuelto como null en la request.

package servlets;

import java.io.IOException;

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 javax.servlet.http.HttpSession;

import model.CarritoDAO;
import model.CarritoVO;

@WebServlet("/frontend")
public class SFrontend extends HttpServlet {
private static final long serialVersionUID = 1L;

HttpSession sesion;
CarritoVO carrito;

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

    if (request.getParameter("volver") != null) {

        request.getRequestDispatcher("frontend.jsp").forward(request, response);
    } else {

        request.getRequestDispatcher("carritoCompra.jsp").forward(request, response);

    }
}

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

    sesion = request.getSession();

    int idLibro;
    int idCliente;
    int cantidad;

    idLibro = -1;
    idCliente = -1;
    cantidad = -1;

    if (request.getParameter("id") != null) {
        idLibro = Integer.parseInt(request.getParameter("id"));
    }

    if (request.getParameter("cantidad") != null) {

        System.out.println("cantidad:" + request.getParameter("cantidad"));

        cantidad = Integer.parseInt(request.getParameter("cantidad"));

        sesion.setAttribute("cantidad", cantidad);

        System.out.println("cantidad final:" + cantidad);

    } else {

        request.getRequestDispatcher("frontend.jsp").forward(request, response);
    }

    if (sesion.getAttribute("ClienteId") != null) {

        idCliente = (int) sesion.getAttribute("ClienteId");

    }

    if (CarritoDAO.getIdCarrito(idCliente, idLibro)) {

        cantidad = cantidad + CarritoDAO.getCantidad(idCliente, idLibro);

        CarritoDAO.nuevaCantidad(cantidad, idCliente, idLibro);

    } else {

        System.out.println("cliente" + idCliente + "libro:" + idLibro + "cantidad:" + cantidad);

        int insCarrito = CarritoDAO.insertarCarrito(idCliente, idLibro, cantidad);

        if (insCarrito == 1) {
            System.out.println("Producto añadido a carrito");
        }
    }

    request.getRequestDispatcher("frontend.jsp").forward(request, response);

}

}

Al pulsar cualquiera de los submits generados en el jsp, devuelve este error (He hecho debug y he comprobado que es debido a idLibro que lo manda con valor -1 al modelo).

    java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`libreria`.`carrito`, CONSTRAINT `FK_carrito_libro` FOREIGN KEY (`idLibro`) REFERENCES `libro` (`idLibro`) ON UPDATE CASCADE)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1350)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
at model.CarritoDAO.insertarCarrito(CarritoDAO.java:37)
at servlets.SFrontend.doPost(SFrontend.java:84)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

Como dije al principio, despúes de hacer algún ajuste a la base de datos fue cuando surgió el problema. Así que os dejo los archivos create e insert por si veis algo raro. NOTA: En los insert de la tabla libro faltan algunos datos como el titulo, isbn... Pero los introduje manualmente.

 DROP DATABASE IF EXISTS libreria;
 CREATE DATABASE libreria;

 USE libreria;

  /* TABLAS */

 DROP TABLE IF EXISTS libreria.libro;
 DROP TABLE IF EXISTS libreria.tienda;
 DROP TABLE IF EXISTS libreria.cliente;
 DROP TABLE IF EXISTS libreria.empleado;
 DROP TABLE IF EXISTS libreria.autor;
 DROP TABLE IF EXISTS libreria.direccion;
 DROP TABLE IF EXISTS libreria.carrito;
 DROP TABLE IF EXISTS libreria.compra;
 DROP TABLE IF EXISTS libreria.almacen;

CREATE TABLE libro(
     idLibro INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     titulo CHAR(50) NOT NULL,
     numPag INT NOT NULL,
     edicion CHAR(20) NOT NULL,
     categoria INT NOT NULL,
     precio numeric(4,2) NOT NULL,
     isbn CHAR(30) NOT NULL
 )ENGINE=InnoDB;



 CREATE TABLE tienda(
    idTienda INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     nombre CHAR(30) NOT NULL,
     metros INT NOT NULL,
     plantas INT NOT NULL,
    tipo INT NOT NULL
 )ENGINE=InnoDB;



 CREATE TABLE cliente(
    idCliente INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     nombre CHAR(45) NOT NULL,
     nif CHAR(10) NOT NULL,
     sexo CHAR(9) NOT NULL,
     edad INT NOT NULL,
     telefono CHAR(15) NOT NULL,
     email CHAR(45) NOT NULL,
     passw CHAR(100) NOT NULL
 )ENGINE=InnoDB;



 CREATE TABLE empleado(
    idEmpleado INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     nombre CHAR(45) NOT NULL,
     nif CHAR(10) NOT NULL,
     edad INT NOT NULL,
     telefono CHAR(15) NOT NULL,
     ciudad CHAR(20) NOT NULL,
     sueldo float NOT NULL,
     categoria INT NOT NULL,
     email CHAR(45) NOT NULL,
     passw CHAR(100) NOT NULL
 )ENGINE=InnoDB;



 CREATE TABLE autor(
    idAutor INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     nombre CHAR(45) NOT NULL,
     fNac date NOT NULL,
     numEjemVend BIGINT NOT NULL,
     categoria INT NOT NULL
 )ENGINE=InnoDB;



 CREATE TABLE direccion(
    idDireccion INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     nombre CHAR(50) NOT NULL,
     ciudad CHAR(50) NOT NULL,
     pais CHAR(50) NOT NULL,
     provincia CHAR(20) NOT NULL,
     calle CHAR(50) NOT NULL,
     numero CHAR(5) NOT NULL,
     piso CHAR(5) ,
     cp CHAR(10) NOT NULL
 )ENGINE=InnoDB;

 CREATE TABLE carrito(
    idCarrito INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    idCliente INT NOT NULL,
     idLibro INT NOT NULL,
     cantidad INT,

     CONSTRAINT FK_carrito_cliente
        FOREIGN KEY (idCliente)
            REFERENCES LIBRERIA.CLIENTE(idCliente)
                ON UPDATE CASCADE,
    CONSTRAINT FK_carrito_libro
        FOREIGN KEY (idLibro)
            REFERENCES LIBRERIA.LIBRO(idLibro)
                ON UPDATE CASCADE
 )ENGINE=InnoDB;

 CREATE TABLE compra(
    idCompra INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     idCliente INT NOT NULL,
     idLibro INT NOT NULL,
     idTienda INT NOT NULL,
     fCompra date NOT NULL,
     cantidadLibros INT NOT NULL,

     CONSTRAINT FK_compra_cliente
        FOREIGN KEY (idCliente)
            REFERENCES LIBRERIA.CLIENTE(idCliente)
             ON UPDATE CASCADE,
    CONSTRAINT FK_compra_libro
        FOREIGN KEY (idLibro)
            REFERENCES LIBRERIA.LIBRO(idLibro)
             ON UPDATE CASCADE,
    CONSTRAINT FK_compra_tienda
        FOREIGN KEY (idTienda)
            REFERENCES LIBRERIA.TIENDA(idTienda)
             ON UPDATE CASCADE
 )ENGINE=InnoDB;

 CREATE TABLE almacen(
    idAlmacen INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     idLibro INT NOT NULL,
     idTienda INT NOT NULL,

     CONSTRAINT FK_almacen_libro
        FOREIGN KEY (idLibro)
            REFERENCES libreria.libro(idLibro)
                ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT FK_almacen_tienda
        FOREIGN KEY (idTienda)
            REFERENCES libreria.tienda(idTienda)
             ON UPDATE CASCADE
 )ENGINE=InnoDB;

El cambio que hice fue añadir la tabla carrito y la foreign key idLibro a la tabla compra. Si hay algo más que pueda aportar que os sea de ayuda por favor decírmelo. Muchas Gracias.

0

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

Examina otras preguntas con la etiqueta o formula tu propia pregunta.