java中验证码的方法

1,在jsp页面中直接生成验证码

[html]  view plain  copy
  1. //image.jsp  
  2. <%@ page contentType="image/jpeg"  
  3.     import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"  
  4.     pageEncoding="GBK"%>  
  5. <%!Color getRandColor(int fc, int bc) {//给定范围获得随机颜色  
  6.         Random random = new Random();  
  7.         if (fc > 255)  
  8.             fc = 255;  
  9.         if (bc > 255)  
  10.             bc = 255;  
  11.         int r = fc + random.nextInt(bc - fc);  
  12.         int g = fc + random.nextInt(bc - fc);  
  13.         int b = fc + random.nextInt(bc - fc);  
  14.         return new Color(r, g, b);  
  15.     }%>  
  16. <%  
  17.     //设置页面不缓存  
  18.     response.setHeader("Pragma", "No-cache");  
  19.     response.setHeader("Cache-Control", "no-cache");  
  20.     response.setDateHeader("Expires", 0);  
  21.   
  22.     // 在内存中创建图象  
  23.     // 通过这里可以修改图片大小  
  24.     int width = 85height = 23;  
  25.     BufferedImage image = new BufferedImage(width, height,  
  26.             BufferedImage.TYPE_INT_RGB);  
  27.   
  28.     // 获取图形上下文  
  29.     // g相当于笔  
  30.     Graphics g = image.getGraphics();  
  31.   
  32.     //生成随机类  
  33.     Random random = new Random();  
  34.   
  35.     // 设定背景色  
  36.     g.setColor(getRandColor(200, 250));  
  37.     // 画一个实心的长方,作为北京  
  38.     g.fillRect(0, 0, width, height);  
  39.   
  40.     //设定字体  
  41.     g.setFont(new Font("黑体", Font.PLAIN, 18));  
  42.   
  43.     //画边框  
  44.     g.setColor(Color.BLUE);  
  45.     g.drawRect(0,0,width-1,height-1);  
  46.   
  47.     // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到  
  48.     g.setColor(getRandColor(160, 200));  
  49.     for (int i = 0; i < 155; i++) {  
  50.         int x = random.nextInt(width);  
  51.         int y = random.nextInt(height);  
  52.         int xl = random.nextInt(12);  
  53.         int yl = random.nextInt(12);  
  54.         g.drawLine(x, y, x + xl, y + yl);  
  55.     }  
  56.   
  57.     // 取随机产生的认证码(4位数字)  
  58.     //String rand = request.getParameter("rand");  
  59.     //rand = rand.substring(0,rand.indexOf("."));  
  60.     String sRand = "";  
  61.     // 如果要使用中文,必须定义字库,可以使用数组进行定义  
  62.     // 这里直接写中文会出乱码,必须将中文转换为unicode编码  
  63.     String[] str = { "A", "B", "C", "D", "E", "F", "G", "H", "J", "K",  
  64.             "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X",  
  65.             "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",  
  66.             "k", "m", "n", "p", "s", "t", "u", "v", "w", "x", "y", "z",  
  67.             "1", "2", "3", "4", "5", "6", "7", "8", "9" };  
  68.   
  69.     for (int i = 0; i < 5; i++) {  
  70.         String rand = str[random.nextInt(str.length)];  
  71.         sRand += rand;  
  72.         // 将认证码显示到图象中  
  73.         g.setColor(new Color(20 + random.nextInt(110), 20 + random  
  74.                 .nextInt(110), 20 + random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成  
  75.         g.drawString(rand, 16 * i + 6, 19);  
  76.     }  
  77.   
  78.     // 将认证码存入SESSION  
  79.     session.setAttribute("rand", sRand);  
  80.   
  81.     // 图象生效  
  82.     g.dispose();  
  83.   
  84.     // 输出图象到页面  
  85.     ImageIO.write(image, "JPEG", response.getOutputStream());  
  86.     out.clear();  
  87.     out = pageContext.pushBody();  
  88. %>  

[html]  view plain  copy
  1. //使用验证码的页面login.jsp  
  2. <%@ page contentType="text/html" pageEncoding="GBK"%>  
  3. <html>  
  4.     <head>  
  5.         <title>登陆页面</title>  
  6.         <script>  
  7.     function reloadImage() {   
  8.         document.getElementById('identity').src = 'image.jsp?ts=' + new Date()  
  9.                 .getTime();  
  10.     }  
  11. </script>  
  12.     </head>  
  13.     <body>  
  14.         <center>  
  15.             <%  
  16.                 // 乱码解决  
  17.                 request.setCharacterEncoding("GBK");  
  18.             %>  
  19.             <h1>  
  20.                 登陆程序  
  21.             </h1>  
  22.             <hr>  
  23.             <%=request.getAttribute("info") != null ? request  
  24.                     .getAttribute("info") : ""%>  
  25.             <form action="check.jsp" method="post">  
  26.                 用户ID:  
  27.                 <input type="text" name="mid">  
  28.                 <br>  
  29.                 密  码:  
  30.                 <input type="password" name="password">  
  31.                 <br>  
  32.                 验证码:  
  33.                 <input type="text" name="code"  maxlength="5" size="5">  
  34.                 <img src="image.jsp" id="identity" onclick="reloadImage()" title="看不清,点击换一张">  
  35.                 <br>  
  36.                 <input type="submit" value="登陆">  
  37.                 <input type="reset" value="重置">  
  38.             </form>  
  39.         </center>  
  40.     </body>  
  41. </html>  

效果如下:

2,使用Servlet生成验证码

[java]  view plain  copy
  1. //IdentityServlet.java代码如下:  
  2. package com.helloweenvsfei.servlet;  
  3.   
  4. import java.awt.Color;  
  5. import java.awt.Font;  
  6. import java.awt.Graphics2D;  
  7. import java.awt.image.BufferedImage;  
  8. import java.io.IOException;  
  9. import java.util.Random;  
  10.   
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.ServletOutputStream;  
  13. import javax.servlet.http.HttpServlet;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16.   
  17. import com.sun.image.codec.jpeg.JPEGCodec;  
  18. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  19.   
  20. public class IdentityServlet extends HttpServlet {  
  21.   
  22.     /** 
  23.      *  
  24.      */  
  25.     private static final long serialVersionUID = -479885884254942306L;  
  26.   
  27.     public static final char[] CHARS = { '2''3''4''5''6''7''8',  
  28.             '9''A''B''C''D''E''F''G''H''J''K''L''M',  
  29.             'N''P''Q''R''S''T''U''V''W''X''Y''Z' };  
  30.   
  31.     public static Random random = new Random();  
  32.   
  33.     public static String getRandomString() {  
  34.         StringBuffer buffer = new StringBuffer();  
  35.         for (int i = 0; i < 6; i++) {  
  36.             buffer.append(CHARS[random.nextInt(CHARS.length)]);  
  37.         }  
  38.         return buffer.toString();  
  39.     }  
  40.   
  41.     public static Color getRandomColor() {  
  42.         return new Color(random.nextInt(255), random.nextInt(255), random  
  43.                 .nextInt(255));  
  44.     }  
  45.   
  46.     public static Color getReverseColor(Color c) {  
  47.         return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c  
  48.                 .getBlue());  
  49.     }  
  50.   
  51.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  52.             throws ServletException, IOException {  
  53.   
  54.         response.setContentType("image/jpeg");  
  55.   
  56.         String randomString = getRandomString();  
  57.         request.getSession(true).setAttribute("randomString", randomString);  
  58.   
  59.         int width = 100;  
  60.         int height = 30;  
  61.   
  62.         Color color = getRandomColor();  
  63.         Color reverse = getReverseColor(color);  
  64.   
  65.         BufferedImage bi = new BufferedImage(width, height,  
  66.                 BufferedImage.TYPE_INT_RGB);  
  67.         Graphics2D g = bi.createGraphics();  
  68.         g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));  
  69.         g.setColor(color);  
  70.         g.fillRect(00, width, height);  
  71.         g.setColor(reverse);  
  72.         g.drawString(randomString, 1820);  
  73.         for (int i = 0, n = random.nextInt(100); i < n; i++) {  
  74.             g.drawRect(random.nextInt(width), random.nextInt(height), 11);  
  75.         }  
  76.   
  77.         // 转成JPEG格式  
  78.         ServletOutputStream out = response.getOutputStream();  
  79.         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
  80.         encoder.encode(bi);  
  81.         out.flush();  
  82.     }  
  83.   
  84.     public static void main(String[] args) {  
  85.         System.out.println(getRandomString());  
  86.     }  
  87. }  

[html]  view plain  copy
  1. //Web.xml的配置为:  
  2. <servlet>  
  3.     <servlet-name>IdentityServlet</servlet-name>  
  4.     <servlet-class>com.helloweenvsfei.servlet.IdentityServlet</servlet-class>  
  5. </servlet>  
  6. <servlet-mapping>  
  7.     <servlet-name>IdentityServlet</servlet-name>  
  8.     <url-pattern>/servlet/IdentityServlet</url-pattern>  
  9. </servlet-mapping>  

[html]  view plain  copy
  1. //测试页面identity.html为:  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4.     <head>  
  5.         <title>identity.html</title>  
  6.   
  7.         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  8.         <meta http-equiv="description" content="this is my page">  
  9.         <meta http-equiv="content-type" content="text/html; charset=GB18030">  
  10.   
  11.         <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  
  12.   
  13.     </head>  
  14.   
  15.     <body>  
  16.   
  17. <script>  
  18.     function reloadImage() {  
  19.         document.getElementById('btn').disabled = true;  
  20.         document.getElementById('identity').src='servlet/IdentityServlet?ts=' + new Date().getTime();  
  21.     }  
  22.     </script>  
  23.   
  24.         <img src="servlet/IdentityServlet" id="identity" onload="btn.disabled = false; " />  
  25.         <input type=button value=" 换个图片 " onclick="reloadImage()" id="btn">  
  26.   
  27.     </body>  
  28. </html>  

