验证码的生成思想是在服务器段预先生成好验证码,前台显示,然后再到后台去匹配! code.jsp: <%@ page language="java" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" contentType="image/jpeg" pageEncoding="UTF-8"%> <% //设置页面不缓存 response.setHeader("Pragma","No-cache"); response.setHeader("Cahce-Control","no-cache"); response.setDateHeader("Expires",0); //在内存中创建图片 int width=58; int height=20; BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //获取图形上下文 Graphics g= image.getGraphics(); //生成随机类 Random random= new Random(); //设置背景颜色 g.setColor(new Color(150,200,100)); g.fillRect(0,0,width,height); //设置字体 g.setFont(new Font("Times New Roman",Font.PLAIN,18)); //随机产生50条干扰线,使图形中的验证码不易被其他的程序探测到 g.setColor(new Color(150,200,100)); for(int i=0;i<50;i++) { int x=random.nextInt(width); int y=random.nextInt(height); int x1=random.nextInt(width); int y1=random.nextInt(height); g.drawLine(x,y,x+x1,y+y1); } //随机产生验证码(6位数字) String sRand=""; for(int i=0;i<4;i++) { String rand=String.valueOf(random.nextInt(10)); sRand+=rand; //将验证码显示到图象 g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))); g.drawString(rand,13*i+6,16); } session.setAttribute("rand",sRand); //将产生的验证码存储到sesson中 g.dispose(); ImageIO.write(image,"JPEG",response.getOutputStream()); out.clear(); out=pageContext.pushBody(); %> code.jsp把生成的验证码输出成图片格式,所以页面引用时只需要把该也当图片处理! <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'reg.jsp' starting page</title> </head> <body> <h2>验证码</h2><br> 用户名:<input type="text" name="name"><br> 密 码:<input type="password" name="password"><br> 验证码:<input type="text" name="code"> <!-- 引用验证码 --> <img alt="验证码" src="code.jsp" mce_src="code.jsp"><br> <input type="submit" value="登陆"> </body> </html>