JSP(JavaServer Pages)是一种用于创建动态Web内容的技术,它允许开发者在HTML页面中嵌入Java代码。下面是一个简单的JSP登录和注册页面的示例代码。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="authenticate.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 contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Register</title>
</head>
<body>
<h2>Register</h2>
<form action="registerProcess.jsp" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
Email: <input type="email" name="email"><br><br>
<input type="submit" value="Register">
</form>
</body>
</html><%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
// 这里应该使用预编译语句来防止SQL注入
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
pstmt = conn.prepareStatement("SELECT * FROM users WHERE username=? AND password=?");
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
if (rs.next()) {
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
} else {
out.println("Invalid login credentials. Please try again.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try { if (rs != null) rs.close(); } catch (Exception e) {}
try { if (pstmt != null) pstmt.close(); } catch (Exception e) {}
try { if (conn != null) conn.close(); } catch (Exception e) {}
}
%><%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
pstmt = conn.prepareStatement("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
pstmt.setString(1, username);
pstmt.setString(2, password);
pstmt.setString(3, email);
pstmt.executeUpdate();
response.sendRedirect("login.jsp");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try { if (pstmt != null) pstmt.close(); } catch (Exception e) {}
try { if (conn != null) conn.close(); } catch (Exception e) {}
}
%>这些示例代码提供了一个基本的登录和注册功能的起点,但在实际部署之前,需要进行更多的安全性和性能优化。
没有搜到相关的文章