Java项目,用户注册登陆和验证码,用代码实现
时间: 2023-08-10 15:13:34 浏览: 49
好的,下面提供一个简单的 Java Web 项目实现用户注册登录和验证码功能的示例代码。
1. 首先,需要创建一个名为 "RegisterLogin" 的 Java Web 项目,并添加以下依赖包:
- servlet-api.jar
- jsp-api.jar
- mysql-connector-java.jar
2. 在项目中创建一个名为 "RegisterServlet" 的 Servlet 类,用于处理用户注册请求。在该类中实现 doPost 方法,代码如下:
```java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
String code = request.getParameter("code");
String checkCode = (String) request.getSession().getAttribute("check_code");
if (!code.equalsIgnoreCase(checkCode)) {
out.print("<script>alert('验证码错误!');window.location='register.jsp';</script>");
return;
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "123456");
String sql = "SELECT * FROM user WHERE username=?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
rs = ps.executeQuery();
if (rs.next()) {
out.print("<script>alert('该用户名已被注册!');window.location='register.jsp';</script>");
return;
}
sql = "INSERT INTO user(username, password, email) VALUES(?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ps.setString(3, email);
ps.executeUpdate();
out.print("<script>alert('注册成功!');window.location='login.jsp';</script>");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException 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();
}
}
}
}
}
```
3. 在项目中创建一个名为 "LoginServlet" 的 Servlet 类,用于处理用户登录请求。在该类中实现 doPost 方法,代码如下:
```java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
String code = request.getParameter("code");
String checkCode = (String) request.getSession().getAttribute("check_code");
if (!code.equalsIgnoreCase(checkCode)) {
out.print("<script>alert('验证码错误!');window.location='login.jsp';</script>");
return;
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "123456");
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()) {
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("index.jsp");
} else {
out.print("<script>alert('用户名或密码错误!');window.location='login.jsp';</script>");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException 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();
}
}
}
}
}
```
4. 在项目中创建一个名为 "CheckCodeServlet" 的 Servlet 类,用于生成验证码图片。在该类中实现 doGet 方法,代码如下:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
Random random = new Random();
g.setColor(Color.BLUE);
for (int i = 0; i < 10; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int index = random.nextInt(chars.length());
char c = chars.charAt(index);
sb.append(c);
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.setFont(new Font("宋体", Font.BOLD, 20));
g.drawString(c + "", 20 * i + 10, 20);
}
HttpSession session = request.getSession();
session.setAttribute("check_code", sb.toString());
ImageIO.write(image, "JPEG", response.getOutputStream());
}
}
```
5. 在项目中创建一个名为 "register.jsp" 的 JSP 页面,用于显示用户注册表单。代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action="RegisterServlet" method="post">
<p>
用户名:<input type="text" name="username" required>
</p>
<p>
密码:<input type="password" name="password" required>
</p>
<p>
邮箱:<input type="email" name="email" required>
</p>
<p>
验证码:<input type="text" name="code" required>
<img src="CheckCodeServlet" onclick="this.src='CheckCodeServlet?'+Math.random();"/>
</p>
<p>
<input type="submit" value="注册">
</p>
</form>
</body>
</html>
```
6. 在项目中创建一个名为 "login.jsp" 的 JSP 页面,用于显示用户登录表单。代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form action="LoginServlet" method="post">
<p>
用户名:<input type="text" name="username" required>
</p>
<p>
密码:<input type="password" name="password" required>
</p>
<p>
验证码:<input type="text" name="code" required>
<img src="CheckCodeServlet" onclick="this.src='CheckCodeServlet?'+Math.random();"/>
</p>
<p>
<input type="submit" value="登录">
</p>
</form>
</body>
</html>
```
7. 在项目中创建一个名为 "index.jsp" 的 JSP 页面,用于显示用户登录后的主页。代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<h1>欢迎您,<%=session.getAttribute("username")%>!</h1>
<p><a href="login.jsp">退出登录</a></p>
</body>
</html>
```
这样,一个简单的 Java Web 项目实现用户注册登录和验证码功能就完成了。