Eliminar múltiples registros de mysql mediante la casilla de verificación y el botón enviar

I can't manage to work this part of my app. I have to delete some records (correctly loaded from DB) in mysql database from a jsp page, checking checkboxes and clicking submit button. Even if data is correctly displayed, nothing is been deleted from DB Here's the code:

Esta es la clase

/* ArticoliManager.java */
public class ArticoliManager {

public void cancellaArticolo(String chboxArticoliDaCancellare[]) throws SQLException{
Connection con = DBConnectionPool.getConnection();
PreparedStatement ps = null;
try {
    for(String deleteThem:chboxArticoliDaCancellare){
    String query = "DELETE * FROM articoli WHERE id='"+deleteThem+"'";
    ps = con.prepareStatement(query);
    ps.executeUpdate();
    con.commit();
}
}
finally {
    if (ps != null) {
        try {
            ps.close();
        }
        catch (SQLException ignored) {
        }
    }
    try {
        con.close();
    }
    catch (SQLException ignored) {
    }
}

}
}

Here's the servlet

/* CancellaArticolo.java
*/
public class CancellaArticoloServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    int idArticoloDaCancellare = 0;
    try {
        ArticoliManager am = new ArticoliManager();
        String chboxArticoliDaCancellare[] = request.getParameterValues("chbox");
        am.cancellaArticolo(chboxArticoliDaCancellare);
        request.getRequestDispatcher("gestione_admin.jsp").forward(request, response);
    } finally {            
        out.close();
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (SQLException ex) {
        Logger.getLogger(CancellaArticoloServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (SQLException ex) {
        Logger.getLogger(CancellaArticoloServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/** 
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

Here's part of the jsp page

/* gestione_admin.jsp */
<%    
                            for (int i=0; i<al.size(); i++){
                            out.println("<table>");
                            out.println("<tr>");
                            out.println("<td>");
                            %>
                            <form action="CancellaArticolo">
                            <input type="checkbox" name="chbox" value="<%=+al.get(i).getId()%>"/>
                            <%
                            out.println("<b>Autore: </b>"+al.get(i).getAutore()+"                    <b>Articolo: </b>"+al.get(i).getTitolo()+"</td>");
                            out.println("</tr>");
                            out.println("</table>");
                            %>
                            </form>
                            <%
                            }
                            %>
                            <input type="submit" value="Cancella Articoli Selezionati"></input>
                            </form>

it seems almost allright... what's the problem?

preguntado el 02 de febrero de 12 a las 11:02

I'd test it on simple application, e.g. in console mode. Debug your code. Is connection open? Were there any exceptions? Add catch to main try-finally block. -

1 Respuestas

The checkbox value must be the ID of the item. Something like this:

<input type="checkbox" name="chbox" value="<%=al.get(i).getId()%>"/>

You should already have discovered this when you bothered to debug the chboxArticoliDaCancellare values. As you had it, they are all "chkbox".

You also need to ensure that the input elements are all inside the mismo <form> as the submit button which is supposed to send the desired data along. So, basically:

<form action="yourServletURL" method="post">
    ...
    <input type="checkbox" ... />
    ...
    <input type="checkbox" ... />
    ...
    <input type="checkbox" ... />
    ...
    <input type="submit" ... />
    ...
</form>

No relacionado to the concrete problem, you're not using PreparedStatement correctly. You still have a SQL injection hole there because you concatenated the user-controlled request parameter value inside the SQL string instead of using a placeholder ? con un PreparedStatement#setXxx() call. Also, consider looking at JSTL/EL, it will make your presentation code cleaner.

Respondido 02 Feb 12, 20:02

Yes, the problem is the chechbox value, I've corrected it. Now it deletes record but only the last record, even if others checkboxes are checked - Fsee

Eliminar el con.commit() line out of the loop. It will already be committed when you close it. By the way, to improve performance, use addBatch() y la executeBatch() en lugar de. Ver también stackoverflow.com/questions/2467125/… - BalusC

I've tried it but it continues to delete only the last record selected it seems that String[] chboxArticoliDaCancellare is not populated properly - Fsee

Well, then you haven't filled the checkboxe values correctly. Maybe they all end up to have the ID of the last item. Just look in the generated HTML source if it's all right and trackback the cause of the problem in the JSP code. - BalusC

El <form> should go around the table and the button. - BalusC

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.