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

kaptcha 验证码

尉迟默
2023-12-01

1. baomidou提供的kaptcha-spring-boot-starter

pom

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>kaptcha-spring-boot-starter</artifactId>
    <version>1.1.0</version>
</dependency>

自定义验证码参数,以下为默认配置, yml配置

kaptcha:
  height: 50
  width: 200
  content:
    length: 4
    source: abcdefghjklmnopqrstuvwxyz23456789
    space: 2
  font:
    color: black
    name: Arial
    size: 40
  background-color:
    from: lightGray
    to: white
  border:
    enabled: true
    color: black
    thickness: 1

controlller

import com.baomidou.kaptcha.Kaptcha;
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.RestController;

/**
 * 生成验证码服务
 *
 * @author liuxb
 * @date 2022/5/18 15:17
 */
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

    @Autowired
    private Kaptcha kaptcha;

    /**
     * 获取Kaptcha验证码,返回前端图片流
     */
    @GetMapping("/kaptchaImg")
    public void kaptchaImg() {
        //默认900秒 15min有效期
        kaptcha.render();
    }

    /**
     * 验证验证码
     *
     * @param code 验证码
     * @return
     */
    @GetMapping("/valid")
    public boolean validDefaultTime(String code) {
        //default timeout 900 seconds
       return kaptcha.validate(code);
    }

    /**
     * 校验验证码是否在指定时间内有效
     * @param code
     */
    @GetMapping("/validCustomTime")
    public boolean validCustomTime(String code) {
        return kaptcha.validate(code, 60);
    }
}

2. com.github.penggle封装的kaptcha

pom

<!-- Kaptcha验证码组件-->
<dependency>
  <groupId>com.github.penggle</groupId>
  <artifactId>kaptcha</artifactId>
  <version>2.3.2</version>
</dependency>

配置类

import com.google.code.kaptcha.util.Config;

@Configuration
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
        Properties properties=new Properties();
        //是否有边框
        properties.setProperty(Constants.KAPTCHA_BORDER,"yes");
        //验证码文本颜色
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR,"blue");
        //验证码图片宽度
        properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH,"160");
        //验证码图片高度
        properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT,"60");
        //文本字符大小
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE,"38");
        //验证码session的值
        properties.setProperty(Constants.KAPTCHA_SESSION_CONFIG_KEY,"kaptchaCode");
        //验证码文本长度
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH,"4");
        //字体
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "宋体,楷体,微软雅黑");
 
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

controller
···java
@Controller
public class KaptchaController {
@Resource
private Producer kaptchaProducer;

@GetMapping("verify_code")
public void createVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //响应立即过期
    response.setDateHeader("Expires", 0);
    //不缓存任何图片数据
    response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
    response.setHeader("Cache-Control", "post-check=0,pre-check=0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("image/png");
    //生成验证码字符文本
    String verifyCode = kaptchaProducer.createText();
    request.getSession().setAttribute("kaptchaVerifyCode", verifyCode);
    System.out.println(request.getSession().getAttribute("kaptchaVerifyCode"));
    BufferedImage image = kaptchaProducer.createImage(verifyCode);//创建验证图片
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(image, "png", out);
    //输出和关闭输出
    out.flush();
    out.close();
}

/**
*校对验证码
* @param httpServletRequest
* @return
*/
@RequestMapping(value = “login”, method = RequestMethod.POST)
public boolean CheckDefaultKaptcha(@RequestBody LoginTwoVo loginTwoVo, HttpServletRequest request){
//得到session里面的,key为“vrifyCode”的value值
String captchaId = (String)request.getSession().getAttribute(“kaptchaVerifyCode”);
//输出该value值和自己测试时填写的值
System.out.println((“Session vrifyCode ---->” + captchaId + “---- form code —>” + loginTwoVo.getCode()));
//判断session里面的验证码与自己填写的值是否一致
if (!captchaId.equals(loginTwoVo.getCode())) {
System.out.println((“错误的验证码”));
return false;
} else {
//判断账号和密码是否一致
if(loginTwoVo.getUserName().equals(“wsw”)&&loginTwoVo.getPassword().equals(“123456”)){
System.out.println(“登录成功”);
return true;
}
return false;
}
}
}
····

 类似资料: