retrieve id and Delete the line using button JSP - java

I am new to jsp.
In my example I retrieve data from a table and I am looking to have a button that can delete the row using the id , it does not work, but when I inspect the button I see that it retrieves the id correctly but the deletion does not run .
I work for the moment with the servlet class, and I pass the delete method in dopost
Code jsp :
<%
try {
ArrayList<Dossier> dossiers = (ArrayList<Dossier>) request.getAttribute("list_dossiers");
for (Dossier c : dossiers) {%>
<tr>
<td> <%=c.getId()%> </td>
<td> <%=c.getTitre()%> </td>
<td> <%=c.getDate_creation()%></td>
<td> <form action="Controller" method="post">
<input type="hidden" name="type" value="supprimerDossier"/>
<input type="hidden" name="id" value="<%=c.getId()%>"/>
<button type="submit" class="btn btn-primary">Supprimer</button>
</form>
</td>
<td> <button type="button" class="btn btn-primary">Modifier</button> </td>
</tr>
<% }
} catch (Exception e) {
e.printStackTrace();
}%>
Method delete :
private void deleteDossier(int id) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/avocat", "root", "");
PreparedStatement ps = con.prepareStatement("DELETE FROM dossier WHERE ID=?");
ps.setInt(1, id);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
Dopost:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String hiddenParam=request.getParameter("type");
try {
if (hiddenParam.equals("addClient")) {
addClients(request, response);
request.setAttribute("success", "Client ajouté avec succès");
getServletContext().getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
} else if (hiddenParam.equals("addDossier")) {
addDossiers(request, response);
request.setAttribute("success", "Dossier ajouté avec succès");
getServletContext().getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
} else if (hiddenParam.equals("supprimerDossier")){
String id= request.getParameter("id");
deleteDossier(Integer.parseInt(id));
request.setAttribute("success", "Dossier supprimer");
getServletContext().getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}

Related

HTTP Status 404 - Not Found in Servlet crud

i am creating a simple crud system in Java Servlet. I am beginner of Servlet.I filled the form and clicked submit button and got the error - HTTP Status 404 - Not Found. I have attached the screen shot image below along with the code.
folder structure
Form
<form method = post action = "employee/employee.java">
<table class="table table-borederd">
<tr>
<td>Enter Employee ID:</td>
<td ><input class="form-control" type = "text" name = "txtEmpId"/></br></td>
</tr>
<tr>
<td>Enter Employee FirstName:</td>
<td ><input class="form-control" type = "text" name = "txtFName"/></td>
</tr>
<tr>
<td>Enter Employee LastName:</td>
<td ><input class="form-control" type = "text" name = "txtLName"/></td>
</tr>
<td><input type = "submit" value = "submit"/></td>
</form>
employee.java
public class employee extends HttpServlet
{
Connection con;
int row;
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException, ServletException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/empp","root","");
System.out.println("Connection Established");
}
catch(Exception e)
{
System.out.println("Sorry...........");
}
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
String empId = req.getParameter("txtEmpId");
String empFName = req.getParameter("txtFName");
String empLName = req.getParameter("txtLName");
try
{
PreparedStatement stat = con.prepareStatement("insert into record (id,fname,lname) Values(?,?,?)");
stat.setString(1,empId);
stat.setString(2,empFName);
stat.setString(3,empLName);
row = stat.executeUpdate();
}
catch(Exception e)
{
}
out.println("<html>");
out.println("<font color = 'red'>Sucessfully registered!</font>");
out.println("</body>");
out.println("<h2>");
out.println(row);
out.println("</h2>");
out.println("</body>");
}
}

Inserting user records into MYSQL table

