我有一个简单的表单来从用户
获取数据并将其存储到数据库。
这是我的简单表格:
<!DOCTYPE html>
<html>
<head>
<title> Database Insertion Form </title>
</head>
<body>
</body>
<h1>
<center> Phonebook</center>
</h1>
<Form method=post action="DbServlet">
<pre>
Surname: <input type="text" name="Surname">
Forename: <input type="text" name="Forenames">
Phone number: <input type="text" name="PhoneNum">
</pre>
<br><br>
<center><input type="submit" VALUE="Commit"></center>
</Form>
</html>
这是 DbServlet
Servlet:
@WebServlet("/DbServlet")
public class DbServlet extends HttpServlet {
private PreparedStatement ps;
private Connection connection;
private String URL = "jdbc:mysql://localhost/lib";
@Override
public void init() throws ServletException {
super.init();
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(URL, "root", "2323");
} catch (SQLException e) {
e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException {
String surname, forenames, telNum;
surname = request.getParameter("Surname");
forenames = request.getParameter("Forenames");
telNum = request.getParameter("PhoneNum");
response.setContentType("text/HTML");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet + JDBC</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
String query = "INSERT INTO PhoneNums"
+ " VALUES('" + surname + "','"
+ forenames + "','" + telNum + "')";
try {
ps = connection.prepareStatement(query);
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Done");
} catch (SQLException sqle) {
sqle.printStackTrace();
}
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
@Override
public void destroy() {
try {
connection.close();
} catch (Exception ex) {
System.out.println(
"Error on closing database!");
ex.printStackTrace();
System.exit(1);
}
}
}
当我点击 html 表单的submit
按钮时,没有任何反应,甚至出现任何异常!
MySQL 连接器 jar 文件存在于 Tomcat 的 lib 文件夹中。
最佳答案
在您的表格中,您写了 <Form method=post action="DbServlet">
您还没有写""
(双引号)与您的方法名称(post),我想因此尚未为表单定义 post 方法,默认情况下它正在调用 doGet()
servlet 的方法而不是 doPost()
所以这样写:
<form method="post" action="DbServlet">
我想给出的第二个建议是:
当您使用PreparedStatement
时在您的代码中,因此无需管理 '
单引号您自己的查询。
您可以使用?
查询字符串中的问号,然后使用 setXXX
类似 setInt()
的方法或setString
String query = "INSERT INTO PhoneNums VALUES (?, ?, ?)";
ps = connection.prepareStatement(query);
ps.setString(1, surname);
ps.setString(2, forenames);
ps.setString(3, telNum);
ps.executeUpdate();
// I believe all these three are strings
关于java - servlet 中的 JDBC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27523290/