Jquery+Servlet+JDBC实现登录注册功能
以下是一个简化的例子,展示了如何使用jQuery、Servlet和JDBC来实现登录和注册功能。
前端代码(HTML + jQuery)
<!-- 登录表单 -->
<form id="loginForm">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
<!-- 注册表单 -->
<form id="registerForm">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Register</button>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
// 登录提交
$('#loginForm').submit(function(e){
e.preventDefault();
$.post('LoginServlet', $(this).serialize(), function(data){
alert(data);
});
});
// 注册提交
$('#registerForm').submit(function(e){
e.preventDefault();
$.post('RegisterServlet', $(this).serialize(), function(data){
alert(data);
});
});
});
</script>
后端代码(Servlet + JDBC)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
// 登录Servlet
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
PreparedStatement stmt = con.prepareStatement("SELECT * FROM users WHERE username=? AND password=?");
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
response.getWriter().println("Login successful");
} else {
response.getWriter().println("Login failed");
}
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 注册Servlet
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("usern
评论已关闭