欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot 图形验证码的生成和校验

程序员文章站 2022-03-26 14:54:18
1. 编写工具类package com.cn.beauty.util;import org.slf4j.logger;import org.slf4j.loggerfactory;import jav...

1. 编写工具类

package com.cn.beauty.util;

import org.slf4j.logger;
import org.slf4j.loggerfactory;

import javax.imageio.imageio;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.util.arraylist;
import java.util.random;

public class randomvalidatecodeutil {
    public static final string randomcodekey = "meishang-login-randomvalidatecodekey";//放到session中的key
    private string randstring = "0123456789abcdefghijklmnopqrstuvwxyz";//随机产生数字与字母组合的字符串
    private int width = 95;// 图片宽
    private int height = 40;// 图片高
    private int stringnum = 4;// 随机产生字符数量
    private static final logger logger = loggerfactory.getlogger(randomvalidatecodeutil.class);
    private random random = new random();

    /**
     * 获得字体
     */
    private font getfont() {
        return new font("wide latin", font.plain, 18);
    }

    /**
     * 获得颜色(粉色为主)
     */
    private color getrandcolor() {
        arraylist<color> colors = new arraylist<color>();
        colors.add(new color(241, 158, 194));
        colors.add(new color(255, 94, 226));
        colors.add(new color(255, 156, 177));
        colors.add(new color(245, 152, 217));
        colors.add(new color(255, 85, 81));
        colors.add(new color(245, 152, 251));
        int num = random.nextint(6);
        return colors.get(num);
    }

    /**
     * 生成随机图片
     */
    public void getrandcode(httpservletrequest request, httpservletresponse response) {
        httpsession session = request.getsession();
        // bufferedimage类是具有缓冲区的image类,image类是用于描述图像信息的类
        bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_bgr);
        graphics g = image.getgraphics();// 产生image对象的graphics对象,改对象可以在图像上进行各种绘制操作
        g.fillrect(0, 0, width, height);//图片大小
        g.setfont(new font("wide latin", font.plain, 18));//字体大小
        g.setcolor(getrandcolor());//字体颜色

        // 添加噪点
        float yawprate = 0.01f;// 噪声率
        int area = (int) (yawprate * width * height);
        for (int i = 0; i < area; i++) {
            int x = random.nextint(width);
            int y = random.nextint(height);
            image.setrgb(x, y, random.nextint(255));
        }

        // 绘制随机字符
        string randomstring = "";
        for (int i = 1; i <= stringnum; i++) {
            randomstring = drowstring(g, randomstring, i);
        }
        logger.info(randomstring);
        //将生成的随机字符串保存到session中
        session.removeattribute(randomcodekey);
        session.setattribute(randomcodekey, randomstring);
        g.dispose();
        try {
            // 将内存中的图片通过流动形式输出到客户端
            imageio.write(image, "jpeg", response.getoutputstream());
        } catch (exception e) {
            logger.error("将内存中的图片通过流动形式输出到客户端失败>>>>   ", e);
        }

    }

    /**
     * 绘制字符串
     */
    private string drowstring(graphics g, string randomstring, int i) {
        g.setfont(getfont());
        g.setcolor(getrandcolor());
        string rand = string.valueof(getrandomstring(random.nextint(randstring
                .length())));
        randomstring += rand;
        g.translate(random.nextint(3), random.nextint(3));
        g.drawstring(rand, 20 * (i - 1) + 3, 25);
        return randomstring;
    }

    /**
     * 获取随机的字符
     */
    public string getrandomstring(int num) {
        return string.valueof(randstring.charat(num));
    }
}

2. 编写 controller 中的接口

	/**
	 * @description 生成验证码
	 */
	@requestmapping(value = "/user/getverify")
	public void getverify(httpservletrequest request, httpservletresponse response) {
	    try {
	        //设置相应类型,告诉浏览器输出的内容为图片
	        response.setcontenttype("image/jpeg");
	        //设置响应头信息,告诉浏览器不要缓存此内容
	        response.setheader("pragma", "no-cache");
	        response.setheader("cache-control", "no-cache");
	        response.setdateheader("expire", 0);
	        randomvalidatecodeutil randomvalidatecode = new randomvalidatecodeutil();
	        //输出验证码图片方法
	        randomvalidatecode.getrandcode(request, response);
	    } catch (exception e) {
	        log.error("获取验证码失败>>>>", e);
	    }
	}
	
	/**
	 * @description 校验验证码
	 */
	@postmapping("/user/checkverify")
	public boolean checkverify(@requestparam string verifyinput, httpsession session) {
	    try {
	        // 从session中获取随机数
	        string inputstr = verifyinput;
	        string random = (string) session.getattribute("meishang-login-randomvalidatecodekey");
	        if (random == null) {
	            return false;
	        }
	        if (random.equalsignorecase(inputstr)) {
	            return true;
	        } else {
	            return false;
	        }
	    } catch (exception e) {
	        log.error("验证码校验失败", e);
	        return false;
	    }
	}

3. 获取验证码图片

访问获取验证码接口

http://127.0.0.1:8605/user/getverify

效果如下

SpringBoot 图形验证码的生成和校验

另一种方法

1.添加依赖

