登录与注册功能(简单版)(4)注册时使用Session校验图片验证码

news2024/9/30 13:30:39

目录

1、需求及实现流程分析

2、实现

1)新建register.jsp

2)导入CheckCodeUtil工具类

3)新建CheckCodeServlet

4)修改RegisterServlet

5)启动访问


1、需求及实现流程分析

验证码的作用:防止机器自动注册,攻击服务器。

需求分析:

第一步:展示验证码:展示验证码图片,可以点击切换。
第二步:校验验证码:判断程序生成的验证码和用户输入的验证码是否一致,不一致时阻止注册。

关键思路:

  • 验证码就是Java代码生成的一张图片。
  • 怎样把生成的图片写回到浏览器进行展示 :使用Reponse对象的getOutputStream()方法。
  • 验证码图片访问和提交注册表单是两次请求,需要在一个会话的两次请求之间共享数据,将程序生成的验证码存入到:Session(更安全)。

具体实现流程:

(1)展示验证码:

  • 前端发送请求给CheckCodeServlet
  • CheckCodeServlet接收到请求后,Java工具类生成验证码图片到磁盘上(使用的是OutputStream流)
  • 图片用Reponse对象的输出流写回到前端

(2)校验验证码:

  • 在CheckCodeServlet中生成验证码的时候,将验证码数据存入Session对象
  • 前端将验证码和注册数据提交到后台,交给RegisterServlet类
  • RegisterServlet类接收到请求和数据后,将其中的验证码与Session中的验证码进行对比,如果一致,则完成注册,如果不一致,则提示错误信息

2、实现

1)新建register.jsp

因为要动态生成验证码、访问会话对象存储的验证码信息、在服务器端安全地验证,此功能的实现使用JSP而不是纯HTML。在webapp文件夹下新建register.jsp。

从后台获取生成的验证码图片:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
</head>
<body>
<form action="register" method="post">
    <label for="username">用户名</label>
    <input type="text" id="username" name="username" required><br>

    <label for="password">设置密码:</label>
    <input type="text" id="password" name="password" required><br>

    <label for="checkCodeImg">验证码</label>
    <input type="text" id="checkCode" name="checkCode" required><br>
    <img id="checkCodeImg" src="/understandTomcat/CheckCodeServlet">
    <a href="#" id="changeImg">看不清?</a>
    <%--  href="#" 表示链接不会导向其他页面,而是停留在当前页面。--%>

    <script>
        document.getElementById("changeImg").onclick=function (){
            document.getElementById("checkCodeImg").
        src="/understandTomcat/CheckCodeServlet?"
        +new Date().getMilliseconds();
        //路径后面添加时间戳避免浏览器进行缓存静态资源
        //? 表示查询字符串的开始                                                                                                
        }
    </script>

    <input type="submit" value="注册">
</form>

</body>
</html>

2)导入CheckCodeUtil工具类

新建util文件夹,创建CheckCodeUtil用于生成验证码(直接使用、按提示导包):

/**
 * 生成验证码工具类
 */
public class CheckCodeUtil {
    public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static Random random = new Random();

    /**
     * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
     *
     * @param w
     * @param h
     * @param os
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    /**
     * 使用系统默认字符源生成验证码
     *
     * @param verifySize 验证码长度
     * @return
     */
    public static String generateVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    /**
     * 使用指定源生成验证码
     *
     * @param verifySize 验证码长度
     * @param sources    验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources) {
        // 未设定展示源的字码,赋默认值大写字母+数字
        if (sources == null || sources.length() == 0) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

    /**
     * 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
     *
     * @param w
     * @param h
     * @param outputFile
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    /**
     * 生成指定验证码图像文件
     *
     * @param w
     * @param h
     * @param outputFile
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
        if (outputFile == null) {
            return;
        }
        File dir = outputFile.getParentFile();
        //文件不存在
        if (!dir.exists()) {
            //创建
            dir.mkdirs();
        }
        try {
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch (IOException e) {
            throw e;
        }
    }

    /**
     * 输出指定验证码图片流
     *
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 创建颜色集合,使用java.awt包下的类
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW};
        float[] fractions = new float[colors.length];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);
        // 设置边框色
        g2.setColor(Color.GRAY);
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        // 设置背景色
        g2.setColor(c);
        g2.fillRect(0, 2, w, h - 4);

        // 绘制干扰线
        Random random = new Random();
        // 设置线条的颜色
        g2.setColor(getRandColor(160, 200));
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        // 噪声率
        float yawpRate = 0.05f;
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            // 获取随机颜色
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }
        // 添加图片扭曲
        shear(g2, w, h, c);

        g2.setColor(getRandColor(100, 160));
        int fontSize = h - 4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    /**
     * 随机颜色
     *
     * @param fc
     * @param bc
     * @return
     */
    private static Color getRandColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }
        }
    }
}

