开源patchca验证码使用总结
pom.xml
<!-- 验证码 --> <dependency> <groupId>com.github.bingoohuang</groupId> <artifactId>patchca</artifactId> <version>0.0.1</version> </dependency>
jsp:
<div > 验证码:<input type="text" style="width: 150px;height: 20px;" class="authod" name="authcode" id="authcode"></input> <img id="validationCode" alt="验证码图片" title="验证码图片" src="<%=path %>/pcrimg" onclick="refreshCode(this)" /> <a id="aRecode" href="javascript:void(0);" onclick="refreshCode()">看不清,换一张</a> </div>
js:
function refreshCode(imgObj) { if (!imgObj) { imgObj = document.getElementById("validationCode"); } var index = imgObj.src.indexOf("?"); if(index != -1) { var url = imgObj.src.substring(0,index + 1); imgObj.src = url + Math.random(); } else { imgObj.src = imgObj.src + "?" + Math.random(); } }
后台代码:
// 验证码处理器工厂 private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService(); private static Random random = new Random(); static { cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170))); cs.setColorFactory(new ColorFactory() { public Color getColor(int x) { int[] c = new int[3]; int i = random.nextInt(c.length); for (int fi = 0; fi < c.length; fi++) { if (fi == i) { c[fi] = random.nextInt(71); } else { c[fi] = random.nextInt(256); } } return new Color(c[0], c[1], c[2]); } }); // 生成的单词设置 RandomWordFactory wf = new RandomWordFactory(); wf.setCharacters("23456789abcdefghigkmnpqrstuvwxyzABCDEFGHIGKLMNPQRSTUVWXYZ"); wf.setMaxLength(4); wf.setMinLength(4); cs.setWordFactory(wf); } @RequestMapping("/pcrimg") public void crimg(HttpServletRequest request, HttpServletResponse response) throws IOException { switch (random.nextInt(5)) { case 0: cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory())); break; case 1: cs.setFilterFactory(new MarbleRippleFilterFactory()); break; case 2: cs.setFilterFactory(new DoubleRippleFilterFactory()); break; case 3: cs.setFilterFactory(new WobbleRippleFilterFactory()); break; case 4: cs.setFilterFactory(new DiffuseRippleFilterFactory()); break; } HttpSession session = request.getSession(false); if (session == null) { session = request.getSession(); } setResponseHeaders(response); String token = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream()); session.setAttribute("captchaToken", token); System.out.println("当前的SessionID=" + session.getId() + ",验证码=" + token); } protected void setResponseHeaders(HttpServletResponse response) { response.setContentType("image/png"); response.setHeader("Cache-Control", "no-cache, no-store"); response.setHeader("Pragma", "no-cache"); long time = System.currentTimeMillis(); response.setDateHeader("Last-Modified", time); response.setDateHeader("Date", time); response.setDateHeader("Expires", time); }
好记性不如烂笔头