生成图形验证码是如此简单

2023-03-05 15:25:14 浏览数 (1)

依赖

代码语言:javascript复制
<!-- kaptcha验证码-->
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

获取图形验证码

前端传入uuid,后端通过uuid作为redis缓存key

代码语言:javascript复制
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.core.domain.RApp;
import com.ruoyi.common.core.utils.KeyUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.shlz.common.utils.redis.RedisConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * 图形验证码控制器
 *
 * @author xGuo
 * @date 2022/03/25
 */
@RestController
@RequestMapping("/api/code/")
@Slf4j
public class VerifyCodeController {
    @Autowired
    private  RedisService redisService;
    @Autowired
    private  Producer producer;

    /**
     * 获取验证码
     *
     * @param request  请求
     * @param response 响应
     * @param uuid     uuid
     * @return {@link ModelAndView}
     * @throws IOException ioexception
     */
    @GetMapping("getCode")
    public ModelAndView getCode(HttpServletRequest request, HttpServletResponse response
            , @RequestParam(value = "uuid") String uuid) throws IOException {

        ModelAndView mv = new ModelAndView();

        if (StringUtils.isEmpty(uuid)) {
            uuid = KeyUtils.randomUUID(false);
        }
        mv.addObject("uuid", uuid);
        String verifyCodeKey = RedisConst.RedisKeyPrefix.VERIFY_CODE   uuid;

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = producer.createText();
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        //存入redis
        redisService.setCacheObject(verifyCodeKey, capText
                , RedisConst.RedisCacheExTime.REDIS_VERIFY_CODE_EXTIME, TimeUnit.SECONDS);

        BufferedImage bi = producer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

校验验证码

代码语言:javascript复制
/**
 * 校验验证码
 *
 * @param code    验证码
 * @param uuid    uuid
 * @return {@link RApp}<{@link ?}>
 */
@GetMapping("checkCode")
public RApp<?> checkCode(@RequestParam(value = "code") String code
        , @RequestParam(value = "uuid") String uuid) {
    String original = redisService.getCacheObject(RedisConst.RedisKeyPrefix.VERIFY_CODE   uuid);
    if (StringUtils.isNotEmpty(code)) {
        if (code.equalsIgnoreCase(original)) {
            return RApp.createBySuccessMsg("验证码通过");
        }
    }
    return RApp.createByErrorMsg("验证码失败");
}

0 人点赞