3)新建CheckCodeServlet

生成验证码,存入Session:

@WebServlet(name = "/CheckCodeServlet", value = "/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //生成验证码
        ServletOutputStream os=response.getOutputStream();
            //通过Response对象获取字节输出流
        String checkCode= CheckCodeUtil.outputVerifyImage(100,50,os,4);
            //调用CheckCodeUtil工具类的方法:生成一个验证码图片,并将图片数据输出到之前获取的
            //ServletOutputStream对象中。参数:图片的宽度 高度 输出流 验证码中字符的数量

        //存入Session
        HttpSession session=request.getSession();  //获取Session对象
        session.setAttribute("checkCodeGen",checkCode); //存储数据
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

}

4)修改RegisterServlet

获取页面的和session对象中的验证码,进行比对:

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
// 获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");
// 程序生成的验证码,从Session获取
        HttpSession session=request.getSession();
        String checkCodeGen= (String) session.getAttribute("checkCodeGen");

        String resource="mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession =sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User user = userMapper.verityUsername(username);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if (user!=null){
            writer.write("用户已存在");
        }else {

// 比对  
            if (checkCode!=null && checkCodeGen!=null){
                if (!checkCodeGen.equalsIgnoreCase(checkCode)){  
                //先判断非空 否则报空指针
                  writer.write("验证码错误");
// 不允许注册
                    return;
                }
            }

            userMapper.insertUser(username,password);
            //提交事务
            sqlSession.commit();
            //释放资源
            sqlSession.close();
            writer.write("注册成功");
        }
    }
}

5)启动访问

  • 查看验证码图片的显示:

  • 点击看不清,会生成新的图片:

输入用户名、密码、验证码,并点击注册:

  • (1)未注册过的用户名、正确的验证码:

点击注册:

  • (2)未注册过的用户名、错误的验证码:

  • (3)注册过的用户名、正确的验证码:

  • (4)注册过的用户名、错误的验证码:

 

  • 打开navicat,查看user表:

看到注册成功的那条数据已经添加上

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1540752.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Maven,pom.xml,查找 子jar包

在IDEA打开pom.xml&#xff0c;会看到这里&#xff1a; 然后如果有需要&#xff0c;把相关的 子jar包 去掉 <dependency><groupId>XXX</groupId><artifactId>XXX</artifactId><exclusions><exclusion><artifactId>xxx</a…

[java基础揉碎]代码块

目录 基本介绍: 基本语法: 代码块的好处: 1)相当于另外一种形式的构造器(对构造器的补充机制)&#xff0c;可以做初始化的操作 2)场景:如果多个构造器中都有重复的语句&#xff0c;可以抽取到初始化块中&#xff0c;提高代码的重用性 如下: 代码块的注意事项和使用细节: …

详细安装步骤:vue.js 三种方式安装(vue-cli)

Vue.js&#xff08;读音 /vjuː/, 类似于 view&#xff09;是一个构建数据驱动的 web 界面的渐进式框架。Vue.js 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。它不仅易于上手&#xff0c;还便于与第三方库或既有项目整合。 三种 Vue.js 的安装方法&…

探索设计模式的魅力:精准、快速、便捷:游标尺模式在软件设计中的三大优势

​&#x1f308; 个人主页&#xff1a;danci_ &#x1f525; 系列专栏&#xff1a;《设计模式》 &#x1f4aa;&#x1f3fb; 制定明确可量化的目标&#xff0c;并且坚持默默的做事。 精准、快速、便捷&#xff1a;游标尺模式在软件设计中的三大优势 文章目录 一、案例场景&…

化工企业能源在线监测管理系统,智能节能助力生产

化工企业能源消耗量极大&#xff0c;其节能的空间也相对较大&#xff0c;所以需要控制能耗强度&#xff0c;保持更高的能源利用率。 化工企业能源消耗现状 1、能源管理方面 计量能源消耗时&#xff0c;计量器具存在问题&#xff0c;未能对能耗情况实施完全计量&#xff0c;有…

【电气安全】ASCP电气防火限流式保护器/末端回路线路保护

为什么要使用电气防火限流式保护器&#xff1f; 应急管理部消防救援局统计&#xff0c;在造成电气火灾事故的原因中&#xff0c;最为主要的当为末端线路短路&#xff0c;在电气火灾事故中占比高达70%以上。如何效预防末端线路短路引发的电气火灾事故&#xff1f; 现阶段最为常…

逆向爬虫技术的进阶应用与实战技巧

前言 在互联网的海洋中&#xff0c;数据是无价的财富。爬虫技术作为获取这些数据的重要手段&#xff0c;一直备受关注。然而&#xff0c;随着网站反爬虫机制的日益完善&#xff0c;简单的爬虫程序已经很难满足我们的需求。因此&#xff0c;掌握爬虫逆向技术&#xff0c;突破反爬…

