生成验证码
1.Kaptcha
-
简介
-
导包:jar导入网站
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gedaI0Fl-1646367836400)(C:\Users\dooth\AppData\Roaming\Typora\typora-user-images\image-20220301165629985.png)]
-
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
-
验证码的配置
@Configuration //表示这是一个配置类 public class KaptchaConfig {//Config包存放配置类 @Bean public Producer kaptchaProducer(){//Producer实例可以用于生成验证码 //配置验证码参数 Properties properties = new Properties(); properties.setProperty("kaptcha.image.width","100");//配置验证码图片的宽度 properties.setProperty("kaptcha.image.height","40");//配置验证码图片的高度 properties.setProperty("kaptcha.textproducer.font.size","40");//配置验证码字号 properties.setProperty("kaptcha.textproducer.font.color","0,0,0");//配置验证码字号 properties.setProperty("kaptcha.textproducer.char.string","0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");//配置验证码生成字的范围 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; } }
-
-
验证码的使用
-
在controller中生成验证码:
@Autowired private Producer kaptchaProducer; //注入验证码生成的bean @RequestMapping(path = "/kaptcha",method = RequestMethod.GET) public void getKaptcha(HttpServletResponse response,HttpSession session){//验证码为敏感数据,所以用session存储 //生成验证码 String text = kaptchaProducer.createText();//验证码的内容 BufferedImage image = kaptchaProducer.createImage(text);//生成与上面对应的验证码图片 //将验证码存入session session.setAttribute("kaptcha",text); //将图片输出到浏览器 response.setContentType("image/png");//声明传入response的是什么类型 try { OutputStream os = response.getOutputStream();//创建字节输出流 ImageIO.write(image,"png",os);//字节输出流输出图片 } catch (IOException e) { logger.error("响应验证码失败"+e.getMessage());//生成日志 } }
-
在html中的使用
th:src="@{/kaptcha}" 在标签中调用即可
-
点击刷新
<script> function refresh_kaptcha(){ var path = CONTEXT_PATH + "/kaptcha?p=" + Math.random(); $('#kaptcha').attr("src",path); } </script>
-