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和生成的验证码进行保存,在下步对验证码进行校验时使用。

下面是效果图:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM