kaptcha验证码实现,配合spring boot使用

一、kaptcha介绍

  Kaptcha是谷歌放在github上的一个验证码jar包,我们可以简单配置属性实现验证码的验证功能。

  kaptcha参数设置如下所示:

  Constant 描述 默认值
  kaptcha.border 图片边框,合法值:yes , no yes
  kaptcha.border.color 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. black
  kaptcha.border.thickness 边框厚度,合法值:>0 1
  kaptcha.image.width 图片宽 200
  kaptcha.image.height 图片高 50
  kaptcha.producer.impl 图片实现类 com.google.code.kaptcha.impl.DefaultKaptcha
  kaptcha.textproducer.impl 文本实现类 com.google.code.kaptcha.text.impl.DefaultTextCreator
  kaptcha.textproducer.char.string 文本集合,验证码值从此集合中获取 abcde2345678gfynmnpwx
  kaptcha.textproducer.char.length 验证码长度 5
  kaptcha.textproducer.font.names 字体 Arial, Courier
  kaptcha.textproducer.font.size 字体大小 40px.
  kaptcha.textproducer.font.color 字体颜色,合法值: r,g,b 或者 white,black,blue. black
  kaptcha.textproducer.char.space 文字间隔 2
  kaptcha.noise.impl 干扰实现类 com.google.code.kaptcha.impl.DefaultNoise
  kaptcha.noise.color 干扰颜色,合法值: r,g,b 或者 white,black,blue. black
  kaptcha.obscurificator.impl 图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影            

  com.google.code.kaptcha.impl.ShadowGimpy com.google.code.kaptcha.impl.WaterRipple 
  kaptcha.background.impl 背景实现类 com.google.code.kaptcha.impl.DefaultBackground
  kaptcha.background.clear.from 背景颜色渐变,开始颜色 light grey
  kaptcha.background.clear.to 背景颜色渐变,结束颜色 white
  kaptcha.word.impl 文字渲染器 com.google.code.kaptcha.text.impl.DefaultWordRenderer
  kaptcha.session.key session key KAPTCHA_SESSION_KEY
  kaptcha.session.date session date KAPTCHA_SESSION_DATE

二、实现

1、引入maven依赖

<!-- kaptcha 验证码接入jar -->
<dependency>
    <groupId>kaptcha.wso2</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.0.wso2v1</version>
</dependency>

2、编写配置类

 1 package com.example.demo.config;
 2 
 3 import com.google.code.kaptcha.impl.DefaultKaptcha;
 4 import com.google.code.kaptcha.util.Config;
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.context.annotation.Configuration;
 7 
 8 import java.util.Properties;
 9 
10 /**
11  * @author zsh
12  * @company wlgzs
13  * @create 2019-03-10 9:37
14  * @Describe CaptchaConfig配置类
15  */
16 @Configuration
17 public class CaptchaConfig {
18 
19     @Bean(name = "captchaProducer")
20     public DefaultKaptcha getKaptchaBean(){
21         DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
22         Properties properties=new Properties();
23         properties.setProperty("kaptcha.border", "yes");
24         properties.setProperty("kaptcha.border.color", "105,179,90");
25         properties.setProperty("kaptcha.textproducer.font.color", "blue");
26         properties.setProperty("kaptcha.image.width", "125");
27         properties.setProperty("kaptcha.image.height", "45");
28         properties.setProperty("kaptcha.session.key", "code");
29         properties.setProperty("kaptcha.textproducer.char.length", "5");
30         properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
31         Config config=new Config(properties);
32         defaultKaptcha.setConfig(config);
33         return defaultKaptcha;
34     }
35 
36 }

3、编写controller类

package com.example.demo;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @author zsh
 * @company wlgzs
 * @create 2019-03-10 9:41
 * @Describe Captcha测试controller
 */
@Controller
public class CaptchaController {

    @Autowired
    DefaultKaptcha defaultKaptcha;

    /**
     * 显示验证码
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute("verifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }


    @PostMapping("/verifyCode")
    public String imgverifyControllerDefaultKaptcha(Model model, HttpSession session, String verifyCode) {
        String captchaId = (String) session.getAttribute("verifyCode");
        System.out.println("验证码是:" + captchaId);
        System.out.println("用户输入的是:" + verifyCode);
        if (!captchaId.equals(verifyCode)) {
            System.out.println("输入错误");
            model.addAttribute("info", "错误的验证码");
        } else {
            System.out.println("输入正确");
            model.addAttribute("info", "正确");
        }
        return "/index";
    }

    @GetMapping("/")
    public ModelAndView test() {
        return new ModelAndView("index");
    }

}

4、编写测试页面

1 -------------Kaptcha验证码
2 <h1 th:text="${info}"/>
3 <div>
4     <img alt="验证码" onclick="this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha"/>
5 </div>
6 <form action="/verifyCode" method="post">
7     <input type="text" name="verifyCode"/>
8     <input type="submit" value="提交"/>
9 </form>

5、效果

猜你喜欢

转载自www.cnblogs.com/zsh-blogs/p/10504431.html