验证码是防止因系统或网络原因出现重复登录等异常
Kaptcha则是生成这样的验证码图片的一个功能强大的工具包
1.导包
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2.添加配置
package io.renren.common.config;
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 Mark sunlightcs@gmail.com */ @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", "3"); properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑"); Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } } 关于工具包的配置可以根据自己的需要进行修改
3.保存在session中
@Autowired
private Producer producer;
@GetMapping("kaptcha.jpg")
public void kaptcha(HttpServletResponse response,HttpServletRequest request) throws ServletException,IOException{
response.setHeader("Cache-Control", "no-store,no-cache");
response.setContentType("image/jpeg");
//生成文字验证码
String text=producer.createText();
//生成图片验证码
BufferedImage image=producer.createImage(text);
//保存验证码到session
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
ServletOutputStream out=response.getOutputStream();
ImageIO.write(image, "jpg", out);
//用到IO工具包控制开关
IOUtils.closeQuietly(out);
}
4.存数据库
存数据库可以灵活设置过期时间
uuid是主键,code是验证码。expire_time是过期时间。
然后每次生成验证码,需要一个参数(说是uuid其实用的时候就是一个id的作用)。会将这个uuid当做表的主键,然后code和过期时间一起存到数据库。
在登录的时候先做校验,判断这个uuid的code和输入的验证码是否一样,是的话验证成功,并且删除这条记录。不是的话返回验证码错误
5.调用
/**
* 验证码
*/
@ApiOperation("获取验证码")
@RequestMapping("kaptcha.jpg")
public void kaptcha(HttpServletResponse response, @ApiParam(name="uuid",value="随机字符串") String uuid)throws IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
//获取图片验证码
BufferedImage image = sysCaptchaService.getCaptcha(uuid);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
IOUtils.closeQuietly(out);
}
来源:https://www./content-4-833601.html
|