• springboot和session实现验证码功能


    先搞定一个验证码生成类

    package com.example.testsession.util;
    
    
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.util.Random;
    
    /**
     * 生成4个字符的验证码,背景颜色、字体颜色、字体类型都随机生成,另外加上干扰线条
     */
    
    public class VerifyCode {
    
        private Random random = new Random();
        private int width = 100;// 生成验证码图片的宽度
        private int height = 30;// 生成验证码图片的高度
        //    字体
        private String[] fontNames = {"宋体", "楷体", "隶书", "微软雅黑"};
        //    背景颜色
        private Color bgColor = new Color(255, 255, 255);
        //    从下面的字符串中挑选字符放入验证码集中
        private String codes = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
        //    记录随机字符串
        private String text;
    
        public VerifyCode() {
            getVerifyCode();
        }
    
        /**
         * 获得一个随机颜色
         *
         * @return
         */
        private Color randomColor() {
            int red = random.nextInt(150);
            int green = random.nextInt(150);
            int blue = random.nextInt(150);
            return new Color(red, green, blue);
        }
    
        /**
         * 获得一个随机字体
         *
         * @return
         */
        private Font randomFont() {
            String name = fontNames[random.nextInt(fontNames.length)];
            int style = random.nextInt(4);
            int size = random.nextInt(5) + 24;
            return new Font(name, style, size);
        }
    
        /**
         * 获得一个随机字符
         *
         * @return
         */
        private char randomChar() {
            return codes.charAt(random.nextInt(codes.length()));
        }
    
        /**
         * BufferedImage
         * 验证码背景图
         *
         * @return
         */
        private BufferedImage createImage() {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = (Graphics2D) image.getGraphics();
            g2.setColor(bgColor);// 设置验证码图片的背景颜色
            g2.fillRect(0, 0, width, height);
            return image;
        }
    
        /**
         * 给图片添加干扰线条
         *
         * @param image
         */
        private void drawLine(BufferedImage image) {
            Graphics2D g2 = (Graphics2D) image.getGraphics();
            int num = 5;
            for (int i = 0; i < num; i++) {
                int x1 = random.nextInt(width);
                int y1 = random.nextInt(height);
                int x2 = random.nextInt(width);
                int y2 = random.nextInt(height);
                g2.setColor(randomColor());
                g2.setStroke(new BasicStroke(1.5f));
                g2.drawLine(x1, y1, x2, y2);
            }
        }
    
        /**
         * 得到验证码图片
         *
         * @return
         */
        public BufferedImage getVerifyCode() {
            BufferedImage image = createImage();
            Graphics2D g2 = (Graphics2D) image.getGraphics();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 4; i++) {
    //            字符
                String s = randomChar() + "";
                sb.append(s);
    //            字符属性
                g2.setColor(randomColor());
                g2.setFont(randomFont());
                float x = i * width * 1.0f / 4;
                g2.drawString(s, x, height - 8);
            }
            this.text = sb.toString();
            drawLine(image);
            return image;
        }
    
        public String getText() {
            return text;
        }
    
        public void setText(String text) {
            this.text = text;
        }
    
    
    }
    
    

    前端第一次发起请求:生成验证码图片并生成一个session;前端第二次发起请求:接收前端的cookie和验证码值

    package com.example.testsession.controller;
    
    import com.example.testsession.util.VerifyCode;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.imageio.ImageIO;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    
    @RestController
    public class VerifyCodeController {
    
        VerifyCode verifyCode = new VerifyCode();
    
        @Autowired
        HttpServletRequest httpServletRequest;
    
        @Autowired
        HttpServletResponse httpServletResponse;
    
    
        /**
         * 生成验证码图片
         *
         * @throws IOException
         */
        @RequestMapping("/getVerifyIma")
        public void getVerifyIma() throws IOException {
    
    //        设置响应的信息类型
            httpServletResponse.setContentType("image/png");
    
    //        验证码
            VerifyCode verifyCode = new VerifyCode();
            BufferedImage bufferedImage = verifyCode.getVerifyCode();
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", baos);
            baos.flush();
            byte[] imageInByte = baos.toByteArray();
            baos.close();
    
    //        session处理
            HttpSession mySession = httpServletRequest.getSession();
            mySession.setAttribute("verifycode", verifyCode.getText());
    
            OutputStream stream = httpServletResponse.getOutputStream();
            stream.write(imageInByte);
    //        清空
            stream.flush();
    //        关闭
            stream.close();
    
        }
    
        /**
         * 得到前端session中返回的验证码
         */
        @RequestMapping("/getVerifyCode")
        public void getVerifyCode() {
            HttpSession mySession = httpServletRequest.getSession(false);
            String vCode = (String) mySession.getAttribute("verifycode");
    
        }
    
    
    }
    
    
  • 相关阅读:
    一道编程题: 在1~n之间选择若干个数,使其和为m
    关于raft算法
    程序员算法基础——动态规划
    c++中两个类互相引用的问题
    c++ 之模板进阶
    jmeter分布式操作-远程启动功能探索
    linux下安装不同版本的jdk
    Jmeter插件监控服务器性能
    测试开发面试-技术持续累积
    python:Jpype安装和使用
  • 原文地址:https://www.cnblogs.com/lyd447113735/p/14876334.html
Copyright © 2020-2023  润新知