<dependency>
            <groupid>com.github.penggle</groupid>
            <artifactid>kaptcha</artifactid>
            <version>2.3.2</version>
        </dependency>
        
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>

项目结构

SpringBoot 图形验证码的生成和校验

2.全部代码

usercontroller

package com.yzm.config;

import java.util.hashmap;

import javax.annotation.resource;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.responsebody;

import com.google.code.kaptcha.impl.defaultkaptcha;
import com.yzm.utils.util;

@controller
public class testcontroler {
 
    @resource
    private defaultkaptcha captchaproducer;
    /**
     * 登录验证码sessionkey
     */
    public static final string login_validate_code = "login_validate_code";
    /**
     * 登录验证码图片
     */
    @requestmapping(value = {"/loginvalidatecode"})
    public void loginvalidatecode(httpservletrequest request, httpservletresponse response) throws exception{
        util.validatecode(request,response,captchaproducer,login_validate_code);
    }
 
    /**
     * 检查验证码是否正确
     */
    @requestmapping("/checkloginvalidatecode")
    @responsebody
    public hashmap checkloginvalidatecode(httpservletrequest request,@requestparam("validatecode")string validatecode) {
        string loginvalidatecode = request.getsession().getattribute(login_validate_code).tostring();
        hashmap<string,object> map = new hashmap<string,object>();
        if(loginvalidatecode == null){
            map.put("status",null);//验证码过期
        }else if(loginvalidatecode.equals(validatecode)){
            map.put("status",true);//验证码正确
        }else if(!loginvalidatecode.equals(validatecode)){
            map.put("status",false);//验证码不正确
        }
        map.put("code",200);
        return map;
    }
}
package com.yzm.controller;

import java.util.properties;

import org.springframework.context.annotation.bean;
import org.springframework.stereotype.component;

import com.google.code.kaptcha.impl.defaultkaptcha;
import com.google.code.kaptcha.util.config;

@component
public class testconfig {
 
    @bean
    public defaultkaptcha getdefaultkaptcha() {
        defaultkaptcha defaultkaptcha = new defaultkaptcha();
        properties properties = new properties();
        // 图片边框
        properties.setproperty("kaptcha.border", "no");
        // 边框颜色
        properties.setproperty("kaptcha.border.color", "black");
        //边框厚度
        properties.setproperty("kaptcha.border.thickness", "1");
        // 图片宽
        properties.setproperty("kaptcha.image.width", "200");
        // 图片高
        properties.setproperty("kaptcha.image.height", "50");
        //图片实现类
        properties.setproperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.defaultkaptcha");
        //文本实现类
        properties.setproperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.defaulttextcreator");
        //文本集合,验证码值从此集合中获取
        properties.setproperty("kaptcha.textproducer.char.string", "01234567890");
        //验证码长度
        properties.setproperty("kaptcha.textproducer.char.length", "4");
        //字体
        properties.setproperty("kaptcha.textproducer.font.names", "宋体");
        //字体颜色
        properties.setproperty("kaptcha.textproducer.font.color", "black");
        //文字间隔
        properties.setproperty("kaptcha.textproducer.char.space", "5");
        //干扰实现类
        properties.setproperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.defaultnoise");
        //干扰颜色
        properties.setproperty("kaptcha.noise.color", "blue");
        //干扰图片样式
        properties.setproperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.waterripple");
        //背景实现类
        properties.setproperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.defaultbackground");
        //背景颜色渐变,结束颜色
        properties.setproperty("kaptcha.background.clear.to", "white");
        //文字渲染器
        properties.setproperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.defaultwordrenderer");
        config config = new config(properties);
        defaultkaptcha.setconfig(config);
        return defaultkaptcha;
    }
 
}

util 

package com.yzm.utils;

import java.awt.image.bufferedimage;

import javax.imageio.imageio;
import javax.servlet.servletoutputstream;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import com.google.code.kaptcha.impl.defaultkaptcha;

public class util {
     
    /**
     * 生成验证码图片
     * @param request 设置session
     * @param response 转成图片
     * @param captchaproducer 生成图片方法类
     * @param validatesessionkey session名称
     * @throws exception
     */
    public static void validatecode(httpservletrequest request, httpservletresponse response, defaultkaptcha captchaproducer, string validatesessionkey) throws exception{
        // set to expire far in the past.
        response.setdateheader("expires", 0);
        // set standard http/1.1 no-cache headers.
        response.setheader("cache-control", "no-store, no-cache, must-revalidate");
        // set ie extended http/1.1 no-cache headers (use addheader).
        response.addheader("cache-control", "post-check=0, pre-check=0");
        // set standard http/1.0 no-cache header.
        response.setheader("pragma", "no-cache");
 
        // return a jpeg
        response.setcontenttype("image/jpeg");
 
        // create the text for the image
        string captext = captchaproducer.createtext();
 
        // store the text in the session
        request.getsession().setattribute(validatesessionkey, captext);
 
        // create the image with the text
        bufferedimage bi = captchaproducer.createimage(captext);
 
        servletoutputstream out = response.getoutputstream();
 
        // write the data out
        imageio.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}

以上就是springboot 图形验证码的生成和校验的详细内容,更多关于springboot 验证码的生成和校验的资料请关注其它相关文章!