手把手教你系列之java生成验证码,登录校验,直接复制过去用 您所在的位置:网站首页 Java生成验证码 手把手教你系列之java生成验证码,登录校验,直接复制过去用

手把手教你系列之java生成验证码,登录校验,直接复制过去用

2023-03-13 01:09| 来源: 网络整理| 查看: 265

如果你在网上搜的话,会出来很多种方法,我接下来要写的是纯java生成验证码图片,以及校验的。 老规矩,直接复制粘贴过去用好吗

第一步: 导入依赖

com.github.penggle kaptcha 2.3.2

第二步: 写一个配置类,配置你生成验证码的那张图

@Configuration public class KaptchaConfig { /** * 验证码生成相关 */ @Bean public DefaultKaptcha kaptcha() { Properties properties = new Properties(); properties.put("kaptcha.border", "no"); properties.put("kaptcha.border.color", "105,179,90"); properties.put("kaptcha.textproducer.font.color", "blue"); properties.put("kaptcha.image.width", "125"); properties.put("kaptcha.image.height", "45"); properties.put("kaptcha.textproducer.font.size", "45"); properties.put("kaptcha.session.key", "code"); properties.put("kaptcha.textproducer.char.length", "4"); properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑"); Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } }

第三步: 写一个Controller,让前端来调你这个接口,生成或者刷新验证码,返回一个图,如下:

@Controller @RequestMapping("/kaptcha") public class KaptchaController { @Autowired private Producer producer; /** * 生成验证码 */ @RequestMapping("/code") public void kaptcha(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); response.setDateHeader("Expires", 0); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); // return a jpeg response.setContentType("image/jpeg"); // create the text for the image String capText = producer.createText(); // store the text in the session session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); // create the image with the text BufferedImage bi = producer.createImage(capText); ServletOutputStream out = null; try { out = response.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } // write the data out try { ImageIO.write(bi, "jpg", out); } catch (IOException e) { e.printStackTrace(); } try { try { out.flush(); } catch (IOException e) { e.printStackTrace(); } } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }

以上是生成验证码的代码,写到这里就明白了各位,校验我还没写,明天再写吧,划一会儿水~~~~~~ 校验你们可以自己写,就是把前端输入的验证码和session里的验证码比较一下。如果想偷懒的话,等着看我下一篇吧。。。。。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有