jsp登录注册页面代码
时间: 2023-08-19 08:05:48 浏览: 39
这里是一个简单的 JSP 登录注册页面代码示例:
登录页面代码:
```jsp
<html>
<head>
<title>登录页面</title>
</head>
<body>
<h1>登录</h1>
<form method="post" action="login.jsp">
用户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
```
登录处理代码 login.jsp:
```jsp
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
String sql = "select * from user where username = ? and password = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
if (rs.next()) {
session.setAttribute("username", username);
response.sendRedirect("home.jsp");
} else {
out.println("用户名或密码错误!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
```
注册页面代码:
```jsp
<html>
<head>
<title>注册页面</title>
</head>
<body>
<h1>注册</h1>
<form method="post" action="register.jsp">
用户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
确认密码:<input type="password" name="confirm_password"/><br/>
<input type="submit" value="注册"/>
</form>
</body>
</html>
```
注册处理代码 register.jsp:
```jsp
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String confirm_password = request.getParameter("confirm_password");
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
String sql = "insert into user(username, password) values(?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
if (password.equals(confirm_password)) {
ps.executeUpdate();
session.setAttribute("username", username);
response.sendRedirect("home.jsp");
} else {
out.println("两次密码不一致!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
```
注意:上述代码仅供参考,实际开发中需要根据具体需求进行修改和完善。同时,为了安全起见,密码应该进行加密存储,代码中也应该加入相应的安全措施。