2017-07-30 72 views
0

Remove.java是servlet,index.jsp是jsp文件。我試圖使用電子郵件刪除該文件,因爲它是唯一的。使用servlet從數據庫中刪除記錄

Remove.java

package servletPool; 

import java.io.IOException; 
import java.io.PrintWriter; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 

import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

@WebServlet("/Remove") 
public class Remove extends HttpServlet { 
private static final long serialVersionUID = 1L; 

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 

    String uEmail = request.getParameter("email"); 

    try { 
     Class.forName("com.mysql.jdbc.Driver"); 
     String user = "root"; 
     String pass = "root"; 
     String query = "delete from user_details where email=?"; 
     Connection con = DriverManager.getConnection("jdbc:mysql://locahost:3306/dbname", user, pass); 
     PreparedStatement ps = con.prepareStatement("delete from user_details where email=?"); 
     ps.setString(1, uEmail); 

     int i = ps.executeUpdate(); 

     if(i > 0) { 
      out.println("User successfully removed..."); 
     } 

    } catch (Exception e) { 
     System.out.println(e); 
    } 
} 

} 

,這裏是index.jsp文件從該記錄將被刪除。

的index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>Registration Page.</title> 

</head> 
<body> 
    <div> 


      <div style="padding : 10px;"> 
      <center> 

       <form action="Remove.servlet" method="get"> 
       <h5>If you want to remove users,</h5> 
       <input type="email" placeHolder="User's Email" name="email"/> 
       <input type="button" value="Click" name="remove"/> 
       </form> 

      </center> 
     </div> 

    </center> 

    </div> 
    </body> 
    </html> 
+0

對於錯誤感到抱歉,但在index.jsp中有method =「post」。 –

+0

您能否驗證表單操作?試試這個:action =「/刪除」 –

+0

歡迎來到Stack Overflow!你已經在你的問題中發佈了很多代碼,這使得我們(以及未來的讀者)不清楚問題出在哪裏。請將您的問題代碼減少到10行或更少。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)和[如何調試小程序](https://ericlippert.com/2014/03/05 /如何調試的小程序/)。 –

回答

1

嘗試從改變:

<form action="Remove.servlet" method="get"> 

到:

<form action="Remove" method="post"> 

和:

<input type="button" value="Click" name="remove"/> 

到:

<input type="submit" value="Click" name="remove"/> 

另外,在因爲它們是不必要在Remove.java index.jsp和第29行(String query = "delete from user_details where email=?";)應被刪除線26(</center>)。

相關問題