JavaWeb16.7【Cookie&Session:案例-登录验证码】

 

 

 

 

 

 

 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: yubaby
 4   Date: 2021/7/3
 5   Time: 12:32
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10 <head>
11     <title>Title</title>
12     
13     <script>
14         window.onload = function () {
15             document.getElementById("img").onclick = function () {
16                 var timeStamp = new Date().getTime();
17                 this.src = "/day16/checkCodeServlet?time=" + timeStamp;
18                 //this即通过document.getElementById("img")获取到的对象
19             }
20         }
21     </script>
22     <style>
23         div{
24             color: red;
25         }
26     </style>
27 </head>
28 <body>
29 
30     <form action="/day16/LoginServlet" method="post">
31         <table>
32             <tr>
33                 <td>用户名</td>
34                 <td><input type="text" name="username"></td>
35             </tr>
36             <tr>
37                 <td>密码</td>
38                 <td><input type="password" name="password"></td>
39             </tr>
40             <tr>
41                 <td>验证码</td>
42                 <td><input type="text" name="checkCode"></td>
43             </tr>
44             <tr>
45                 <td colspan="2"><img id="img" src="/day16/checkCodeServlet"></td>
46             </tr>
47             <tr>
48                 <td colspan="2"><input type="submit" value="登录"></td>
49             </tr>
50         </table>
51     </form>
52 
53     <div><%=request.getAttribute("cc_error")==null ? "" : request.getAttribute("cc_error")%></div>
54     <div><%=request.getAttribute("login_error")==null ? "" : request.getAttribute("login_error")%></div>
55 </body>
56 </html>
 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: yubaby
 4   Date: 2021/7/3
 5   Time: 13:28
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10 <head>
11     <title>Title</title>
12 </head>
13 <body>
14     <h1><%=request.getSession().getAttribute("user")%>,欢迎您</h1>
15 </body>
16 </html>
 1 package com.haifei.servlet;
 2 
 3 import javax.servlet.ServletException;
 4 import javax.servlet.annotation.WebServlet;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import javax.servlet.http.HttpSession;
 9 import java.io.IOException;
10 import java.util.Map;
11 
12 /**
13  * session案例-登录验证码
14  */
15 @WebServlet("/LoginServlet")
16 public class LoginServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         //1 设置request编码
19         request.setCharacterEncoding("utf-8");
20         //2 获取参数集合
21         /*Map<String, String[]> parameterMap = request.getParameterMap();
22         for (String key: parameterMap.keySet()) {
23             String[] value = parameterMap.get(key);
24             System.out.println(key + ":" + value);
25         }*/
26         String username = request.getParameter("username");
27         String password = request.getParameter("password");
28         String checkCode = request.getParameter("checkCode");
29 
30         //3 判断用户输入的验证码是否正确
31         //========================================
32         //获取checkCodeServlet生成的验证码
33         HttpSession session = request.getSession();
34 //        Object checkCodeTruth = session.getAttribute("checkCodeTruth");
35         String checkCodeTruth = (String)session.getAttribute("checkCodeTruth"); //需要强转为字符串类型,不然equalsIgnoreCase报错
36         //用完之后立即删除session中存储的验证码,增强安全性(保证验证码的一次性使用)
37         session.removeAttribute("checkCodeTruth");
38         //========================================
39         if (checkCodeTruth!=null && checkCodeTruth.equalsIgnoreCase(checkCode)){ //忽略大小写比较字符串方法
40             //一致,用户输入验证码正确
41 
42             //判断用户输入的用户名和密码是否正确
43             if ("zhangsan".equals(username) && "123".equals(password)){ //此处实际应该调用UserDao查询数据库数据
44                 //登录成功
45 
46                 //存储用户信息
47                 session.setAttribute("user", username); //此处实际应该传入查询出来的user对象
48                 //重定向到success.jsp
49                 response.sendRedirect(request.getContextPath() + "/success.jsp");
50             }else {
51                 //登录失败
52 
53                 //存储提示信息到request
54                 request.setAttribute("login_error", "用户名或密码错误");
55                 //转发到登录页面
56                 request.getRequestDispatcher("/login.jsp").forward(request, response);
57             }
58 
59         }else {
60             //不一致,用户输入验证码不正确
61 
62             //存储提示信息到request
63             request.setAttribute("cc_error", "验证码错误");
64             //转发到登录页面
65             request.getRequestDispatcher("/login.jsp").forward(request, response);
66         }
67 
68     }
69 
70     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
71         this.doPost(request, response);
72     }
73 }
 1 package com.haifei.servlet;
 2 
 3 import javax.imageio.ImageIO;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.annotation.WebServlet;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 import javax.servlet.http.HttpSession;
10 import java.awt.*;
11 import java.awt.image.BufferedImage;
12 import java.io.IOException;
13 import java.util.Random;
14 
15 /**
16  * Response对象案例-验证码
17  */
18 @WebServlet("/checkCodeServlet")
19 public class CheckCodeServlet extends HttpServlet {
20     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
21         int width = 100;
22         int height = 50;
23 
24         //1 创建对象,再内存中画图(验证码图片对象)
25         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
26 
27         //2 美化图片
28         //2.1 填充背景色
29         Graphics g = image.getGraphics();//画笔对象
30         g.setColor(Color.PINK);//设置画笔颜色
31         g.fillRect(0,0,width,height);
32         //2.2画边框
33         g.setColor(Color.BLUE);
34         g.drawRect(0,0,width - 1,height - 1);
35         //2.3画验证码
36         String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
37         Random ran = new Random();
38         //========================================
39         StringBuilder sb = new StringBuilder();
40         //========================================
41         for (int i = 1; i <= 4; i++) {
42             //生成随机下标
43             int index = ran.nextInt(str.length());
44             //获取随机字符
45             char ch = str.charAt(index);
46             sb.append(ch);
47 
48             //写验证码
49             g.drawString(ch+"",width/5*i,height/2);
50         }
51         //========================================
52         String checkCodeTruth = sb.toString();
53         //将生成的验证码存入session
54         HttpSession session = request.getSession();
55         session.setAttribute("checkCodeTruth", checkCodeTruth);
56         //========================================
57 
58         //2.4画干扰线
59         g.setColor(Color.GREEN);
60         for (int i = 0; i < 10; i++) { //随机生成坐标点
61             int x1 = ran.nextInt(width);
62             int x2 = ran.nextInt(width);
63             int y1 = ran.nextInt(height);
64             int y2 = ran.nextInt(height);
65             g.drawLine(x1,y1,x2,y2);
66         }
67 
68         //3 将图片输出到页面展示
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 }

 

 

 

 

 

 

 

 

 

 

posted @ 2021-07-03 13:53  yub4by  阅读(75)  评论(0编辑  收藏  举报