100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > java使用kaptcha生成图片验证码

java使用kaptcha生成图片验证码

时间:2018-10-03 04:49:57

相关推荐

java使用kaptcha生成图片验证码

作为一个后端开发人员,平台安全是重中之重,对于平台中登陆的校验一直是斗智斗勇的存在,

因此增加一些人工的校验,对于攻击有很好的拦截,也能够很好的保证用户账号密码的安全

图片验证码效果图

使用的pom包,如果使用的不是pom,可以在网上下载相同的jar

<dependency><groupId>com.github.axet</groupId><artifactId>kaptcha</artifactId><version>0.0.9</version></dependency><!-- /artifact/mons/commons-lang3其中有方法 RandomStringUtils.randomNumeric(5); 生成任意五位数字 --><dependency><groupId>mons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency>

Kaptcha配置文件

import com.google.code.kaptcha.impl.DefaultKaptcha;import com.google.code.kaptcha.util.Config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.util.Properties;/*** 生成验证码配置** @author lwj* @since 2.1.0 -01-12*/@Configurationpublic class KaptchaConfig {@Beanpublic 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");Config config = new Config(properties);DefaultKaptcha defaultKaptcha = new DefaultKaptcha();defaultKaptcha.setConfig(config);return defaultKaptcha;}}

Controller中调用的java方法

@GetMapping("captcha.jpg")public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {response.setHeader("Cache-Control", "no-store, no-cache");response.setContentType("image/jpeg");//生成文字验证码 生成5位中英文混合的验证码//String code = producer.createText();//生成5位数字的验证码String code = RandomStringUtils.randomNumeric(5);//request获取ip,保存到redis中【缺点:统一大型局域网下,公用一个公网IP】//校验也可以使前端传输一个UUID,校验图片二维码时可以使用UUID查询出生成的验证码ServletOutputStream out = response.getOutputStream();//获取图片验证码BufferedImage image = producer.createImage(code);ImageIO.write(image, "jpg", out);out.close();}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。