大家好,希望你有一个美好的一天,因为我不是xD,我是网络编程的新手,我开始使用JSP和Servelts进行网络操作我的问题是什么时候我点击"删除"它会触发servlet,但没有任何事情发生,行不会被删除,并且值(pw.print(name))也不会显示。这些是我的代码。
DeleteServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class deleteuser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw=response.getWriter();
try {
Connection con=Connecter.obtenirconnexion();
Statement st=con.createStatement();
String name=request.getParameter("id");
String Query="delete from users where name ='"+ name+"'";
st.executeUpdate(Query);
pw.print(name);
} catch (SQLException ex) {
Logger.getLogger(deleteuser.class.getName()).log(Level.SEVERE, null, ex);
}
request.getRequestDispatcher("users.jsp").forward(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Users.jsp
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="login.Connecter"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Users</title>
<style> table,td,th
{
border:1px black solid;
} </style>
</head>
<body>
<h1>Hello World</h1>
<%
Connection con = Connecter.obtenirconnexion();
String req = "select * from users";
PreparedStatement pst = con.prepareStatement(req);
ResultSet cur = pst.executeQuery();
out.println("<table ><tr><th>Name</th> <th>Password </th><th>Rank </th><th>Delete </th>");
while (cur.next()) {
out.println("<tr><td>" + cur.getString(1) + "</td><td>" + cur.getString(2) + "</td><td>" + cur.getString(3) + "</td><td> <a href=deleteuser id='"+cur.getString(1)+"'> delete </a></td></tr>");
}
out.println("</table>");
out.close();
%>
</body>
答案 0 :(得分:1)
好吧,删除了DeleteServlet的链接。为了传递请求参数,它应该是:
<a href=deleteuser?id='"+cur.getString(1)+"'> delete </a>
(请注意?
)
但你做的不好。
response.getWriter().print(...)
。你打印的内容将在身体部分之外(甚至在头部之前!):这里你应该把它放在一个请求属性中并在JSP中使用它