easy-captcha生成验证码

通常一些网页登陆时,都需要通过验证码去登录;

生成验证码的方法有很多,这次分享一个验证码即能是汉字的 又能是算术的。

首先maven坐标:

<dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>1.6.2</version>
        </dependency>

 方式很简单,直接看代码

package com.xiaoteng.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xiaozhuang
 * @date 2022年03月20日 15:10
 */
@RestController
@RequestMapping("userlogin")
public class LoginController {
    /**
     * 生成验证码,通过前端传入一个key,区分同一时间请求的验证码
     *
     * @param key
     */
    @GetMapping(value = "/captcha", produces = "image/png")
    public void creatCaptcha(String key, HttpServletResponse response) throws IOException {
        // 算数验证码
        Captcha captcha = new ArithmeticCaptcha();
        // 文字验证码
        // Captcha captcha2=new ChineseCaptcha();
        // 生成的验证码
        String text = captcha.text();
        System.out.println("验证码 = " + text);
        // 返回图片类型
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        // 清除浏览器缓存
        response.setHeader(HttpHeaders.PRAGMA, "No-cache");
        response.setHeader(HttpHeaders.CACHE_CONTROL, "No-cache");
        // 缓存时间为0
        response.setDateHeader(HttpHeaders.EXPIRES, 0L);
        // 回写给前端图片
        captcha.out(response.getOutputStream());
    }
}

 这里的key,是防止同时有多个同时请求,需要区分开来,key可以是前端传来的uuid之类的值,我们可以通过这个key和生成的验证码进行保存,在下步对验证码进行校验时使用。

下面是效果图:

posted @   超级大菜鸡  阅读(808)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示