一、依赖
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
二、springmvc配置文件
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg> <props> <prop key="kaptcha.border">yes</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.textproducer.font.color">blue</prop> <prop key="kaptcha.image.width">125</prop> <prop key="kaptcha.image.height">45</prop> <prop key="kaptcha.textproducer.font.size">45</prop> <prop key="kaptcha.session.key">code</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop> </props> </constructor-arg> </bean> </property> </bean>
1.后端
controler类中: @Autowired private Producer captchaProducer = null; @RequestMapping(value = "captcha") public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); //生成验证码 String capText = captchaProducer.createText(); session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); //向客户端写出 BufferedImage bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } }
2.前端
<div class="form-group"> <div class="row"> <div class="col-sm-8"> <input type="text" id="code" class="form-control" placeholder="验证码" data-toggle="tooltip" data-placement="top"> </div> <div class="col-sm-4"> <img id="codeImg" src="http://127.0.0.1:8666/sys/captcha" class="img-responsive" style="display: block;width:100%;height: 32px"> </div> </div> </div>
参考:https://www.cnblogs.com/moonlightL/p/7282469.html