使用servlet从数据库中删除记录

时间:2017-07-30 18:53:52

标签: java jsp servlets

Remove.java是servlet,index.jsp是jsp文件。我正在尝试使用电子邮件删除该文件,因为它是唯一的。

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>

1 个答案:

答案 0 :(得分: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"/>

此外,应删除index.jsp中的第26行(</center>)和Remove.java中的第29行(String query = "delete from user_details where email=?";),因为它们是不必要的。