当前位置: 首页 > 工具软件 > patchca > 使用案例 >

Patchca验证码及Token的三种传递策略 踩坑贴

舒浩邈
2023-12-01

Patchca验证码

Patchca是Piotr Piastucki写的一个java验证码开源库,打包成jar文件发布,patchca使用简单但功能强大。可以更改验证码样式 滤镜 大小。 这里不多写了,网上有很多相关代码。这次主要记录如何使用跟操作方式。
api相关操作的全部代码在第三种操作方式

//设置照片宽高
CaptchaService captchaService = new CaptchaService(110, 40);
//将设置好的照片大小 格式(png)输入流(os)传递给getChallangeAndWriteImage就可以成功验证码图片。
captcha = EncoderHelper.getChallangeAndWriteImage(captchaService, "png", os);

调用函数就这两个是不是很简单,下面说一下IO流的操作方式

第一种 FileOutputStream
直接用FileOutputStream 修改图片 不建议使用!!

FileOutputStream fos = new FileOutputStream("E:\\patcha_demo.png");

第二种 OutputStream
直接通过response将图片推出去,这里巨坑 我老天。
因为在调用api的时候我需要将tooken一起传递出去。最初是想用cookie将tooken传递出去 ,最后pass掉了。 因为cookie可以存入相关数据,但单页面获取不到,cookie的访问路径都设置好了。欢迎大佬留言

   public JSONObject base64PatchcaController(HttpServletRequest request,HttpServletResponse response) throws IOException {
        OutputStream outputStream = response.getOutputStream();

第三种ByteArrayOutputStream
这是我最后采用的ByteArrayOutputStream一组base64字符串通过josn传递出去。

    @ResponseBody
    @RequestMapping("/Patchca")
        public JSONObject base64PatchcaController() throws IOException {
            String img = null ;

           JSONObject jsonObject = new JSONObject();
            CaptchaService captchaService = new CaptchaService(110, 40);
            //设置照片的base64输出流和宽高
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            OutputStream os = new Base64OutputStream(bos);

            try {
                captcha = EncoderHelper.getChallangeAndWriteImage(captchaService, "png", os);
                img= new String(bos.toByteArray());
                os.flush();
                jsonObject.put("ret",1);
            }catch (Exception e) {
                jsonObject.put("ret",0);
            }finally {
                if (bos != null && os != null) {
                    os.close();
                    bos.close();
                }
            }
            //将redis存入redis
            String token = UUID.randomUUID()+":"+captcha;
            redisTemplate.opsForSet().add("token",token);
            redisTemplate.expire("token",1000, TimeUnit.MICROSECONDS);

            jsonObject.put("token",token);
            jsonObject.put("img",img);
            return jsonObject;
        }
 类似资料: