---------------------------------------------------------------------------------------------------------------
[版权申明:本文系作者原创,转载请注明出处]
文章出处:http://www.jb51.cc/article/p-rlqyommt-vc.html
作者:朱培 ID:sdksdk0
---------------------------------------------------------------------------------------------------------------
今天分享的是通过ajax来动态的验证验证码输入是否正确。我们这里采用的是ajax+struts2来做的这个验证。 我们新建一个web工程。然后需要导入struts的相应包。之后我们需要写一个类来生成验证码。
这里命名为01_image.jsp,这类的主要功能就是生成验证码,里面是各种画线条,随机数字等,我这里设置的是5个数字的验证,如果你想要改成其他的也可以,大致思路就是在生成数字的那个循环那里加上字母就可以了。
<%@ 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);//0-255 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<5;i++){ str += random.nextInt(10);//0-9 } return str; } %> <% response.setHeader("pragma","no-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,80,30); for (int i = 0; i < 50; 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(); %>