• 图形验证码登录


    图形验证码登录

    添加图片标签,进入页面访问/api/verifyCode

    1.html

    <img onclick="javascript:getvCode()" id="verifyimg" style="margin-left: 20px;"/>
    
    
    <script>
    	getvCode();
    			/**
    			 * 获取验证码
    			 * 将验证码写到index.html页面的id = verifyimg 的地方
    			 */
    			function getvCode() {
    				document.getElementById("verifyimg").src = timestamp("/api/verifyCode");
    			}
    			//为url添加时间戳
    			function timestamp(url) {
    				var getTimestamp = new Date().getTime();
    				if (url.indexOf("?") > -1) {
    					url = url + "×tamp=" + getTimestamp
    				} else {
    					url = url + "?timestamp=" + getTimestamp
    				}
    				return url;
    			};
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    2.Controller

    package com.aaa.controller;
    
    import com.aaa.pojo.VerifyCode;
    import com.aaa.service.EmployeeImpl.SimpleCharVerifyCodeGenImpl;
    import com.aaa.service.IVerifyCodeGen;
    import io.swagger.annotations.ApiOperation;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @Controller
    public class verifyCode{
    
    private static final Logger LOGGER = LoggerFactory.getLogger(verifyCode.class);
        String code;
       @ApiOperation(value = "验证码")
       @GetMapping("/verifyCode")
       public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
               IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
    
            try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            code = verifyCode.getCode();
            LOGGER.info(code);
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
            }
            catch (IOException e) {
              LOGGER.info("", e);
               }
    
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    3.验证码实体类

    package com.aaa.pojo;
    import lombok.Data;
    
    /**
     * 验证码类
     */
    @Data
    public class VerifyCode {
    
        private String code;
    
        private byte[] imgBytes;
    
        private long expireTime;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    4.service

    package com.aaa.service;
    import com.aaa.pojo.VerifyCode;
    import java.io.IOException;
    import java.io.OutputStream;
    /**
     * 验证码生成接口
     */
    public interface IVerifyCodeGen {
    
        /**
         * 生成验证码并返回code,将图片写的os中
         *
         * @param width
         * @param height
         * @param os
         * @return
         * @throws IOException
         */
        String generate(int width, int height, OutputStream os) throws IOException;
    
        /**
         * 生成验证码对象
         *
         * @param width
         * @param height
         * @return
         * @throws IOException
         */
        VerifyCode generate(int width, int height) throws IOException;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    5.serviceImpl

    package com.aaa.service.EmployeeImpl;
    import com.aaa.pojo.VerifyCode;
    import com.aaa.service.IVerifyCodeGen;
    import com.aaa.util.RandomUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Service;
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Random;
    
    /**
     * 验证码实现类
     */
    @Service
    public class SimpleCharVerifyCodeGenImpl implements IVerifyCodeGen {
    
        private static final Logger logger = LoggerFactory.getLogger(SimpleCharVerifyCodeGenImpl.class);
    
        private static final String[] FONT_TYPES = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" };
    
        private static final int VALICATE_CODE_LENGTH = 4;
    
        /**
         * 设置背景颜色及大小,干扰线
         *
         * @param graphics
         * @param width
         * @param height
         */
        private static void fillBackground(Graphics graphics, int width, int height) {
            // 填充背景
            graphics.setColor(Color.WHITE);
            //设置矩形坐标x y 为0
            graphics.fillRect(0, 0, width, height);
    
            // 加入干扰线条
            for (int i = 0; i < 8; i++) {
                //设置随机颜色算法参数
                graphics.setColor(RandomUtils.randomColor(40, 150));
                Random random = new Random();
                int x = random.nextInt(width);
                int y = random.nextInt(height);
                int x1 = random.nextInt(width);
                int y1 = random.nextInt(height);
                graphics.drawLine(x, y, x1, y1);
            }
        }
    
        /**
         * 生成随机字符
         *
         * @param width
         * @param height
         * @param os
         * @return
         * @throws IOException
         */
        @Override
        public String generate(int width, int height, OutputStream os) throws IOException {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics graphics = image.getGraphics();
            fillBackground(graphics, width, height);
            String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH);
            createCharacter(graphics, randomStr);
            graphics.dispose();
            //设置JPEG格式
            ImageIO.write(image, "JPEG", os);
            return randomStr;
        }
    
        /**
         * 验证码生成
         *
         * @param width
         * @param height
         * @return
         */
        @Override
        public VerifyCode generate(int width, int height) {
            VerifyCode verifyCode = null;
            try {
                //将流的初始化放到这里就不需要手动关闭流
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                String code = generate(width, height, baos);
                verifyCode = new VerifyCode();
                verifyCode.setCode(code);
                verifyCode.setImgBytes(baos.toByteArray());
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                verifyCode = null;
            }
            return verifyCode;
        }
        /**
         * 设置字符颜色大小
         *
         * @param g
         * @param randomStr
         */
        private void createCharacter(Graphics g, String randomStr) {
            char[] charArray = randomStr.toCharArray();
            for (int i = 0; i < charArray.length; i++) {
                //设置RGB颜色算法参数
                g.setColor(new Color(50 + RandomUtils.nextInt(100),
                        50 + RandomUtils.nextInt(100), 50 + RandomUtils.nextInt(100)));
                //设置字体大小,类型
                g.setFont(new Font(FONT_TYPES[RandomUtils.nextInt(FONT_TYPES.length)], Font.BOLD, 26));
                //设置x y 坐标
                g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextInt(8));
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117

    6.实现效果

    在这里插入图片描述
    右侧验证码显示效果,点击图片可以换图

  • 相关阅读:
    无线设备的天线怎么安装最好?
    spring6-IOC容器
    给定DNA序列,查找有效匹配子串
    Hadoop的安装和使用,Windows使用shell命令简单操作HDFS
    【图像分类】MMPretrain训练ImageNet格式自定义数据集
    pyqt5 嵌入WEB 并实现qt向web的通信
    【MFC】打砖块小游戏(上)(5)
    中国机器人产业崛起,德国市场面临30%的份额挑战
    C++算法题 - 矩阵
    北斗导航 | 基于GPS/BDS多星座加权因子图优化的行人智能手机导航
  • 原文地址:https://blog.csdn.net/g877835148/article/details/134299051