Java登录图形验证码生成简单方案

Java登录图形验证码生成简单易上手方案

一、引入相关依赖


            com.github.axet
            kaptcha
            0.0.9
        

二、添加获取验证码图片配置

/**
 * 生成验证码配置
 */
@Configuration
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");  //验证码的颜色
        properties.put("kaptcha.textproducer.char.space", "5");  //验证码个数
        properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

三、添加获取验证码接口及业务代码

Controller层
/**
     * 图形验证码接口
     *
     * @param response
     * @param
     * @throws IOException
     */
    @GetMapping("/getCode")
    public void getCode(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码 并把图片写入到响应中
        BufferedImage image = userService.getCaptcha();
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }
Service层
/**
     * 获取图形验证码
     * @return BufferedImage
     */
    @Resource
    @Lazy
    private Producer producer;
    public BufferedImage getCaptcha() {
        //生成文字验证码
        String code = producer.createText();
        log.debug("验证码为:{}", code);
        redisTemplate.opsForValue().set("code" + code, code);
        return producer.createImage(code);
    }

四、前端接口


HTML代码




JS代码
getcode(){
      this.$axios.get("user/getCode",{responseType: 'blob'}).then(res => {
        console.log(res);
        this.ruleForm.codeImg = window.URL.createObjectURL(res.data)
      })
    }

五、实现效果图
图片展示

你可能感兴趣的:(springboot,java,开发语言,spring,boot,后端,intellij-idea,javascript,vue)