案例一:包含验证码登录案例
1、需求
1. 访问带有验证码的登录页面login.jsp
2. 用户输入用户名,密码以及验证码。
如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误
如果验证码输入有误,跳转登录页面,提示:验证码错误
如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您
2、分析:
3、login.jsp 页面
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>登录</title>
6 <script>
7
8 window.onloa = function() {
9 // 刷新验证码
10 document.getElementById("img").onclick = function() {
11 this.src = "/day13/checkcodeservletdemo"+new Date().getTime();
12 }
13 }
14 </script>
15 <style>
16
17 div {
18 color:red;
19 }
20 </style>
21
22 <body>
23 <form action="/day13/loginservletdemo" method="post">
24 <table>
25 <tr>
26 <td>用户名</td>
27 <td><input type="text" name="username"></td>
28 </tr>
29
30 <tr>
31 <td>密码</td>
32 <td><input type="password" name="password"></td>
33 </tr>
34
35 <tr>
36 <td>验证码</td>
37 <td><input type="text" name="checkcode"></td>
38 </tr>
39
40 <tr>
41 <td colspan="2"><img id="img" src="/day13/checkcodeservletdemo"></td>
42 </tr>
43
44 <tr>
45 <td colspan="2"><input type="submit" value="登录"></td>
46 </tr>
47 </table>
48
49 <div><%=request.getAttribute("cc_error") == null ? "":request.getAttribute("cc_error") %></div>
50 <div><%=request.getAttribute("login_error") == null ? "":request.getAttribute("login_error") %></div>
51
52 </form>
53 </body>
54 </html>
4、success 页面
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 <html>
3 <head>
4 <title>登录成功</title>
5 </head>
6 <body>
7 <h1><%=request.getSession().getAttribute("user")%>,欢迎您</h1>
8
9 </body>
10 </html>
5、生成验证码 servlet
1 import javax.imageio.ImageIO;
2 import javax.servlet.ServletException;
3 import javax.servlet.annotation.WebServlet;
4 import javax.servlet.http.HttpServlet;
5 import javax.servlet.http.HttpServletRequest;
6 import javax.servlet.http.HttpServletResponse;
7 import java.awt.*;
8 import java.awt.image.BufferedImage;
9 import java.io.IOException;
10 import java.util.Random;
11
12 @WebServlet("/checkcodeservletdemo")
13 public class CheckCodeServlet extends HttpServlet {
14 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
15
16 // 定义图片的宽高
17 int width = 100;
18 int height = 50;
19
20 // 1 创建对象,在内存中生成图片(验证码图片对象)
21 BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
22
23 // 2 修饰图片
24 // 2.1 填充背景色
25 Graphics g = image.getGraphics(); //获取画笔对象
26 g.setColor(Color.pink); // 设置画笔颜色
27 g.fillRect(0,0,width,height); // 绘制一个矩形,给定坐标与宽高
28
29 // 2.2 画边框
30 g.setColor(Color.blue); // 设置画笔颜色
31 g.drawRect(0,0,width-1,height-1); // 给图像绘制边框
32
33 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
34 //生成随机角标
35 Random ran = new Random();
36
37 StringBuilder sb = new StringBuilder();
38 for (int i = 1; i <= 4; i++) {
39 int index = ran.nextInt(str.length());
40 //获取字符
41 char ch = str.charAt(index);//随机字符
42 sb.append(ch);
43
44
45 //2.3写验证码
46 g.drawString(ch+"",width/5*i,height/2);
47 }
48
49 String checkCode_session = sb.toString();
50 // 将验证码存入 session
51 request.getSession().setAttribute("checkCode_session",checkCode_session);
52
53 //2.4画干扰线
54 g.setColor(Color.GREEN);
55
56 // 随机生成坐标点
57
58 for (int i = 0; i < 6; i++) {
59 int x1 = ran.nextInt(width);
60 int x2 = ran.nextInt(width);
61
62 int y1 = ran.nextInt(height);
63 int y2 = ran.nextInt(height);
64 g.drawLine(x1,y1,x2,y2); // 画干扰线
65 }
66
67
68 // 3 将图片输出到页面展示:通过response 的 字符流,将图片输出到浏览器上
69 ImageIO.write(image,"jpg",response.getOutputStream());
70 }
71
72 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
73 this.doPost(request, response);
74 }
75 }
6、登录 servlet
1 import javax.servlet.ServletException;
2 import javax.servlet.annotation.WebServlet;
3 import javax.servlet.http.HttpServlet;
4 import javax.servlet.http.HttpServletRequest;
5 import javax.servlet.http.HttpServletResponse;
6 import javax.servlet.http.HttpSession;
7 import java.io.IOException;
8
9 @WebServlet("/loginservletdemo")
10 public class LoginServlet extends HttpServlet {
11 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
12 // 1. 设置编码
13 request.setCharacterEncoding("utf-8");
14 // 2. 获取参数
15 //Map<String, String[]> map = request.getParameterMap();
16
17 String username = request.getParameter("username");
18 String password = request.getParameter("password");
19 String checkcode = request.getParameter("checkcode");
20
21 // 3.先判断验证码是否正确
22 // 获取生成验证码
23 HttpSession session = request.getSession();
24 String checkCode_session = (String) session.getAttribute("checkCode_session");
25 // 删除 session中存储的验证码
26 session.removeAttribute("checkCode_session");
27
28 // 判断,忽略大小写
29 if(checkCode_session!= null && checkCode_session.equalsIgnoreCase(checkcode)) {
30 //验证码正确
31 // 判断用户名和密码是否一致
32 if("zhangsan".equals(username) && "123".equals(password)) {
33 // 登录成功
34 // 存储用户信息
35
36 session.setAttribute("user",username);
37 // 重定向到 success.jsp
38 response.sendRedirect(request.getContextPath()+"/success.jsp");
39 }else {
40 // 存储提示信息到request
41 request.setAttribute("login_error","用户名或密码错误");
42 request.getRequestDispatcher("/login.jsp").forward(request,response);
43 }
44
45 } else {
46 // 验证码不正确
47 // 存储提示信息到request
48 request.setAttribute("cc_error","验证码错误");
49 request.getRequestDispatcher("/login.jsp").forward(request,response);
50 }
51
52 }
53
54 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
55 this.doPost(request, response);
56 }
57 }
案例二:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现