JAVA后端《kaptcha》

1.SpringBoot整合kaptcha快速实现验证码功能

  • 搭建基础SpringBoot环境,导入kaptcha依赖
<!--验证码-->
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>
  • 编写kaptcha配置类
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfig {

    @Bean(name = "defaultKaptcha")
    public DefaultKaptcha defaultKaptcha(){
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border","yes");
        properties.setProperty("kaptcha.border.color","105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color","blue");
        properties.setProperty("kaptcha.image.width","125");
        properties.setProperty("kaptcha.image.height","45");
        properties.setProperty("kaptcha.textproducer.font.size","45");
        properties.setProperty("kaptcha.session.key","code");
        //验证码长度
        properties.setProperty("kaptcha.textproducer.char.length","4");
        properties.setProperty("kaptcha.textproducer.font.names","宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}
  • 编写Web层
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.wpq.ip.IpUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class TestController {

    @Resource
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/kaptcha.jpg")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response){

        String ipAddr = IpUtils.getIpAddr(request);
        response.setHeader("Cache-Control","no-store,no-cache");
        response.setContentType("image/jpg");
        String kaptchaText = defaultKaptcha.createText();
        
        //前后端分离使用@ipAddr客户端IP地址 作为key,kaptchaText作为值存入Redis中
        // 非前后端分离可以使用固定的key存入session中
        //todo 将验证码存入Redis/Session
        
        BufferedImage image = defaultKaptcha.createImage(kaptchaText);
        try {
            ImageIO.write(image,"jpg",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 本服务器或其它服务器使用标签绑定此生成验证码接口,即可拿到验证码图片
  <img src="http://localhost:8080/kaptcha.jpg" />
  • 不使用HttpServletResponse的输出流,使用AJAX异步调用返回结果方式
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.wpq.ip.IpUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@CrossOrigin(allowedHeaders = "*")
public class TestController {

    @Resource
    private DefaultKaptcha defaultKaptcha;
    @Resource
    private RedisCache redisCache;


    private static final String KAPTCHA_PREFIX="kaptcha";
    private static final String KAPTCHA_SPLITTER="::";

    @ResponseBody
    @GetMapping("/kaptcha.jpg")
    public Map<String,Object> getKaptcha(HttpServletRequest request){

        StringBuilder sb = new StringBuilder();
        //全局唯一UUID
        String cacheKey = sb.append(KAPTCHA_PREFIX)
                            .append(KAPTCHA_SPLITTER)
                            .append(this.uuid()).toString();
        String kaptchaText = defaultKaptcha.createText();
        // 前后端分离使用cacheKey作为Redis的key,注册或登录的时候带着key过来注册或登录就行
        //todo 将验证码存入Redis
        redisCache.set(cacheKey, kaptchaText, 3, TimeUnit.MINUTES);
        BufferedImage image = defaultKaptcha.createImage(kaptchaText);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        try {
            //验证码图片数据写进字节数组输出流
            ImageIO.write(image,"jpg",byteStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        Map<String,Object> data = new HashMap<String, Object>();
        //把Redis的key放进AJAX返回结果中
        data.put("cacheKey",cacheKey);
        //把字节数组输出流转成字节数组,再进行BASE64编码
        data.put("img", encoder.encode(byteStream.toByteArray()));
        return data;
    }

    public String uuid(){
        return UUID.randomUUID().toString().replace("-","");
    }
}
  • 前端页面的img标签使用data URL的形式获取验证码:“data:image/gif;base64,”+BASE64编码后的图片数据
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<p>
    <img id="img" src="" /><br>
    <span id="cacheKey"></span>
    <input type="button" value="获取验证码" onclick="getCode();">
</p>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script>
    function getCode() {
        $.ajax({
            url:"http://localhost:8080/kaptcha.jpg",
            dataType:"json",
            type:"get",
            success:function (r) {
                alert(JSON.stringify(r));
                $("#img")[0].src = "data:image/gif;base64,"+r.img;
                $("#cacheKey").text(r.cacheKey);
            }
        })
    }
</script>
</body>
</html>
  • 效果展示
    在这里插入图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值