0

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:

Here's the class

/* 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?

Fseee
  • 2,476
  • 9
  • 40
  • 63
  • 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. – Devart Feb 02 '12 at 11:37

1 Answers1

0

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 same <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>

Unrelated 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 ? with a PreparedStatement#setXxx() call. Also, consider looking at JSTL/EL, it will make your presentation code cleaner.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 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 – Fseee Feb 02 '12 at 14:07
  • Remove the `con.commit()` line out of the loop. It will already be committed when you close it. By the way, to improve performance, use `addBatch()` and `executeBatch()` instead. See also http://stackoverflow.com/questions/2467125/reusing-a-preparedstatement-multiple-times – BalusC Feb 02 '12 at 14:15
  • I've tried it but it continues to delete only the last record selected it seems that String[] chboxArticoliDaCancellare is not populated properly – Fseee Feb 02 '12 at 15:11
  • 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 Feb 02 '12 at 15:13
  • they have different ID, I've explored html source in the browser... really can't find why request.getParameterValues("chbox") saves only the last id – Fseee Feb 02 '12 at 16:46
  • It saves nothing. It just retrieves what is been sent with the HTTP request. Are all checkboxes and the submit button within the same `
    `?
    – BalusC Feb 02 '12 at 16:49
  • 1
    The `
    ` should go around the table and the button.
    – BalusC Feb 02 '12 at 17:04