Java 生成验证码 可自定义配置

1.使用kaptcha配置生成验证码

使用maven坐标引入pom

<dependency>
 <groupId>com.github.penggle</groupId>
 <artifactId>kaptcha</artifactId>
 <version>2.3.2</version>
 <exclusions>
 <exclusion>
 <artifactId>javax.servlet-api</artifactId>
 <groupId>javax.servlet</groupId>
 </exclusion>
 </exclusions>
</dependency>
 

新建配置文件kaptcha.properties,下面的验证码配置,从英文单词的角度很容易理解,当我们需要调整验证码的边框、颜色、大小、字体等属性的时候,可以修改这些配置。

kaptcha.border=no
kaptcha.border.color=105,179,90
kaptcha.image.width=200
kaptcha.image.height=60
kaptcha.session.key=code
kaptcha.textproducer.font.color=blue
kaptcha.textproducer.font.size=35
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.names=宋体,楷体,微软雅黑

 

新建配置类CaptchaConfig加载配置文件

@Component
@PropertySource(value = {"classpath:kaptcha.properties"})
public class CaptchaConfig {

 @Value("${kaptcha.border}")
 private String border;
    @Value("${kaptcha.border.color}")
 private String borderColor;
    @Value("${kaptcha.textproducer.font.color}")
 private String fontColor;
    @Value("${kaptcha.image.width}")
 private String imageWidth;
    @Value("${kaptcha.image.height}")
 private String imageHeight;
    @Value("${kaptcha.session.key}")
 private String sessionKey;
    @Value("${kaptcha.textproducer.char.length}")
 private String charLength;
    @Value("${kaptcha.textproducer.font.names}")
 private String fontNames;
    @Value("${kaptcha.textproducer.font.size}")
 private String fontSize;

    @Bean(name = "captchaProducer")
 public DefaultKaptcha getKaptchaBean() {
 DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", border);
        properties.setProperty("kaptcha.border.color", borderColor);
        properties.setProperty("kaptcha.textproducer.font.color", fontColor);
        properties.setProperty("kaptcha.image.width", imageWidth);
        properties.setProperty("kaptcha.image.height", imageHeight);
        properties.setProperty("kaptcha.session.key", sessionKey);
        properties.setProperty("kaptcha.textproducer.char.length", charLength);
        properties.setProperty("kaptcha.textproducer.font.names", fontNames);
        properties.setProperty("kaptcha.textproducer.font.size",fontSize);
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

}

至此,Kaptcha开源验证码软件的配置我们就完成了。

 

2.生成验证码并保存

 通过captchaProducer.createText()生成验证码文字,并和失效时间一起保存到CaptchaImageVO中。

将CaptchaImageVO验证码信息类对象,保存到session中。

通过captchaProducer.createImage(capText)生成验证码图片,并通过ServletOutputStream返回给前端

 

@RestController
public class CaptchaController {

 @Resource
 DefaultKaptcha captchaProducer;

    /**
 * 获取验证码
 */
 @GetMapping("kaptcha")
 public void kaptcha(HttpSession session, HttpServletResponse response) throws Exception {

 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 = captchaProducer.createText();
        CaptchaImageVO captchaImageVO = new CaptchaImageVO(capText,2 * 60);
        //将验证码存到session
 session.setAttribute(Constants.KAPTCHA_SESSION_KEY, captchaImageVO);

        //将图片返回给前端
 try(ServletOutputStream out = response.getOutputStream();) {
 BufferedImage bi = captchaProducer.createImage(capText);
            ImageIO.write(bi, "jpg", out);
            out.flush();
        }//使用try-with-resources不用手动关闭流
 }

}

 

 
CaptchaImageVO实体类: 
@Data
public class CaptchaImageVO {

 //验证码文字
 private String code;
    //验证码失效时间
 private LocalDateTime expireTime;

    public CaptchaImageVO(String code, int expireAfterSeconds){
 this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireAfterSeconds);
    }

 //验证码是否失效
 public boolean isExpried() {
 return LocalDateTime.now().isAfter(expireTime);
    }

}

 

3.测试

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <script th:inline="javascript">
 var url_image = [[@{/kaptcha}]];
 </script>
</head>
<body>
 <img th:src="@{/kaptcha}" id="kaptcha" width="110px" height="40px"/>
</body>
<script th:inline="javascript">
 window.onload=function(){
 var kaptchaImg = document.getElementById("kaptcha");
        kaptchaImg.onclick = function(){
 kaptchaImg.src = url_image + "?" + Math.floor(Math.random() * 100);
        }
 }
</script>
</html>
 

实现的效果是,页面初始化即加载验证码。以后每一次点击,都会更新验证码。

 

 

4.kaptcha配置项

Constant描述默认值
kaptcha.border图片边框,合法值:yes , noyes
kaptcha.border.color边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.black
kaptcha.image.width图片宽200
kaptcha.image.height图片高50
kaptcha.producer.impl图片实现类com.google.code.kaptcha.impl.DefaultKaptcha
kaptcha.textproducer.impl文本实现类com.google.code.kaptcha.text.impl.DefaultTextCreator
kaptcha.textproducer.char.string文本集合,验证码值从此集合中获取abcde2345678gfynmnpwx
kaptcha.textproducer.char.length验证码长度5
kaptcha.textproducer.font.names字体Arial, Courier
kaptcha.textproducer.font.size字体大小40px.
kaptcha.textproducer.font.color字体颜色,合法值: r,g,b 或者 white,black,blue.black
kaptcha.textproducer.char.space文字间隔2
kaptcha.noise.impl干扰实现类com.google.code.kaptcha.impl.DefaultNoise
kaptcha.noise.color干扰 颜色,合法值: r,g,b 或者 white,black,blue.black
kaptcha.background.impl背景实现类com.google.code.kaptcha.impl.DefaultBackground
kaptcha.background.clear.from背景颜色渐变,开始颜色light grey
kaptcha.background.clear.to背景颜色渐变, 结束颜色white
kaptcha.word.impl文字渲染器com.google.code.kaptcha.text.impl.DefaultWordRenderer
kaptcha.session.keysession keyKAPTCHA_SESSION_KEY
kaptcha.session.datesession dateKAPTCHA_SESSION_DATE
kaptcha.obscurificator.impl

图片样式:<br />水纹 com.google.code.kaptcha.impl.WaterRipple

<br /> 鱼眼 com.google.code.kaptcha.impl.FishEyeGimpy

<br /> 阴影 com.google.code.kaptcha.impl.ShadowGimpy

com.google.code.kaptcha.impl.WaterRipple


 

 

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值