JSP(Java Server Pages)是一种动态网页技术,它允许在HTML或XML文档中直接嵌入Java代码片段和表达式。MySQL是一种关系型数据库管理系统,广泛用于Web应用程序的数据存储。
以下是一个简单的JSP登录界面的示例代码,展示了如何连接MySQL数据库并进行用户验证:
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="login.jsp" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
<%-- 处理登录请求 --%>
<%
if (request.getMethod().equalsIgnoreCase("POST")) {
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 加载JDBC驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 连接数据库
String url = "jdbc:mysql://localhost:3306/mydatabase";
String dbUsername = "root";
String dbPassword = "password";
conn = DriverManager.getConnection(url, dbUsername, dbPassword);
// 执行查询
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
if (rs.next()) {
out.println("Login successful!");
} else {
out.println("Invalid username or password.");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
</body>
</html>
PreparedStatement
来防止SQL注入。try-with-resources
语句或在finally
块中关闭资源。希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云