3,在Struts2应用中生成验证码

[java]  view plain  copy
  1. //RandomNumUtil.java  
  2. package org.ml.util;  
  3.   
  4. import java.awt.Color;  
  5. import java.awt.Font;  
  6. import java.awt.Graphics;  
  7. import java.awt.image.BufferedImage;  
  8. import java.io.ByteArrayInputStream;  
  9. import java.io.ByteArrayOutputStream;  
  10. import java.util.Random;  
  11. import javax.imageio.ImageIO;  
  12. import javax.imageio.stream.ImageOutputStream;  
  13.   
  14. public class RandomNumUtil {  
  15.     public static final char[] CHARS = {'A''B''C''D''E''F''G''H''J''K''L''M',  
  16.         'N''P''Q''R''S''T''U''V''W''X''Y''Z','2''3''4''5''6''7''8',  
  17.         '9','a''b''c''d''e''f''g''h''i''j''k''m',  
  18.         'n''q''r''s''t''u''v''w''x''y''z'};   
  19.     private ByteArrayInputStream image;// 图像  
  20.     private String str;// 验证码  
  21.     /** 
  22.      *  构造方法调用初始化属性方法 
  23.      */  
  24.     private RandomNumUtil() {  
  25.         init();  
  26.     }  
  27.   
  28.     /** 
  29.      * 取得RandomNumUtil实例 
  30.      */  
  31.     public static RandomNumUtil Instance() {  
  32.         return new RandomNumUtil();  
  33.     }  
  34.   
  35.     /** 
  36.      * 取得验证码图片 
  37.      */  
  38.     public ByteArrayInputStream getImage() {  
  39.         return this.image;  
  40.     }  
  41.   
  42.     /** 
  43.      * 取得图片的验证码 
  44.      */  
  45.     public String getString() {  
  46.         return this.str;  
  47.     }  
  48.       
  49.     /** 
  50.      * 初始化属性否具体方法 
  51.      */  
  52.     private void init() {  
  53.         // 在内存中创建图象  
  54.         int width = 85, height = 18;  
  55.         //设置图形的高度和宽度,以及RGB类型  
  56.         BufferedImage image = new BufferedImage(width, height,  
  57.                 BufferedImage.TYPE_INT_RGB);  
  58.         // 获取图形上下文  
  59.         Graphics g = image.getGraphics();  
  60.         // 生成随机类  
  61.         Random random = new Random();  
  62.         // 设定背景色  
  63.         g.setColor(getRandColor(200250));  
  64.         g.fillRect(00, width, height);  
  65.         // 设定字体  
  66.         g.setFont(new Font("Times New Roman", Font.PLAIN, 18));  
  67.         // 随机产生255条干扰线,使图象中的认证码不易被其它程序探测到  
  68.         g.setColor(getRandColor(160200));  
  69.         for (int i = 0; i < 255; i++) {  
  70.             int x = random.nextInt(width);  
  71.             int y = random.nextInt(height);  
  72.             int xl = random.nextInt(12);  
  73.             int yl = random.nextInt(12);  
  74.             g.drawLine(x, y, x + xl, y + yl);  
  75.         }  
  76.         // 取随机产生的认证码(6位数字)  
  77.         StringBuffer sRand = new StringBuffer();    
  78.         for (int i = 0; i < 6; i++) {  
  79.             String rand = String.valueOf(CHARS[random.nextInt(CHARS.length-1)]);//从字符数组中随机产生一个字符  
  80.             sRand.append(rand);   
  81.             // 将认证码显示到图象中  
  82.             g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));  
  83.             // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成  
  84.             g.drawString(rand, 13 * i + 617);  
  85.         }  
  86.         // 赋值验证码  
  87.         this.str = sRand.toString();  
  88.   
  89.         // 图象生效  
  90.         g.dispose();  
  91.         //下面将生成的图形转变为图片  
  92.         ByteArrayOutputStream output = new ByteArrayOutputStream();   
  93.         ByteArrayInputStream input = null;  
  94.         try {  
  95.             ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);  
  96.             ImageIO.write(image, "JPEG", imageOut);//将图像按JPEG格式写入到imageOut中,即存入到output的字节流中  
  97.             imageOut.close();//关闭写入流  
  98.             input = new ByteArrayInputStream(output.toByteArray());//input读取output中的图像信息  
  99.         } catch (Exception e) {  
  100.             System.out.println("验证码图片产生出现错误:" + e.toString());  
  101.         }  
  102.   
  103.         this.image = input;/* 赋值图像 */  
  104.     }   
  105.     /* 
  106.      * 给定范围获得随机颜色 
  107.      */  
  108.     private Color getRandColor(int fc, int bc) {  
  109.         Random random = new Random();  
  110.         if (fc > 255)  
  111.             fc = 255;  
  112.         if (bc > 255)  
  113.             bc = 255;  
  114.         int r = fc + random.nextInt(bc - fc);  
  115.         int g = fc + random.nextInt(bc - fc);  
  116.         int b = fc + random.nextInt(bc - fc);  
  117.         return new Color(r, g, b);  
  118.     }  
  119. }  

