springboot和session实现验证码功能

Posted 西红柿里没有番茄

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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");

    }


}

以上是关于springboot和session实现验证码功能的主要内容,如果未能解决你的问题,请参考以下文章

PHP JS CSS session实现验证码功能

Springboot使用session容器存取短信验证码

Redis实战之Session实现短信登录以及Redis完善登录功能

SpringBoot+Vue项目中实现登录验证码校验

基于SessionRedis 短信登录功能实现,解决Session共享,登录状态刷新问题及Threadlocal线程隔离

从session实现机制分析模拟请求验证码的可行性(转)