我想使用JSPJSP 和 Bootstrap 开发的注册失败页面,当用户名与数据库中已有的内容重复时时会自动跳转回登录页面,
时间: 2023-11-27 12:54:41 浏览: 73
好的,你需要在注册页面中添加一个表单,表单中包含用户名、密码和确认密码等字段,当用户点击注册按钮时,将表单数据通过 AJAX 提交到后端进行处理。后端需要检查用户名是否已经存在于数据库中,如果存在,则返回错误信息,前端需要接收这个错误信息,然后使用 Bootstrap 的弹窗提示用户注册失败,并自动跳转回登录页面。
以下是一个简单的示例代码:
1. 前端代码(register.jsp):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Register</h1>
<form id="register-form">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="mb-3">
<label for="confirm-password" class="form-label">Confirm Password</label>
<input type="password" class="form-control" id="confirm-password" name="confirmPassword" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function() {
$('#register-form').submit(function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'register.do',
data: formData,
success: function(data) {
if (data.success) {
// 注册成功,跳转到登录页面
window.location.href = 'login.jsp';
} else {
// 注册失败,弹出错误信息
$('#register-form').addClass('was-validated');
$('#username').addClass('is-invalid');
$('#username-feedback').text(data.message);
}
},
error: function() {
// 提交失败,弹出错误信息
alert('Failed to submit the form');
}
});
});
});
</script>
</body>
</html>
```
2. 后端代码(RegisterServlet.java):
```java
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private static final String USER = "root";
private static final String PASS = "root";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
String confirmPassword = request.getParameter("confirmPassword");
if (!password.equals(confirmPassword)) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("success", false);
jsonObject.addProperty("message", "The passwords don't match");
PrintWriter out = response.getWriter();
out.write(new Gson().toJson(jsonObject));
return;
}
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
String sql = "SELECT COUNT(*) FROM users WHERE username = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
rs = stmt.executeQuery();
if (rs.next() && rs.getInt(1) > 0) {
// 用户名已存在
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("success", false);
jsonObject.addProperty("message", "The username already exists");
PrintWriter out = response.getWriter();
out.write(new Gson().toJson(jsonObject));
return;
}
sql = "INSERT INTO users (username, password) VALUES (?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
stmt.executeUpdate();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("success", true);
PrintWriter out = response.getWriter();
out.write(new Gson().toJson(jsonObject));
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
// 注册失败
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("success", false);
jsonObject.addProperty("message", "Failed to register");
PrintWriter out = response.getWriter();
out.write(new Gson().toJson(jsonObject));
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在数据库中,需要创建一个名为 `users` 的表,表结构如下:
```sql
CREATE TABLE `users` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
这样,当用户在注册页面输入用户名、密码和确认密码,并点击注册按钮时,就会将表单数据通过 AJAX 提交到后端进行处理。后端会检查用户名是否已经存在于数据库中,如果存在,则返回错误信息;如果不存在,则将用户名和密码插入到数据库中,并返回成功信息。前端接收到后端返回的信息后,根据成功或失败的情况进行相应的处理。
阅读全文