【C语言】编译链接

1、宏&#xff08;***&#xff09; 1.1#define定义宏 #define 机制包括了一个规定&#xff0c;允许把参数替换到文本中&#xff0c;这种实现通常称为宏&#xff08;macro&#xff09;或定义 宏&#xff08;define macro&#xff09;。 注意&#xff1a;用于对数值表达式进行求…

React中 类组件 与 函数组件 的区别

类组件 与 函数组件 的区别 1. 类组件2. 函数组件HookuseStateuseEffectuseCallbackuseMemouseContextuseRef 3. 函数组件与类组件的区别3.1 表面差异3.2 最大不同原因 1. 类组件 在React中&#xff0c;类组件就是基于ES6语法&#xff0c;通过继承 React.component 得到的组件…

Linux相关命令(2)

1、W &#xff1a;主要是查看当前登录的用户 在上面这个截图里面呢&#xff0c; 第一列 user &#xff0c;代表登录的用户&#xff0c; 第二列&#xff0c; tty 代表用户登录的终端号&#xff0c;因为在 linux 中并不是只有一个终端的&#xff0c; pts/2 代表是图形界面的第…

01-DBA自学课-安装部署MySQL

一、安装包下载 1&#xff0c;登录官网 MySQL :: MySQL Downloads 2&#xff0c;点击社区版下载 3&#xff0c;找到社区服务版 4&#xff0c;点击“档案”Archives 就是找到历史版本&#xff1b; 5&#xff0c;选择版本进行下载 本次学习&#xff0c;我们使用MySQL-8.0.26版本…

Redis入门到实战-第五弹

Redis实战热身Hashes篇 完整命令参考官网 官网地址 声明: 由于操作系统, 版本更新等原因, 文章所列内容不一定100%复现, 还要以官方信息为准 https://redis.io/Redis概述 Redis是一个开源的&#xff08;采用BSD许可证&#xff09;&#xff0c;用作数据库、缓存、消息代理和…

【Delphi JCL库文件解剖 1】库文件的大体脉络

JCL库是一个开源的Delphi库文件,下载到它很容易,可是想能灵活运用它却并不容易。下面是这个库文件的大体文件脉络,咱们要分析的核心还是在 source 源代码文件。 bin - 示例应用程序可执行文件的常见位置 docs - 读…

qt 实现 轮播图效果,且还有 手动 上一页和下一页 已解决

QT中有 轮播图的需求&#xff0c;按照正常html版本 。只需要配置数组就能搞定&#xff0c;但是c qt版本 应该用什么了。 第一想到的是采用定时器。 // 定时器初始化{m_pTime new QTimer(this);m_pTime->start(4 * 1000);//启动定时器并设置播放时间间隔m_pAutoFlag true;/…

001 高并发内存池_项目简介

​&#x1f308;个人主页&#xff1a;Fan_558 &#x1f525; 系列专栏&#xff1a;高并发内存池 &#x1f339;关注我&#x1f4aa;&#x1f3fb;带你学更多知识 文章目录 前言一、项目简介二、所需知识储备与难度三、什么是内存池四、内存池主要解决的问题 小结 前言 话不多…

MySQL中的数据备份

1. 逻辑备份 备份的是建表、建库、插入等操作所执行SQL语句&#xff0c;适用于中小型数据库&#xff0c;效率相对较低。 本质&#xff1a;导出的是SQL语句文件 优点&#xff1a;不论是什么存储引擎&#xff0c;都可以用mysqldump备成SQL语句 缺点&#xff1a;速度较慢&…

centos7 linux下yum安装redis

安装redis 检查是否有redis yum 源 yum install redis下载fedora的epel仓库 yum install epel-release安装redis数据库 yum install redis安装完毕后&#xff0c;使用下面的命令启动redis服务 # 启动redis service redis start# 停止redis service redis stop# 查看redis运…

隐私计算实训营学习三:隐私计算框架的架构和技术要点

文章目录 一、隐语架构二、产品层三、算法层3.1 PSI与PIR3.2 Data Analysis-SCQL3.3 Federated Learning 四、计算层4.1 混合调度编译-RayFed4.2 密态引擎4.3 密码原语YACL 五、资源管理层六、互联互通七、跨域管控 一、隐语架构 1、完备性&#xff1a;支持多种技术&#xff0…

谷粒商城 - 前端基础

1.前端技术栈 2.ES6 2.1简介 2.2 let 与 const <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Doc…

yolov8目标检测数据集制作——make sense

背景 在前几天我进行了录制视频以准备足够多的数据集&#xff0c;同时使用利用python自定义间隔帧数获取视频转存为图片&#xff0c;所以今天我准备对我要训练的数据集进行标注。我要做的是一个基于yolo的检测项目&#xff0c;在搜索资料后得知大家多是用labelme或者make sens…