Foros del Web » Programación para mayores de 30 ;) » Java »

Problema al selecciona filas a borrar con checkbox en JSP y servlet

Estas en el tema de Problema al selecciona filas a borrar con checkbox en JSP y servlet en el foro de Java en Foros del Web. Muy buenas a todos, estoy desarrollando el tipico backend para mostrar filas, borrarlas, modificarlas, etc.. Y estoy teniendo problemas en el servlet que supuestamente recoje ...
  #1 (permalink)  
Antiguo 16/01/2017, 06:05
 
Fecha de Ingreso: octubre-2013
Mensajes: 79
Antigüedad: 10 años, 6 meses
Puntos: 1
Problema al selecciona filas a borrar con checkbox en JSP y servlet

Muy buenas a todos,


estoy desarrollando el tipico backend para mostrar filas, borrarlas, modificarlas, etc..
Y estoy teniendo problemas en el servlet que supuestamente recoje el ID de cada fila seleccionada para borrar por el checkbos seleccionado.
El error que me aparece es: java.lang.NullPointerException. Osea que esta recogiendo el valor de las variables en null.
El error creo que debe estar en el JSP que no he declarado bien el valor del ID ó en el action del form no redirijo correctamente al servlet. ö tal vez en el servlet no recojo adecuadamente los valores del checkbox.

Subo el codigo del JSP y del servlet. Gracias por las aportaciones :)


Codigo JSP:


<%@page import="Imagenes.*" %>
<%@page import="java.sql.*" %>
<%@page import="java.io.*" %>
<%@page import="javax.servlet.http.*" %>
<%@page import="javax.imageio.ImageIO" %>
<%@page import="javax.servlet.ServletOutputStream" %>
<%@page import="java.awt.image.BufferedImage" %>

<jsp:setProperty name="imagen" property="*" />

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<HTML ><HEAD><TITLE>Imagenes</TITLE></HEAD><BODY><HEADER><H1>Mostrar Imagenes</H1></HEADER>

<form action="http://localhost:8080/SubirImagenes/delete" method="Post" enctype='multipart/form-data'>
<TABLE><TR><TH >Nombre</TH><TH colspan='3'>FOTO</TH></TR>


<%
try {
String d = "com.mysql.jdbc.Driver";
Class.forName(d);
String sURL = "jdbc:mysql://localhost:3306/imagenes";
Connection Conexion;
Conexion = DriverManager.getConnection(sURL, "root", "oldViews17");


Statement misentencia;
ResultSet rs;
misentencia=Conexion.createStatement();
rs=misentencia.executeQuery("SELECT * FROM imagenes");
while (rs.next()) {
String nombre = rs.getString("Nombre");
int Id = rs.getInt("Id");
%>
<tr>
<td > <input type="checkbox" value='<%=Id %>' name='caja'></td>
<td > <%=Id %></td>
<td ><%=nombre %></td>

<td ><img src="http://localhost:8080/SubirImagenes/select?Id=<%=Id %>" width="190px" height="100px" align="right"></td></tr>


<%
}
}
catch (SQLException ex) {
}
catch(ClassNotFoundException ex)
{
}
%>

</table>
<input type="submit" value='Borrar'>
</form>

</body>
</html>



__________________________________

Codigo del servlet:



package Imagenes;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.*;


@WebServlet(urlPatterns = {"/delete"})
public class delete extends HttpServlet {

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

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<HTML ><HEAD><TITLE>Borrado</TITLE></HEAD><BODY><HEADER><H1>Borrado</H1></HEADER>");

try {

String [] Array= request.getParameterValues("caja");


String d = "com.mysql.jdbc.Driver";
Class.forName(d);
String sURL = "jdbc:mysql://localhost:3306/imagenes";
Connection Conexion;
Conexion = DriverManager.getConnection(sURL, "root", "oldViews17");

PreparedStatement misentencia;

for (int j=0; j<Array.length-1; j++) {
String IdBorrar=Array[j];

misentencia = Conexion.prepareStatement("DELETE * FROM Imagenes WHERE Id='"+IdBorrar+"'");
ResultSet rs = misentencia.executeQuery();
}


} catch (SQLException ex) {

}
catch(ClassNotFoundException ex)
{

}
catch(NullPointerException ex)
{
out.println("<P>No envia variables desde el JSP</P>");
}

out.println("</body></html>");
}
}
  #2 (permalink)  
Antiguo 16/01/2017, 18:17
 
Fecha de Ingreso: mayo-2010
Mensajes: 99
Antigüedad: 13 años, 11 meses
Puntos: 5
Respuesta: Problema al selecciona filas a borrar con checkbox en JSP y servlet

Wenas te recomiendo este libro de arquitectura java solida , te va guiando paso a paso , espero sirva

http://www.arquitecturajava.com/el-libro/


  #3 (permalink)  
Antiguo 17/01/2017, 05:39
 
Fecha de Ingreso: octubre-2013
Mensajes: 79
Antigüedad: 10 años, 6 meses
Puntos: 1
Respuesta: Problema al selecciona filas a borrar con checkbox en JSP y servlet

Gracias por la aportación :)

Me vendra muy bien para más adelante cuando quiera optimizar la estructura de las servlets, JSP ...si es mejor emplear alguna clase ...etc...lo teni en mente y este libro me va ser de gran ayuda.
  #4 (permalink)  
Antiguo 17/01/2017, 05:39
 
Fecha de Ingreso: octubre-2013
Mensajes: 79
Antigüedad: 10 años, 6 meses
Puntos: 1
Respuesta: Problema al selecciona filas a borrar con checkbox en JSP y servlet

Gracias por la aportación :)

Me vendra muy bien para más adelante cuando quiera optimizar la estructura de las servlets, JSP ...si es mejor emplear alguna clase ...etc ...lo tenia en mente, y este libro me va ser de gran ayuda!
  #5 (permalink)  
Antiguo 17/01/2017, 06:02
 
Fecha de Ingreso: octubre-2013
Mensajes: 79
Antigüedad: 10 años, 6 meses
Puntos: 1
Respuesta: Problema al selecciona filas a borrar con checkbox en JSP y servlet

Y por otro lado ya lo he solucionado.

Hay que eliminar el atributo method="Post" enctype='multipart/form-data de la etiqueta <form> en el JSP para que funcione. Ese atributo es para subir archivos, lo pegue directamente del archivo de insertar en la base de datos, con lo que para este fin no hace falta y ademas ya se ha visto que da problemas.

Despues me he dado cuenta que las sentencias para borrar tienen algun fallo, porque reutilize las del select. Optimizandolas me quedaron asi (por si alguien quiere reutilizar codigo):

try {

String [] Array= request.getParameterValues("caja");


String d = "com.mysql.jdbc.Driver";
Class.forName(d);
String sURL = "jdbc:mysql://localhost:3306/imagenes";
Connection Conexion;
Conexion = DriverManager.getConnection(sURL, "root", "");

Statement misentencia;
ResultSet misresultados;
misentencia=Conexion.createStatement();


for (int j=0; j<Array.length; j++) {
int IdBorrar=Integer.parseInt(Array[j]);
out.println("<P>"+IdBorrar+"</P>");

if((misentencia.executeUpdate("DELETE FROM Imagenes WHERE Id="+IdBorrar))==1){
out.println("<P>El borrado se ha realizado</P>");
}
else{
out.println("<P>El borrado ha fallado </P>");
}

}

Conexion.close();
}

Última edición por sentoki79; 25/04/2018 a las 16:22

Etiquetas: checkbox, filas, imagenes, jsp, servlet, set, string
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 23:15.