1.生成验证码
<%@ page language="java" pageEncoding="UTF-8"%> <%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %> <%! public Color getColor(){ Random random = new Random(); int r = random.nextInt(256); int g = random.nextInt(256); int b = random.nextInt(256); return new Color(r,g,b); } public String getNum(){ String str = ""; Random random = new Random(); for(int i=0;i<4;i++){ str += random.nextInt(10); } return str; } %> <% response.setHeader("pragma", "mo-cache"); response.setHeader("cache-control", "no-cache"); response.setDateHeader("expires", 0); BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setColor(new Color(200,200,200)); g.fillRect(0,0,80,30); for (int i = 0; i < 30; i++) { Random random = new Random(); int x = random.nextInt(80); int y = random.nextInt(30); int xl = random.nextInt(x+10); int yl = random.nextInt(y+10); g.setColor(getColor()); g.drawLine(x, y, x + xl, y + yl); } g.setFont(new Font("serif", Font.BOLD,16)); g.setColor(Color.BLACK); String checkNum = getNum();//"2525" StringBuffer sb = new StringBuffer(); for(int i=0;i<checkNum.length();i++){ sb.append(checkNum.charAt(i)+" ");//"2 5 2 5" } g.drawString(sb.toString(),15,20); session.setAttribute("CHECKNUM",checkNum);//2525 ImageIO.write(image,"jpeg",response.getOutputStream()); out.clear(); out = pageContext.pushBody(); %>
2.添加验证码
<tr> <th>验证码:</th> <td><input size="2" type="text" name="checkcode" id="checkcodeID" maxlength="4"/></td> <td id="checked" ><img id="imageId" src="${pageContext.request.contextPath }/jsp/01_image.jsp"/> <td id="response"></td> </tr>
3.创建AJAX
function createAJAX(){ var ajax = null; try{ ajax = new ActiveXObject("microsoft.xmlhttp"); }catch(e1){ try{ ajax = new XMLHttpRequest(); }catch(e2){ alert("你的浏览器不支持ajax!"); } } return ajax; }
4.异步方式进行验证
<!-- 去除空格 --> <script type="text/javascript"> //去掉二边的空格 function trim(str){ str = str.replace(/^\s*/,""); str = str.replace(/\s*$/,""); return str; } </script> <!-- 异步判断验证码输入是否正确 --> <script type="text/javascript"> document.getElementById("checkcodeID").onkeyup = function(){ var checkcode = this.value; checkcode = trim(checkcode); if(checkcode.length == 4){ //NO1)创建AJAX var ajax = createAJAX(); //NO2)设置提交方式 var method = "POST"; var url = "${pageContext.request.contextPath}/dictionary_checked?time="+new Date().getTime(); ajax.open(method,url); //NO3)设置请求头 ajax.setRequestHeader("content-type","application/x-www-form-urlencoded"); //NO4)设置参数 var content = "checkcode=" + checkcode; ajax.send(content); //--------------------------------------------------------等待 //NO5)判断是否返回成功并接收参数 ajax.onreadystatechange = function(){ if(ajax.readyState == 4){ if(ajax.status == 200){ //NO6) var tip = ajax.responseText; //NO7) var img = document.createElement("img"); img.src = tip; img.style.width = "14px"; img.style.height = "14px"; var td = document.getElementById("response"); td.innerHTML = ""; td.appendChild(img); } } } }else{ //清空图片 var td = document.getElementById("response"); td.innerHTML = ""; } } </script>
5.后台验证
/** * 验证 */ public String checked() throws Exception { // 图片路径 String tip = "images/error.gif"; // 从服务器获取session中的验证码 String checkcodeServer = (String) ActionContext.getContext() .getSession().get("CHECKNUM"); // 将客户端的验证码与服务端的验证码进行比较 if (checkcode.equals(checkcodeServer)) { tip = "images/success.gif"; } // 以IO流的方式将tip变量的值输出到AJAX异步对象中 HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(tip); pw.flush(); pw.close(); return null; }
6.提交验证
function submit2(){ //获取js对象 var td = document.getElementById("response"); var img=td.firstChild; //获取路径信息 var src2=img.src; //对输入的结果进行判定,选择是否提交 if(src2==""){ alert("验证码不能为空!"); }else if(src2=="http://localhost:8080/BBS/jsp/images/success.gif"){ var for2=document.forms[0]; for2.submit(); }else{ alert("验证码输入错误!"); } } </script>
7.总结:
(1)暂时无法实现点击更换验证码
(2)js方式过于繁琐,代码臃肿;