Multiple Delete operation is not working - java

I am trying to delete the data by checking multiple checkboxes, but when I choose the checkboxes from the screen and hit the delete button then the only top row gets deleted. Means no matter which row I select it deletes the only first entry of the table. Please help me.
Delete.servlet
delPage = request.getParameter("delPage");
patientId = request.getParameter("pid");
if(delPage.equals("true")) {
int p = Integer.parseInt(patientId);
patientDao = new PatientDAO();
boolean b = patientDao.isPatientDeleted(p);
if (b) {
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}else
System.out.println("Patient deleting failed ... ! ");
}
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
Masterpage.jsp
<script type="text/javascript">
function addNewPatient(){
debugger;
var addNewPat = "true";
document.form.method = "POST";
document.form.action = "addPatient?newPage="+addNewPat;
document.form.submit();
}
function deletePatient(){
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}">
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
<i class="trash ulternate icon"></i>
Delete
</div>
DeletePatientServlet.java
public class DeletePatientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private PatientBean patient = null;
private PatientDAO patientDao = null;
String delPage = null ;
String patientId = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
}

Okay so there are a bunch of mistakes in your code. I'll start with the jsp...
You are trying to pass parameters via the servlet url with a POST request
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
You cannot pass data in the url with post requests. You need to change your servlet to a GET if you want to do this.
Also, in this line:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
you are passing a value to your deletePatient method. But your deletePatient method does not have an option to pass a value:
function deletePatient(){ // no value being passed here?
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
You can also just do:
${user.patientId}
instead of:
<c:out value="${user.patientId}"></c:out>
Another problem with your code is this, you cannot have multiple elements in your HTML with the same id. This is illegal HTML, and it's the reason why you are getting the same id each time:
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}"> //no this is bad.
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
Your delete button is not even inside your loop, so it will not work:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)"> //this will pass the same id each time
<i class="trash ulternate icon"></i>
Delete
</div>
Try something like this instead (for delete only):
<script type="text/javascript">
function deletePatient(e){
var patientid = e.getAttribute("data-patientid");
deletePatientForm(patientid);
}
function deletePatientForm(pid) {
var form = document.createElement("form");
var input = document.createElement("input");
form.method = "POST";
form.action = "deletePatient";
input.value=pid;
input.name="pid";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
<th>phone</th>
<th></th>
<tr>
<tr>
<td>${user.patientId}</td>
<td>${user.patientName}</td>
<td>${user.patientAddress}</td>
<td>${user.patientPhone}</td>
<td>
<div class="ui small button" onClick="deletePatient(this)" data-patientid="${user.patientId}"><i class="trash ulternate icon"></i> Delete</div>
</td>
<tr>
</c:forEach>
Then in the post of your servlet:
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
If you have any problems or questions let me know.

Related

Java error when using two submit buttons on two different forms in a jsp

I am having some trouble figuring out why I am getting an error with my code. Below is my JSP file (the problem is with the second form):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Book Drivers</title>
</head>
<body>
<h1>Book Demands</h1>
<form method="POST" action="BookDriver.do">
<br>View a table </br>
<input type="radio" name="tbl" value="ListTodaysDemands">List Todays Demands<br />
<input type="radio" name="tbl" value="ListAllDemands">List All Demands<br />
<input type=submit value="Go!"> <br />
</form>
</body>
<body>
<h2>Demands</h2>
<%=(String)(request.getAttribute("query"))%>
</body>
<body>
<h2>Journeys</h2>
<%=(String)(request.getAttribute("query1"))%>
</body>
<body>
<h2>Drivers</h2>
<%=(String)(request.getAttribute("query2"))%>
</body>
<body>
<h2>Book taxi</h2>
<form method="POST" action="BookDriver.do">
<table>
<tr>
<th></th>
<th>Please provide your following details</th>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td>Destination:</td>
<td><input type="text" name="destination"/></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" name="date"/></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" name="time"/></td>
</tr>
<tr>
<td> <input type="submit" value="Book"/></td>
</tr>
</table>
</form>
</body>
Below is my controller:
public class BookDriver extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
LocalDate date = LocalDate.now();
String qry1 = "select * from CUSTOMER";
String qry2 = "select * from DRIVERS";
String qry3 = "select * from DEMANDS where date = '"+date+"'";
String qry4 = "select * from DEMANDS";
String qry5 = "select * from JOURNEY";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Date = Journey.Date LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession(false);
Jdbc dbBean = new Jdbc();
dbBean.connect((Connection)request.getServletContext().getAttribute("connection"));
session.setAttribute("dbbean", dbBean);
if((Connection)request.getServletContext().getAttribute("connection")==null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
else if (request.getParameter("tbl").equals("ListTodaysDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current journeys";
try {
msg = dbBean.retrieve(qry3);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
else if (request.getParameter("tbl").equals("ListAllDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current drivers";
try {
msg = dbBean.retrieve(qry4);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
///////////THIS PART NOT WORKING//////////////////////////
String [] query = new String[5];
query[0] = (String)request.getParameter("name");
query[1] = (String)request.getParameter("address");
query[2] = (String)request.getParameter("destination");
query[3] = (String)request.getParameter("date");
query[4] = (String)request.getParameter("time");
Jdbc jdbc = (Jdbc)session.getAttribute("dbbean");
if (jdbc == null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
if(query[0].equals("") ) {
request.setAttribute("msg", "Username cannot be NULL");
}
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
The first form in the JSP works absolutely fine, the issue is with the second form. Whenever I use the button "Book" I get a null pointer exception and I cannot figure out why and if I comment out all of the code to due with the first form in the servlet, then it no longer throws the exception and it works fine.
I would really appreciate some help with this as I have now spent hours searching for a solution online and i'm still very much struggling to solve the problem.
Cheers,
Use request.getParameterValues("name").. and same for others too maybe the current value be null

Display retrieved data (from RESTful service) to a table (client)

I have 2 project folders. The first one is a RESTful service and the other one is a client. What I'm trying to do is:
Getting all notes from the RESTful service (I do this as a list) of a specific user.
Then display the notes to the client in a table (html).
When I try to display the notes I get the following error:
javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>
The HTML code (I'm using JSP). The error appears at the 'forEach' loop:
<table class="table table-striped">
<thead>
<tr>
<!-- Here we create the columns -->
<th> Id </th>
<th> Title </th>
<th> Text </th>
<th> Color </th>
<th> Date/Time </th>
<th> Actions </th> <!-- the table header for Actions -->
</tr>
</thead>
<!-- Table body - The data in the table -->
<tbody>
<c:forEach items="${note-all}" var="pp">
<tr>
<td><c:out value="${pp.id}" /></td>
<td><c:out value="${pp.title}" /></td>
<td><c:out value="${pp.text}" /></td>
<td><c:out value="${pp.color}" /></td>
<td><c:out value="${pp.datetime}" /></td>
<!-- The final column is the Actions, which is a list of buttons,
that we can perfom on our note Entities. -->
<td>
<div class="btn-group">
<!-- ***** Edit Button ***** -->
<a href="#Url.Action("Edit", new {pp.id})" class="btn btn-xs btn-primary">
<i class="glyphicon glyphicon-edit"></i>
Edit
</a>
<a href="#Url.Action("Delete", new {pp.id})" class="btn btn-xs btn-danger" data-post="Are you sure you want to delete this?">
<i class="glyphicon glyphicon-remove"></i>
Delete
</a>
</div>
</td>
</tr>
</c:forEach>
</tbody>
</table>
The RESTful service code:
#Path("/getAll")
#POST
#Consumes({MediaType.APPLICATION_FORM_URLENCODED/})
#Produces({MediaType.APPLICATION_XML})
public Response login(#FormParam("username") String uname
) throws ClassNotFoundException, SQLException{
System.out.println(uname);
//*First*: We get the id of the user
String sql = "SELECT user_id "
+ " FROM user_table "
+ " WHERE username = ?";
PreparedStatement ps = DbCon.getPreparedStatement(sql);
ps.setString(1, uname);
ResultSet rs = ps.executeQuery();
String id = "";
if(rs.next()){
id = rs.getString("user_id");
}
//*Second*: We get the users notes
String sql2 = "SELECT * "
+ " FROM notes_table "
+ " WHERE user_id_fk = ?";
PreparedStatement ps2 = DbCon.getPreparedStatement(sql2);
ps2.setString(1, id);
ResultSet rs2 = ps2.executeQuery();
ArrayList<Note> note_AL = new ArrayList<Note>();
if(rs2.next()){
Note note = new Note();
note.setId(rs2.getInt("note_id"));
note.setTitle(rs2.getString("title"));
note.setText(rs2.getString("text"));
note.setColor(rs2.getString("color"));
note.setDate(rs2.getString("datetime"));
note_AL.add(note);
}
//we wrap the ArrayList with Generic ENtity
GenericEntity<ArrayList<Note>> generic_list_of_notes = new GenericEntity<ArrayList<Note>>(note_AL){};
return Response.ok(generic_list_of_notes).build();
}
The client servlet code (the post method):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Form form = new Form();
form.add("username", "ali");
//We create a client object
Client client = Client.create();
//We create a resource object and pass a url to it
WebResource webR = client.resource("http://localhost:8080/MyNote/api/notes/getAll");
ClientResponse resp = webR.accept(MediaType.APPLICATION_XML/*"text/html"*/).post(ClientResponse.class, form);
//for debug
if (resp.getStatus() != 200){
System.err.println("Unable to connect to the RESTFUL web service");
}
List<Note> output = resp.getEntity(new GenericType<List<Note>>(){});
request.setAttribute("note-all", output);
RequestDispatcher rd = request.getRequestDispatcher("/Notes.jsp");
rd.forward(request, response);
}

Showing error message on JSP using BindingResult

I am new to Spring.
I am trying to show error messages on jsp for the wrong user and password by using BindingResult. But the error messages are not showing.
Please suggest me what I is wrong in the below code.
JSP
<script type="text/javascript">
function loginUser() {
$('#loginForm').submit();
}
</script>
</head>
<body>
<form:form action="login.test" id="loginForm" commandName="loginForm" method="POST">
<div class="brand_area"></div>
<div class="content_area">
<table style="top: 360px; position: relative; margin-left: 333px;">
<tr id="uNameID">
<td class="label">User Name:</td>
<td><form:input id="userNameID" path="userName" class="textInput" /></td>
<td><form:errors path="userName" class="error"/></td>
</tr>
<tr id="pID">
<td class="label">Password:</td>
<td><form:password id="passwordID" path="password" class="textInput" /></td>
<td><form:errors path="password" class="error"/></td>
</tr>
<tr>
<td></td>
<td><span id="saveButton" class="loginButton"
onclick="loginUser()"> <span>Login</span>
</span></td>
</tr>
</table>
</div>
</form:form>
Controller
#RequestMapping(value = "login.test", method = RequestMethod.POST)
public String processForm( LoginForm loginForm, BindingResult result, ModelMap model, HttpSession session) throws SQLException {
String resultedPage;
model.addAttribute("l_nodes", reportService.getAllLiveNodes());
model.addAttribute("s_nodes", reportService.getAllStaticReportNodes());
User user = userService.getUserByName( loginForm.getUserName() );
if( user != null ){
session.setAttribute("userID", user.getUserID());
if( loginForm.getPassword().equals( user.getPassword() ) ){
resultedPage = "home/userHome";
}else{
result.rejectValue( "password", "login.passwordNotValid");
resultedPage = "redirect:login.test";
}
}else{
result.rejectValue( "userName", "login.userNotValid");
resultedPage = "redirect:login.test";
}
return resultedPage;
}
Thanks
In case anyone else research the same...
Add the hasBindErrors tag to your JSP:
<spring:hasBindErrors name="loginForm">
<c:forEach var="error" items="${errors.allErrors}">
<b><spring:message message="${error}" /></b>
<br/>
</c:forEach>
</spring:hasBindErrors>
Well, i generally send back the values using the Model object.
May be this answer might help you.

mixing up ajax and jsp to get data into a servlet

I've got a jsp file with two text fields (signUp and post). Now, I want the post text and the signUp text to be called to a servlet. Normally its going with request.getParameter(), but now I want the post text going to the servlet with an AJAX function and the signup text with the normal way (that means the name of the input within the jsp file and then request.getParameter).
Is it possible to mix both parts within one servlet because i have this:
<form name="form1" method="POST" action="PostWallServlet" id="form1">
form1 is the ajax code. I don't know how this should work. Normally there stands
`<form action="PostWallServlet" method="POST" >
and everything is callable through the Servlet. But, for now I don't know how I can mix up both components.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PostWall pw=new PostWall();
SimpleDateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + df.format(cal.getTime()));
String message = "";
String sender = request.getParameter("sender");
String post = request.getParameter("message");
String a= df.format(cal.getTime()).toString();
pw.setSender(sender);
pw.setPost(post);
pw.setDate(a);
if (pwi.addPost(pw)) {
message = "Student Successfuly Added";
} else {
message = "Student Adding Failed";
}
//RequestDispatcher rd = request.getRequestDispatcher("post.jsp");
//rd.forward(request, response);
}
$(document).ready(function(){
$('#Add').click(function(){
sendData();
});
});
function sendData(){
var mge = $('#newText').val();
alert(mge);
$.ajax({
type: "POST",
url: "PostWallServlet",
data: { message : mge }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
<form name="form1" method="GET" action="PostWallServlet" id="form1"></form>
<table border="0" width="100%">
<tr>
<td colspan="3"> ${message}</td>
</tr>
<tr>
<td>Sender</td>
<td>:</td>
<td><input type="text" name="sender" value="" size=20/></td>
</tr>
<tr>
<td>Post</td>
<td>:</td>
<td><input type="text" name="post" value="" size=500 id="newText"/ ></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" value="Add" name="Add" /></td>
</tr>
</table>
Any solutions?
Put your ending tag for form AFTER all your inputs:
<form name="form1" method="GET" action="PostWallServlet" id="form1">
...
<td><input type="text" name="sender" value="" size=20 /></td>
...
<td><input type="text" name="post" value="" size=500 id="newText" /></td>
...
<td><input type="submit" value="Add" name="Add" /></td>
...
</form>
Your inputs must be INSIDE the form, not after the form.
Also make sure to end your input tags with /> not / >. You have a space between / and > on one of them.
For the Ajax part you need to give your inputs ids as well as names:
<td><input type="text" name="sender" id="sender" value="" size=20 /></td>
And then in your Ajax function for data:
data: { sender: $('#sender').val(), post: $('#post').val() }

JSTL foreach hidden input submits a null value

I'm doing a small JEE5 application similar to an online shop and I need to show the shop products, it can be seen more clearly in the code:
<c:forEach var="product" items="${productsBean.products}">
<div class ="product">
<table>
<td>
<c:out value="${product.id}"/>
</td>
<td>
<c:out value="${product.name}"/>
</td>
<td>
<c:out value="${product.price}"/>
</td>
<td>
<c:out value="${product.description}"/>
</td>
<td>
<form method="post" action="/servlets-war/AddToCart">
<input type="hidden" name="id" value="${product.id}"></input>
<input type="submit" value="add to cart"/>
</form>
</td>
</table>
</div>
</c:forEach>
The problem is that the hidden input value in the form returns null instead of the ${product.id} when the form is submitted.
The associated servlet code is the next:
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
ShoppingCart shoppingCart = (ShoppingCart)request.getSession()
.getAttribute("shoppingCart");
if(shoppingCart == null){
shoppingCart = new ShoppingCart();
}
ProductsBean store =(ProductsBean) request
.getSession().getAttribute("productsBean");
int id = Integer.parseInt((String)request.getAttribute("id"));
Product temp = store.getProduct(id);
shoppingCart.getProducts().add(temp);
request.getSession().setAttribute("shoppingCart", shoppingCart);
this.getServletContext().getRequestDispatcher("/shop.jsp")
.forward(request, response);
}
You are retrieving the id as a request attribute.
int id = Integer.parseInt((String)request.getAttribute("id"));
Form input is sent to the servlet as a request parameter. Change your code appropriately:
int id = Integer.parseInt((String)request.getParameter("id"));

Categories