How to set checkboxes in JSP

How can I get / set a checkbox value using jstl and delete only those records from the database where the checkbox is checked? can you also advise using ternary operators in jstl for this scenario?

SearchStudent.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Lookup Students</title> </head> <form method="post" action="deleteStudentServlet" class="form"> <body class="body"> <!-- List results --> <c:if test="${not empty studentList}"> <table border="1" cellspacing="0" cellpadding="0" :> <tr> <th></th> <th>ID</th> <th>Title</th> <th>First Name</th> <th>Last Name</th> <th></th> </tr> <c:forEach var="students" items="${studentList}"> <tr> <td><input type="checkbox" name="chkBox"> </td> <td>${students.studentID}</td> <td>${students.title}</td> <td>${students.firstName}</td> <td>${students.lastName}</td> <td><c:url value="UDS" var="url"> <c:param name="StudentID" value="${students.studentID}" /> </c:url> <a href="${url}">Edit</a></td> </tr> </c:forEach> </table> </c:if> <td><input type="submit" name="submit" value="Delete" ></td> </form> <p>There are ${fn:length(studentList)} results.</p> </body> </html> 

thanks.

+4
source share
1 answer

Currently, the checkbox does not have a value associated with the parameter name:

 <input type="checkbox" name="chkBox"> 

So hard to find proven. You must specify a value in the checkbox that uniquely identifies the selected item. In your specific example, the student ID seems like an obvious choice:

 <input type="checkbox" name="selected" value="${student.studentID}"> 

(by the way, why are you duplicating the name of the object in the property name? why not just name it so that you can only use the self-documented use of ${student.id} ? Also your var="students" is odd, it only refers to one , so just name it var="student" , ${studentList} better to call ${students} )

When the form is submitted, the entire verified value is available as follows:

 String[] selectedStudentIds = request.getParameterValues("selected"); 

Finally, just pass it to your DAO / service class, which performs the business task:

 studentService.delete(selectedStudentIds); 

See also:

+9
source

Source: https://habr.com/ru/post/1433904/


All Articles