Java验证码 Kaptcha
Java验证码 Kaptcha
- maven依赖
- KaptchaConfig配置
- 访问效果
maven依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath />
</parent>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<springboot.version>2.1.3.RELEASE</springboot.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
KaptchaConfig配置
@Configuration
public class KaptchaConfig {
@Bean
public Kaptcha Kaptcha() {
return new GoogleKaptcha(defaultKaptcha());
}
@Bean
public DefaultKaptcha defaultKaptcha() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
properties.setProperty("kaptcha.border", "yes");
properties.setProperty("kaptcha.border.color", "105,179,90");
properties.setProperty("kaptcha.textproducer.font.color", "blue");
properties.setProperty("kaptcha.image.width", "125");
properties.setProperty("kaptcha.image.height", "45");
properties.setProperty("kaptcha.session.key", "code");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {
@Autowired
private Kaptcha kaptcha;
@GetMapping("/render")
Object render() {
String render = kaptcha.render();
System.err.println("render=" + render);
return render;
}
@GetMapping("/valid")
Object validDefaultTime(@RequestParam String code) {
boolean validate = kaptcha.validate(code);
System.err.println("validate=" + validate);
return validate;
}
@GetMapping("/validTime")
Object validWithTime(@RequestParam String code) {
boolean validate = kaptcha.validate(code, 60);
System.err.println("validate=" + validate);
return validate;
}
}
访问效果
http://localhost:8080/kaptcha/render
校验:
http://ip:8080/kaptcha/valid?code=yj96
校验成功返回: ture
校验失败:报错
第一次校验成功后再次校验也会报错
还没有评论,来说两句吧...