JSP(JavaServer Pages)是一种用于创建动态Web页面的技术,它允许开发者在HTML或XML等静态页面中嵌入Java代码。以下是一个简单的JSP登录代码示例,包括前端表单和后端处理逻辑。
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="loginProcess.jsp" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
// 假设数据库连接信息
String url = "jdbc:mysql://localhost:3306/mydatabase";
String dbUsername = "root";
String dbPassword = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
String sql = "SELECT * FROM users WHERE username=? AND password=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
// 登录成功
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
} else {
// 登录失败
response.sendRedirect("login.jsp?error=1");
}
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect("login.jsp?error=2");
}
%>
<%
String username = (String) session.getAttribute("username");
if (username != null) {
out.println("<h2>Welcome, " + username + "!</h2>");
} else {
response.sendRedirect("login.jsp");
}
%>
通过以上示例和解释,希望能帮助你理解JSP登录代码的基本结构和常见问题解决方法。
领取专属 10元无门槛券
手把手带您无忧上云