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