[java]  view plain  copy
  1. //RandomAction.java的代码:  
  2. package org.ml.action;  
  3.   
  4. import java.io.ByteArrayInputStream;  
  5.   
  6. import org.ml.util.RandomNumUtil;  
  7.   
  8. import com.opensymphony.xwork2.ActionContext;  
  9. import com.opensymphony.xwork2.ActionSupport;  
  10.   
  11. @SuppressWarnings("serial")  
  12. public class RandomAction extends ActionSupport {  
  13.     private ByteArrayInputStream inputStream;  
  14.   
  15.     public String execute() throws Exception {  
  16.         RandomNumUtil rdnu = RandomNumUtil.Instance();//取得随机验证码产生类的对象  
  17.         this.setInputStream(rdnu.getImage());// 取得带有随机字符串的图片  
  18.         ActionContext.getContext().getSession().put("random", rdnu.getString());// 取得随机字符串放入HttpSession  
  19.         return SUCCESS;  
  20.     }  
  21.   
  22.     public void setInputStream(ByteArrayInputStream inputStream) {  
  23.         this.inputStream = inputStream;  
  24.     }  
  25.   
  26.     public ByteArrayInputStream getInputStream() {  
  27.         return inputStream;  
  28.     }  
  29. }  

[html]  view plain  copy
  1. //struts.xml配置为:  
  2. <!-- Random验证码 -->  
  3. <action name="rand" class="org.ml.action.RandomAction">  
  4.     <result type="stream" name="success">  
  5.     <param name="contentType">image/JPEG</param>  
  6.     <param name="inputName">inputStream</param>  
  7.     </result>  
  8. </action>  

[html]  view plain  copy
  1. //HTML中的表单代码为:  
  2. <tr  height="35" >  
  3.  <td width="14%" class="top_hui_text">  
  4.   <span class="login_txt"> 验证码:    </span>  
  5.  </td>  
  6.  <td colspan="2" class="top_hui_text">  
  7.   <input type="text" name="rand" id="rand" size="6"  
  8.    maxlength="6">  
  9.      <script type="text/javascript">   
  10.   function changeValidateCode(obj) {   
  11.   //获取当前的时间作为参数,无具体意义   
  12.    var timenow = new Date().getTime();   
  13.   //每次请求需要一个不同的参数,否则可能会返回同样的验证码   
  14.   //这和浏览器的缓存机制有关系,也可以把页面设置为不缓存,这样就不用这个参数了。   
  15.    obj.src="rand.action?d="+timenow;   
  16.   }   
  17.   </script>  
  18.   <img src="rand.action" title="点击图片刷新验证码"  
  19.    onclick="changeValidateCode(this)" height="22"  
  20.    width="80" />  
  21.  </td>   
  22. </tr>  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值