Search code examples
javahtmljspservletsjstl

Trouble running overridden doPost method in a java servlet


The code below is from the jsp file.

<table class="table table-striped table-hover table-responsive ezoo-datatable">
        <thead>
            <tr>
                <th class="text-center">Schedule ID</th>
                <th class="text-center">Feeding Time</th>
                <th class="text-center">Recurrence</th>
                <th class="text-center">Notes</th>
                <th class="text-center">Food</th>
                <th class="text-center">Animal ID</th>
                <th></th>
            </tr>
        </thead>
        <% int counter = 0; %>
        <tbody>
            <form action="feedingSchedules" method="post">
                <c:forEach var="schedule" items="${feeding_schedules}">
                <tr>
                    <td><c:out value="${schedule.schedule_ID}" /></td>
                    <td><c:out value="${schedule.feeding_time}" /></td>
                    <td><c:out value="${schedule.recurrence}" /></td>
                    <td><c:out value="${schedule.notes}" /></td>
                    <td><c:out value="${schedule.food}" /></td>
                    <td><c:out value="${schedule.animalID}" /></td>
                    <td><button class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button></td>
                    <% counter++; %>
                </tr>
            </c:forEach>
            <input type="hidden" name="numSchedules" value="${counter}"/>
            </form>
        </tbody>
    </table>    

This code builds a table of data. I have a servlet to populate the table by fetching data from a database in a call to a dao method. I need to add buttons to the table to delete the row corresponding to the button. I have the buttons in place, but I'm not sure how to get them to perform the actual deletion.

@WebServlet(description = "This servlet is the main interface into the Feeding Schedules   System", urlPatterns = { "/feedingSchedules" })
public class FeedingSchedulesServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws    ServletException, IOException {

    // Grab a list of Animals from the Database
    FeedingScheduleDAO dao = DAOUtilities.getFeedingScheduleDao();
    List<FeedingSchedule> schedules = dao.getAllSchedules();

    // Populate the list into a variable that will be stored in the session
    request.getSession().setAttribute("feeding_schedules", schedules);

    request.getRequestDispatcher("feedingScheduleHome.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    FeedingScheduleDAO dao = DAOUtilities.getFeedingScheduleDao();
    List<FeedingSchedule> schedules = dao.getAllSchedules();
    //Get Parameters
    System.out.println("got here");
    int count = Integer.parseInt(request.getParameter("numSchedules"));
    for(int i = 0; i < count; i++) {
        String btn = null;
        btn = request.getParameter("btn" + i);
        if(btn == ("val" + i)) {
            System.out.println("got here");
            // call delete method from DAO
            try {
                dao.deleteSchedule(schedules.get(i));
                request.getSession().setAttribute("message", "Schedule successfully deleted");
                request.getSession().setAttribute("messageClass", "alert-success");
                response.sendRedirect("feedingSchedules");
            } catch (Exception e) {
                e.printStackTrace();
                request.getSession().setAttribute("message", "There was a problem deleting the schedule at this time");
                request.getSession().setAttribute("messageClass", "alert-danger");
                request.getRequestDispatcher("feedingScheduleHome.jsp").forward(request, response);
            }
        }
    }
}

}

The above code is the servlet. The print lines I put in the overridden doPost method do not show in the console when I click the buttons, so I do not believe the method is being called properly. Does anyone know what I'm doing wrong? I've spent a few hours staring at this and could use some fresh eyes.


Solution

  • Assign an id to your form e.g.

    <form id="myForm" action="feedingSchedules" method="post">
    

    And replace

    <button class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button>
    

    with

    <button class="btn-danger-stale" name="btn${counter}" value="val${counter}" onclick="document.getElementById('myForm').submit();">Delete Schedule</button>
    

    Alternatively,

    Assign an id to your form as mentioned above and also to your button as mentioned below:

    <button id="myButton" class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button>
    

    and add the following javascript in your jsp file:

    var form = document.getElementById("myForm");
    
    document.getElementById("myButton").addEventListener("click", function () {
      form.submit();
    });