写一个代码,在jsp页面提交个人信息和账号密码后,将id、姓名、账号、密码都存储在数据表里,数据库名是stu,数据表名为stu_account,账号对应的属性为account_number,密码对应的属性为password,姓名对应的属性为name,id对应的属性为id,数据库名为root,数据库登录密码为BAIWU2002.
时间: 2024-03-19 20:42:34 浏览: 57
以下是一个基于Java Servlet的示例代码,用于在jsp页面提交个人信息和账号密码后将数据存储到数据库中:
```java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/stu";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "BAIWU2002";
private static final String INSERT_QUERY = "INSERT INTO stu_account (id, name, account_number, password) VALUES (?, ?, ?, ?)";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
String accountNumber = request.getParameter("account_number");
String password = request.getParameter("password");
Connection connection = null;
PreparedStatement statement = null;
try {
Class.forName(DB_DRIVER);
connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
statement = connection.prepareStatement(INSERT_QUERY);
statement.setString(1, id);
statement.setString(2, name);
statement.setString(3, accountNumber);
statement.setString(4, password);
statement.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
response.sendRedirect("login.jsp?register_success=true");
}
}
```
在jsp页面中,需要使用表单来提交个人信息和账号密码,例如:
```html
<form action="RegisterServlet" method="post">
<label for="id">ID:</label>
<input type="text" id="id" name="id"><br>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="account_number">Account Number:</label>
<input type="text" id="account_number" name="account_number"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<input type="submit" value="Submit">
</form>
```
在提交成功后,会自动跳转到登录页面,同时可以通过URL参数`register_success=true`来提示用户注册成功。
阅读全文