springboot+kaptcha实现验证码获取和校验

springboot+kaptcha实现验证码获取和校验

    最近几天在做一个入驻平台时候,在登录方面遇到验证码校验问题,可能有经验的人觉得这个问题比较简单,但是对于我这个刚入职的小白来说还是遇到一些问题,通过查询大量的资料,踩了许多坑,网上的版本有许多,但是最终我还是采用了这种方式,解决了该项目中的问题,发出来和大家分享一下,希望能帮到大家,不喜勿喷。废话不多说,上代码。

1. pom.xml



   com.github.penggle
   kaptcha
   2.3.2

2.生成验证码图片工具类



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


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
/*
  @description:生成验证码图片
  @author:qiaoyn
  @date:2019/06/10
*/
public class CommonUtil {


    /**
     * 生成验证码图片
     * @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();
        }
    }


}

3.Kaptcha文件配置

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


import java.util.Properties;


/*
  @description:Kaptcha文件配置
  @author:qiaoyn
  @date:2019/06/10
*/
@Component
public class KaptchaConfig {


    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.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;
    }

}

4.验证码获取与校验

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.sitech.crmbgapp.util.CommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;


/*
  @description:验证码获取与校验
  @author:qiaoyn
  @date:2019/06/10
*/
@RestController
@Api(value = "验证码")
public class ValidateCodeController {


    @Resource
    private DefaultKaptcha captchaProducer;


    /**
     *注册验证码图片SessionKey
     */
    public static final String LOGIN_VALIDATE_CODE = "regist_validate_code";
    /**
     * 注册验证码图片
     */
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @RequestMapping(value = {"/registValidateCode"}  ,method = RequestMethod.POST)
    public void registValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        CommonUtil.validateCode(request,response,captchaProducer,LOGIN_VALIDATE_CODE);
    }


    /**
     * 检查验证码是否正确
     */
    @ApiOperation(value = "检查验证码", notes = "检查验证码")
    @RequestMapping(value = "/checkRegistValidateCode",method = RequestMethod.POST)
    public HashMap checkRegistValidateCode(HttpServletRequest request, @RequestParam("validateCode")String validateCode) {
        String registValidateCode = request.getSession().getAttribute(LOGIN_VALIDATE_CODE).toString();
        HashMap map = new HashMap();
        if(registValidateCode == null){
            map.put("status",null);//验证码过期
        }else if(registValidateCode.equals(validateCode)){
            map.put("status",true);//验证码正确
        }else if(!registValidateCode.equals(validateCode)){
            map.put("status",false);//验证码不正确
        }
        map.put("code",200);
        return map;
    }
}

5.测试
本次测试使用了springboot集成swagger测试

springboot+kaptcha实现验证码获取和校验_第1张图片
springboot+kaptcha实现验证码获取和校验_第2张图片

springboot+kaptcha实现验证码获取和校验_第3张图片
springboot+kaptcha实现验证码获取和校验_第4张图片
springboot+kaptcha实现验证码获取和校验_第5张图片
springboot+kaptcha实现验证码获取和校验_第6张图片

你可能感兴趣的:(菜鸟,IT小白)