-
验证码用到的是图片文字处理技术,利用水印将文字和图片进行水印,然后输出到jsp反馈到前端界面。
- html部分,onsubmit是为了异步处理的时候不跳转页面,通过jS进行判断。
<form method="post" action="成功后跳转的页面" οnsubmit="return check()"> <input name="ver" type="text" > <img src="verification.jsp" alt=""/> <button class="btn" type="button">换一换</button> <button class="btn1" type="submit">登录</button> </form> |
- js部分
$(".btn").click(function () { var src = "verification.jsp?" + (Math.random());//可以换成时间戳更严谨 $("img").attr("src", src); }); function check() { var val = $("input").val(); var url = "yanzheng.jsp?ff=" + val; var res = false; $.ajax({ type: "POST", url: url, dataType: "html", async: false, success: function (result) { //function1() if (result == 0) { res = false; } else { res = true; } }, failure: function (result) { alert('Failed'); } }); return res; };
异步请求解决方案:http://www.jb51.net/article/64185.htm http://www.cnblogs.com/xmphoenix/archive/2011/11/21/2257651.html |
-
jsp部分
<% //创建画布 int width = 100, height = 50; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //画笔声明 Graphics2D g = bi.createGraphics(); g.setFont(new Font("宋体", 0, 30)); //改变画布颜色 g.setColor(Color.white);//画笔颜色 g.fillRect(0, 0, width, height);//可画范围 //创建随机数集合 String str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789"; Random r = new Random();//返回一个随机整数
StringBuffer sb = new StringBuffer();//存放随机的字符串 //循环出验证码的字符串 for (int i = 0; i < 4; i++) { int index = r.nextInt(str.length());//返回的是0到length(不包含本身)之间的整数 g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));//随机颜色 String s = str.substring(index, index + 1);//包头不包尾 sb.append(s);//把选出的字符连接到一起 g.drawString(s, 20 * i + 10, 25 + r.nextInt(20)); } //画线 for (int i = 0; i < 10; i++) { g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));//随机颜色 g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height)); } for (int i = 0; i < 4; i++) { g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));//随机颜色 g.drawArc(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height),r.nextInt(360),r.nextInt(360)); } //写入session session.setAttribute("yanzhengma", sb); //输出jsp response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0);
ServletOutputStream sos = response.getOutputStream(); ImageIO.write(bi, "png", sos); sos.close(); %> |
<% String val = request.getParameter("ff"); Object sb = session.getAttribute("yanzhengma"); if (val.equals(sb)) { out.print("1"); } else { out.print("0"); } %> |