Implementation verification code function

2011-08-08  来源:本站原创  分类:Internet  人气:110 

Recently, get a modest class of sns project, need to use authentication code record. Code is as follows, mainly implemented in serlet images generated with random numbers, random number and then synchronize to the session

package com.ecar.portal.common.servlet;
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.*;

/**
 *  Function : Calling AuthServlet can generate a validation code pictures , The width and height of the picture, you can customize
 *  Call format : /servlet/AuthServlet?width=60&height=20
 *       Or /servlet/AuthServlet
 *  Time :2010-8-6
 *
 * @author: lyj
 */
public class VerifyServlet extends HttpServlet {
 private Font mFont=new Font("Times New Roman", Font.BOLD,22);// Setting the font
 //static String AuthCode="";

//  Processing post
 public void doPost(HttpServletRequest request,HttpServletResponse response)
 throws ServletException,IOException {
   doGet(request,response);
 }

 public void doGet(HttpServletRequest request,HttpServletResponse response)
     throws ServletException,IOException {
//  Made a 1000-9999 random number 

    //System.out.println("servlert Method call ");
     HttpSession session=request.getSession();//request.getSession(false) When parameter is false, , Could not create session
        //session.setAttribute("getImg",s);
     response.setContentType("image/gif");
     response.setHeader("Pragma","No-cache");
     response.setHeader("Cache-Control","no-cache");
     response.setDateHeader("Expires", 0);
     int width=60;
     int height=20;
     if(request.getParameter("width")!=null && !request.getParameter("width").equals(""))
      width = Integer.parseInt(request.getParameter("width"));
     if(request.getParameter("height")!=null && !request.getParameter("height").equals(""))
      height = Integer.parseInt(request.getParameter("height"));

     ServletOutputStream out=response.getOutputStream();
     BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); // Set picture size
     Graphics gra=image.getGraphics();
     Random random=new Random();

     gra.setColor(getRandColor(233,244));    // Set background color
     gra.fillRect(0,0,width,height);

     gra.setColor(Color.black); // Set font color
     gra.setFont(mFont);

     //  Randomly generated 155 interference lines , The authentication code in the image is not easy to be detected by other programs
     gra.setColor(getRandColor(160,200));
     for (int i=0;i<150;i++)
     {
      int x = random.nextInt(width);
      int y = random.nextInt(height);
             int xl = random.nextInt(12);
             int yl = random.nextInt(12);
      gra.drawLine(x,y,x+xl,y+yl);
     }

