在写这个demo之前,需要了解几个前序知识
1.request和response(请求和响应)
当Web容器收到客户端的发送过来http请求,会针对每一次请求,分别创建一个用于代表此次请求的HttpServletRequest对象(request)对象、和代表响应的HTTPServletResponse对象(response)。
request负责获取客户机提交过来的数据。 response负责向客户机输出数据。
2.GET和POST方式
对于POST方式,表单中的参数值对是通过request包发送给服务器,此时浏览器会根据网页的ContentType(“text/html; charset=GBK”)中指定的编码进行对表单中的数据进行编码,然后发给服务器。
对于GET方式,我们知道它的提交是将请求数据附加到URL后面作为参数,这样依赖乱码就会很容易出现,因为数据name和value很有可能就是传递的为非ASCII码。
1.Kaptcha:导入jar包
2.编写Kaptcha配置类
设置一下验证码的长宽高,以及随机字符串从哪些字母里选。最后封装到一个配置类
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer(){
Properties properties = new Properties();
properties.setProperty("kaptcha.image.width","100");
properties.setProperty("kaptcha.image.height","50");
properties.setProperty("kaptcha.textproducer.font.size","32");
properties.setProperty("kaptcha.textproducer.font.color","black");
properties.setProperty("kaptcha.textproducer.char.string","0123456789asdfghjjklmnbvcxzqwertyuiop");
properties.setProperty("kaptcha.textproducer.char.length","4");
properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config=new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
3.生成随机字符、生成图片
因为这个demo只是生成验证码,所以我们只需要调用相应的配置类生成字符串,并且生成随机码的图片。
然后要将验证码存入seeion里面,因为http是无状态的,所以并不会保存每次交互的信息,我们利用session来存储现在生成的验证码,一会写登录功能的时候就可以根据用户输入的验证码和我们存储的验证码做一个对比,看是否符合要求。
同时我们也要让图片在浏览器端显示出来。
@RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session){
//生成验证码
String text = kaptchaProducer.createText();
BufferedImage image = kaptchaProducer.createImage(text);
//将验证码存入session
session.setAttribute("kaptcha",text);
//将图片输出给浏览器
response.setContentType("image/png");
try {
OutputStream os = response.getOutputStream();
ImageIO.write(image,"png",os);
} catch (IOException e) {
logger.error("响应验证码失败:"+e.getMessage());
}
}



