jsp+mysql实现注册登陆并写入数据库代码
时间: 2023-11-06 15:06:57 浏览: 72
以下是 JSP + MySQL 实现注册登录并写入数据库的代码示例:
1. 注册页面 register.jsp
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<h1>注册</h1>
<form action="register.jsp" method="post">
<label>用户名:</label>
<input type="text" name="username"><br><br>
<label>密码:</label>
<input type="password" name="password"><br><br>
<input type="submit" value="注册">
</form>
</body>
</html>
```
2. 注册处理 register.jsp
```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "password");
String sql = "INSERT INTO user(username, password) VALUES(?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
pstmt.executeUpdate();
out.print("注册成功!");
} catch (Exception e) {
e.printStackTrace();
out.print("注册失败!");
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
%>
```
3. 登录页面 login.jsp
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<form action="login.jsp" method="post">
<label>用户名:</label>
<input type="text" name="username"><br><br>
<label>密码:</label>
<input type="password" name="password"><br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
4. 登录处理 login.jsp
```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "password");
String sql = "SELECT * FROM user WHERE username=? AND password=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
if (rs.next()) {
out.print("登录成功!");
} else {
out.print("用户名或密码错误!");
}
} catch (Exception e) {
e.printStackTrace();
out.print("登录失败!");
} finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
%>
```
注意:以上代码仅供参考,具体实现需要根据自己的实际情况进行调整。