     //  Preparation of randomly generated authentication code (4 Digits )
     String sRand="";
     for (int i=0;i<4;i++){
        String rand=String.valueOf(random.nextInt(10));
        sRand+=rand;
        //  To display the authentication code to images
        gra.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));// Call functions out of the same color, because the seeds may be too close , Only direct creation
        gra.drawString(rand,13*i+6,18);
    }
        //ystem.out.println("showimage="+sRand);
        //session.setAttribute("getImg",sRand);
        session.setAttribute("AuthCode",sRand);

        //AuthCode = sRand;
        //session.putValue("AuthCode",sRand);
        JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
        encoder.encode(image);
        //out.flush();

}

  static Color getRandColor(int fc,int bc){// Get random colors the given range
         Random random = new Random();
         if(fc>255) fc=255;
         if(bc>255) bc=255;
         int r=fc+random.nextInt(bc-fc);
         int g=fc+random.nextInt(bc-fc);
         int b=fc+random.nextInt(bc-fc);
         return new Color(r,g,b);
  }

  static public String getAuthCode(HttpSession session){// Returns the validation
   return (String)session.getAttribute("AuthCode");

  }
}
相关文章
  • Implementation verification code function 2011-08-08

    Recently, get a modest class of sns project, need to use authentication code record. Code is as follows, mainly implemented in serlet images generated with random numbers, random number and then synchronize to the session package com.ecar.portal.comm

  • Using Rails Captcha plug-in, easy implementation Verification Code 2009-03-01

    Simple Captcha Plugin Can help us easily in the Rails implementation of Verification Code function. In addition, he has the option to provide sufficient to meet the U.S. requirements for certification, the use of easy. Supported picture and digital a

  • Landing page Implementation Verification Code 2010-04-14

    Written using struts2 framework, the validation of the code written in the action, in the pages of this <img scr="***.action"> direct calls to verify the code image can be obtained, and verified the contents of code to directly setAttribut

  • Verification Code Rails implementation continued 2009-03-03

    http://sanyking.javaeye.com/blog/120339 Connect with the address above on this website are one of the other way regarding the implementation Verification Code article, my article are based on the above completed, and the world is one big copy article

  • More comprehensive verification code php 2011-05-17

    First, download the fonts to download into the item verdana.ttf <?php session_start(); /** * Random numbers, and the verification code */ function getCode ($length = 32, $mode = 0) { switch ($mode) { case '1': $str = '123456789'; break; case '2': $st

  • Image verification code java implementation 2010-05-16

    Image verification code java implementation ImageGenerator generate a random number of images containing 4 Java code package com.my.page; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; impo

  • How to identify high-level verification code 2010-07-13

    First, the basics of verification code 1. The main purpose of validation code is mandatory human-computer interaction to automate attacks against the machine. 2. Most of the verification code designers, and to no avail, do not understand the image pr

  • AJAX + jsp without refresh verification code examples 2010-08-08

    We are doing validation code is often due to the counter when to verify the interference sometimes intentionally add more factors, then verification code displayed is not clear that users often enter the wrong. This will not only have to refresh the

  • php_ transferred verification code __ 2010-12-19

    php Code [tilt, sinusoidal interference line, paste, rotate] Did not write a long post. Has been busy with new projects. Recently, doing verification code program, always wanted a simple and generous, automatic identification more difficult. When sor

  • Technical data verification code ----- REVIEW 2011-09-08

    The role of verification code: effectively prevent this problem for a particular registered user to use brute force approach to a specific program constantly landing attempt, in fact, is verification code is the way many Web site traffic (such as inv

  • Asynchronous manner using the Verification Code Inspection 2009-05-18

    This is the Internet found the source code to solve this Dongdong at my B / S mode Verification Code to do the problem, let me feel the real B / S mode, the development of the real situation. /* namespacing object */ var net=new Object(); net.READY_S

  • struts2 to achieve image verification code 2010-03-29

    There is nothing to say. Hehe depends on the following line of code. He He did not have time so it can not explain. Oh,,,, see the amount of action package com.comm.validateNumImage.action; import java.awt.Color; import java.awt.Font; import java.awt

  • ofbiz verification code to achieve 2008-06-22

    Ofbiz see a verification code from the implementation code, to justice reserve Login.flt In <img align=absbottom vspace=2 border=0 src="<@ofbizUrl>/CreateImage?Image=${encryRandom}&Rgb=255|0|0</@ofbizUrl>" title=" The ver

  • java generated verification code and digital color Chinese Code 2010-03-30

    1. Chinese Color Code <%@ page contentType="image/jpeg" import="java.io.*,java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" pageEncoding="UTF-8" %> <%! // Generates a random color Color getRandColor(Random ran

  • In the servlet generated pages in the verification code: 2010-04-14

    package com.ctcsys.util; import javax.servlet .*; import javax.servlet.http .*; import java.io. *; import java.util .*; import java.awt.image .*; import java.awt .*; import javax.imageio .*; public class CodeMakerServlet extends HttpServlet ... ( / /

  • Generated image verification code 2010-05-07

    BS code are comments. <?php $width = "70";// Picture width $height = "25";// Pictures of high $len = "4";// Several of the verification code generated $bgcolor = "#ffffff";// Background color $noise = true;// Gen

  • . NET using the normal processes generate verification code! 2010-05-11

    Sirloin brother watching the news release system, there is mentioned a verification code applet. To write down <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta h

  • thinkphp verification code can not display the strange solution 2010-05-14

    Today in the project thinkphp verification code can not be displayed, then the forum search, most problems or bom, was able to show that after the closure of debug verification code, tried, really, close the debug to normal, but a turn debug on is no

  • discuz in uccenter the verification code 2010-06-04

    2010-01-07 Thumbnail display Article Category: PHP programming Spent a morning time, and finally extracted, and results presentation: Here is the code: <?php session_start(); class seccode { var $code ; // The verification code var $type = 0; // Can

  • Build and calls the verification code 2010-06-07

    using System; using System.Drawing; using System.Drawing.Imaging; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace bookShop.Web ( public partial class validateCode: System.Web.UI.Page ( protected void Page_Load (objec