关于kaptcha的使用
1.首先写一个配置文件
importcom.google.code.kaptcha.impl.DefaultKaptcha;
importcom.google.code.kaptcha.util.Config;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importjava.util.Properties;
/**
* Created by Administrator on 2017/12/5/005.
*/
@Configuration
public classkaptchaConfig {
@Bean(name="captchaProducer")
publicDefaultKaptchagetKaptchaBean(){
DefaultKaptchadefaultKaptcha=newDefaultKaptcha();
Properties properties=newProperties();
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=newConfig(properties);
defaultKaptcha.setConfig(config);
returndefaultKaptcha;
}
}
然后写一个请求图片的controller
importcom.google.code.kaptcha.impl.DefaultKaptcha;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importjavax.imageio.ImageIO;
importjavax.servlet.ServletOutputStream;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayOutputStream;
/**
* Created by Administrator on 2017/12/5/005.
*/
@Controller
public classKaptchaController {
@Autowired
DefaultKaptchadefaultKaptcha;
@RequestMapping("/defaultKaptcha")
public voiddefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)throwsException{
byte[] captchaChallengeAsJpeg =null;
ByteArrayOutputStream jpegOutputStream =newByteArrayOutputStream();
try{
//生产验证码字符串并保存到session中
String createText =defaultKaptcha.createText();
httpServletRequest.getSession().setAttribute("vrifyCode", createText);
//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge =defaultKaptcha.createImage(createText);
ImageIO.write(challenge,"jpg", jpegOutputStream);
}catch(IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
//定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
httpServletResponse.setHeader("Cache-Control","no-store");
httpServletResponse.setHeader("Pragma","no-cache");
httpServletResponse.setDateHeader("Expires",0);
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream responseOutputStream =
httpServletResponse.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
}
如何验证呢