用户注册功能实现,在HTML页面输入账户名称和密码,在Servlet程序中获取,最后放到数据库中实现
时间: 2024-04-30 16:23:38 浏览: 15
1. 首先创建一个HTML页面,包含一个表单用于输入账户名称和密码,并提交到Servlet程序中。
```html
<!DOCTYPE html>
<html>
<head>
<title>User Registration Form</title>
</head>
<body>
<h1>User Registration Form</h1>
<form action="register" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
```
2. 创建一个Servlet程序,用于处理表单提交,并将账户名称和密码保存到数据库中。
```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;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement stmt = null;
try {
// Connect to database
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
// Insert new user into database
String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
stmt.executeUpdate();
response.sendRedirect("success.html"); // Redirect to success page
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
response.sendRedirect("error.html"); // Redirect to error page
} finally {
try {
if(stmt != null) stmt.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
3. 在MySQL数据库中创建一个名为"mydb"的数据库,并在其中创建一个名为"users"的表,用于存储账户名称和密码。
```sql
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE users (
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
```
4. 将MySQL JDBC驱动程序添加到项目的类路径中,以便在Servlet程序中使用它。
5. 运行项目,并通过浏览器访问注册页面。输入账户名称和密码,提交表单后,Servlet程序将会将其保存到数据库中。