I am trying to create a register page for users to register new accounts.
I am using signup.jsp page with the register form
Which is then connected to RegisterServlet.java (gets form parameters and inserts parameters into database after connecting to DBConnection.java)
DBConnection contains the try{} of connecting to the mysql database.
I have tried multiple ways of registering a user, but the users information never inserts into database.
signup.jsp:
<form action="RegisterServlet" method="post" onsubmit="return validate()">
<div class="row">
<div class="col-lg-6 col-md-6">
<input type="text" placeholder="First Name" name="fname" class="form-control" />
</div>
<div class="col-lg-6 col-md-6">
<input type="text" placeholder="Last Name" name="lname" class="form-control" />
</div>
</div>
<div>
<input type="text" placeholder="User Name" name="username" class="form-control" />
</div>
<div class="row">
<div class="col-lg-6 col-md-6">
<input type="password" placeholder="Password" name="password" class="form-control" id="pass" name="pass" />
</div>
<div class="col-lg-6 col-md-6">
<input type="password" placeholder="Retype Password" name="confirm_password" class="form-control" id="pass2" name="pass2" />
</div>
<div class="col-lg-6 col-md-6">
<%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%>
</div>
</div>
<div class="pull-left"><button type="submit" class="btn btn-primary">Sign Up</button></div>
</form>
RegisterServlet.java:
#WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("login.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String username = request.getParameter("username");
String password = request.getParameter("password");
DBConnection db = new DBConnection();
Connection con = db.getCon();
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into user (fname, lname, username, password)values('"+fname+"','"+lname+"','"+username+"','"+password+"')");
System.out.println("data inserted sucessfully");
response.sendRedirect("login.jsp");
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
DBConnection.java
public class DBConnection {
public Connection con;
public Connection getCon(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cultureexchange", "root", "");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
Sql user table:
fname lname username password
varchar varchar varchar varchar
My login.jsp works so the connection to database must work,
appreciate the help in advance.
try Changing these line
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into user (fname, lname, username, password)values('"+fname+"','"+lname+"','"+username+"','"+password+"')");
to
PreparedStatement stmt = con.prepareStatement("insert into user (fname, lname, username, password)values(?,?,?,?)");
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, username);
ps.setString(4, password);
ps.executeUpdate();
And make sure that you have mysql-j-connector in your lib folder under WEB-INF.

How can I insert and delete value in a database in derby in JSP?

The history: history
The problem is I cannot delete customer from the database. I can create a new customer, but if I leave blank the fields it create an empty record in the database but I create an if criterium.
The client.java:
public class client implements DatabaseConnection{
private static Connection conn = null;
private static void createConnection(){
try {
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void closeConnection(){
if (conn != null){
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public List clientList(){
createConnection();
List list=new ArrayList();
try {
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM customer");
while(rs.next()){
list.add(rs.getString("CNAME"));
list.add(rs.getString("ADDRESS"));
list.add(rs.getString("PHONENUMBER"));
}
stmt.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
return list;
}
public void newClient(String name, String address, String phoneNumber)
throws SQLException{
PreparedStatement ps = null;
try {
createConnection();
String insert="INSERT INTO CUSTOMER(CNAME,ADDRESS, PHONENUMBER)
VALUES(?,?,?)";
ps=conn.prepareStatement(insert);
ps.setString(1, name);
ps.setString(2, address);
ps.setString(3, phoneNumber);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
finally {
ps.close();
closeConnection();
}
}
public void deleteClient(String ID){
try {
createConnection();
String delete="DELETE FROM CUSTOMER WHERE ID=?";
PreparedStatement ps=conn.prepareStatement(delete);
ps.setString(1, ID);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
The index.jsp:
<jsp:useBean id="client" class="database.client" scope="page" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body bgcolor="lightgrey">
<%
String ID=request.getParameter("ID");
String NAME=request.getParameter("CNAME");
String ADDRESS=request.getParameter("ADDRESS");
String PHONENUMBER=request.getParameter("PHONENUMBER");
%>
<form method="post" action="">
<table border="0" align="left">
<th colspan="2" align="center" style="color: brown">Field</th>
<tr>
<td>Name:</td>
<td><input type="text" name="CNAME" style="background-
color:beige"/></td>
</tr>
<tr>
<td>Address?</td>
<td><input type="text" name="ADDRESS" style="background-
color:beige"/></td>
</tr>
<tr>
<td>PhoneNumber:</td>
<td><input type="text" name="PHONENUMBER" style="background-
color:beige"/></td>
</tr>
<input type="submit" name="OK" onclick="
<%
if(NAME!=null && ADDRESS!=null && PHONENUMBER!=null){
client.newClient(NAME, ADDRESS, PHONENUMBER);
}
%>" value="OK"/>
<input type="submit" name="Cancel" onclick="
<%
//nothing
%>" value="Cancel"/>
<input type="submit" name="Delete" onclick="
<%client.deleteClient(ID);%>" value="Delete"/>
</table>
<table border="2">
<th colspan="4" align="center" bgcolor="orange">Clients</th>
<tr bgcolor="silver" align="center">
<td> </td>
<td>Name</td>
<td>Address</td>
<td>PhoneNumber</td>
</tr>
<%
List list=client.clientList();
Iterator it=list.iterator();
while(it.hasNext()){
out.print("<tr bgcolor='lightgreen'>");
out.print("<td>");
NAME=(String)it.next();
out.print("<input type='radio' name='ID' value="+NAME+"/>");
out.print("</td>");
out.print("<td>");
out.print(NAME);
out.print("</td>");
for (int i = 0; i < 2; i++) {
out.print("<td>");
out.print(it.next());
out.print("</td>");
}
out.print("</tr>");
}
%>
</table>
</form>
</body>
</html>
If I leave empty the fields and click OK the following error message appears:
Caused by: org.apache.derby.client.am.SqlException: No actual connection.
If no connection how can create an empty record?
And:
Severe: java.lang.NullPointerException at: client.java PreparedStatement ps=conn.prepareStatement(delete);
EDIT
The new error:
Severe: java.sql.SQLDataException: Invalid string format for INTEGER.
Looks like you are not setting the ID in the list
while(rs.next()){
list.add(rs.getString("ID")); // Add this
list.add(rs.getString("CNAME"));
list.add(rs.getString("ADDRESS"));
list.add(rs.getString("PHONENUMBER"));
}
Without ID in the list , you wont be able to access the same from the jsp and the same wont be available when you call the delete method.
Another thing is make sure that the ID is string and not int . Usually we keep the key (i.e ID here ) as integer.
I understand from the previous question where you defined ID as integer, so you should use setInt instead of setString, try as
public void deleteClient(Integer id){
try {
createConnection();
String delete="DELETE FROM CUSTOMER WHERE ID=?";
PreparedStatement ps=conn.prepareStatement(delete);
ps.setInt(1, id);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
ps.close();
closeConnection();
}
}
Id is an integer in the database field where you defined it has a primary key.
Update 1
Use the following in your index.jsp to convert String to int, pass idNum to your method.
Integer idNum = null;
String id = request.getParameter("ID");
if(id != null) {
try {
System.out.println("String Id value --> "+id.trim());
idNum = Integer.parseInt(id.trim());
}
catch(NumberFormatException ex) {
ex.printStackTrace();
}
}

Delete entire Row from Table in database and display all data in table(i.e., auto update the table in same page)

In table 10 rows are there..selected data has to delete (using check box) and display all the content in table....Here newsid in JSP file is auto incremented value....
This is DeleteSuccess.java File
public class DeleteSuccess extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase","root","root");
PreparedStatement ps = con.prepareStatement("delete from ROOT.NEWSTABLE where newsid='" + (* here what i have 2 write *) +"'");
int i= ps.executeUpdate();
PreparedStatement pss = con.prepareStatement("select NEWSID,NEWS from ROOT.NEWSTABLE");
ResultSet rs =pss.executeQuery();
ArrayList<News> listnewsobj = new ArrayList<News>();
while(rs.next())
{
News obj=new News();
obj.setNewsId(rs.getInt(1));
obj.setNews(rs.getString(2));
listnewsobj.add(obj);
}
session.setAttribute("listnewskey",listnewsobj);
System.out.println(listnewsobj);
if (i > 0)
{
System.out.println("Venkatesh");
//out.print("You are successfully registered...");
//RequestDispatcher rs = request.getRequestDispatcher("Login.html");
// RequestDispatcher rd = request.getRequestDispatcher("JSP/AddNews.jsp");
// rd.include(request, response);
response.sendRedirect("JSP/AddNews.jsp");
}
} catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
This is JSP file
<form method="post" action="../newsdelete">
<fieldset class="rt">
<legend> <b> Manage News </b> </legend>
<table>
<tr>
<th>News Id</th>
<th>News Name</th>
<th>Action</th>
</tr>
<c:forEach items="${listnewskey}" var="listnews">
<tr>
<td class="first_col">${listnews.newsId}</td>
<td>${listnews.news}</td>
<td class="third_col">
<input id="" type="checkbox" name="check" value="action"><label for="radio1"><span><span></span></span></label>
</td>
</tr>
</c:forEach>
</table>
<div> <br><input type="submit" value="Delete" name="delete"></div>
</fieldset>
</form>
This is web.xml
<servlet>
<servlet-name>Delete</servlet-name>
<servlet-class>com.venkatesh.DeleteSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Delete</servlet-name>
<url-pattern>/newsdelete</url-pattern>
</servlet-mapping>
Can anyone tell me how to delete the row which is checked and automatically display the information from the table in same JSP file which i have written the table in Loop...

Updated list is not showing in jsp page even after successful execution of delete query

My jsp page code is here:
<form id="target" >
<table id="table">
<tr id="firstrow"><th>Product Name</th><th>Quantity</th><th>Price/unit</th><th>Vendor's Name</th><th>actions</th></tr>
<c:forEach var="current" items="${sessionScope.productname}" >
<tr id="select_one">
<input id="productId" type="hidden" name="productId" value="<c:out value="${current.productId}" />"/>
<td><input id="productName" class="box" type="" name="productName" value="<c:out value="${current.productName}" />" readonly></td>
<td><input id="quantity" class="box" type="" name="quantity" value="<c:out value="${current.quantity}"/>" readonly></td>
<td><input id="price" class="box" type="" name="price" value="<c:out value="${current.price}"/>" readonly></td>
<td><input id="vname" class="box" type="" name="vname" value="<c:out value="${current.vname}"/>" readonly></td>
<td>
<input class="Edit" type="button" name="action" value="Edit">
<input class="delete"type="button" name="action" value="Delete">
</td>
</tr>
</c:forEach>
</table>
</form>
The jQuery which I have written for "Delete" button is(which is also working fine)
$(document).ready(function() {
$(".delete").click(function()
{
$("#table").remove();
var productId=$(this).closest('tr').find("#productId").val();
var param = {productId:productId};
$.ajax({
url: './deleteproduct',
data: param,
type: 'post',
success: function(result) {
location.reload();
}
});
});
});
And my deleteproduct() fuction code is
public static boolean deleteProduct(int productId) {
boolean status=false;
String driverClass="com.mysql.jdbc.Driver";
String dbUrl="jdbc:mysql://localhost:3306/pmsdb?&relaxAutoCommit=true";
String dbUser="root";
String dbPswd="root";
PreparedStatement pstmt=null;
Connection con=null;
try{
Class.forName(driverClass);
con=DriverManager.getConnection(dbUrl,dbUser,dbPswd);
pstmt=con.prepareStatement("DELETE FROM `pms_prd_details` WHERE `producid`=?");
pstmt.setInt(1, productId);
pstmt.executeUpdate();
con.commit();
System.out.println("Record is deleted!");
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return status;
}
And here is also my servlet's doPost() method
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
int productId=Integer.parseInt(request.getParameter("productId"));
System.out.println(productId);
DeleteProductFromList dpd=new DeleteProductFromList();
if (dpd.deleteProduct(productId)){
System.out.println("true");
ShowProduclist lst= new ShowProduclist();
request.getSession().setAttribute("productname", lst.showProductlist());
RequestDispatcher rd=request.getRequestDispatcher("ProductList.jsp");
rd.include(request,response);
}
}
My eaxact question is that, when I call the
request.getSession().setAttribute("productname", lst.showProductlist());
for creating new record or updating new record and try to show in the same jsp page it's working fine. But at the time of deletion I did the same thing but although it has deleted the record from database successfully in my jsp page it is showing the already deleted record.What is going on?Please help me thank you.
You probably need to understand how Ajax works. When you call your delete inside jQuery with ajax, there is no page reload. Your client still have the same HTML, but he just send delete request in background.
So whole communication is inside JavaScript. Your server can respond with some status (for example 200 OK) and you can make some action in JavaScript on this response from server in your success function (delete object from HTML) using JavaScript/jQuery something like this:
$("#item10").remove()
You can try use some tools like Firebug (plugin for Firefox) to track your HTML/Ajax requests to figure out what is happening.
Update
$(document).ready(function() {
$(".delete").click(function()
{
var productId=$(this).closest('tr').find("#productId").val();
var param = {productId:productId};
$.ajax({
url: './deleteproduct',
data: param,
type: 'post',
success: function(result) {
//find row to delete and use remove();
}
});
});
});

Categories