Jsp production verification code, jsp Verification Code

Source: Internet
Author: User
Tags canvas rectangle

Jsp production verification code, jsp Verification Code
Verification Code

CAPTCHA is short for "Completely automatic Public Turing test to tell Computers and Humans Apart" (a Completely Automated Turing test that distinguishes Computers from Humans, it is a fully-automated public program that distinguishes a user from a computer or a person. It can prevent malicious password cracking, ticket flushing, and Forum bumping, effectively preventing a hacker from continuously logging on to a specific registered user using brute force cracking methods of specific programs, in fact, the verification code is now used by many websites. We have implemented this function in a relatively simple way. This question can be generated and judged by computers, but it must be answered by humans. Because the computer cannot answer CAPTCHA's questions, users who answer questions can be considered as humans.

Jsp production verification code running environment: tomcat + eclipse + jdk basic idea: Now draw a verification code image on the Servlet to display it on the page, and then use the js method to refresh the verification code, you can use ajax to obtain the user's input value and compare it with the verification code through servlet to determine whether it is correct, and follow the prompts of the user's basic method:
      • BufferedImage:

          • Image is an abstract column, and BufferedImage is the implementation of Image.
            Image and BufferedImage are mainly used to load a pair of images into the memory.
            Java loads an image to the memory by using the following methods:
            Java code
            String imgPath = "d:/demo.jpg ";
            BufferedImage image = ImageIO. read (new FileInputStream (imgPath ));
            This method can obtain detailed information about the image, for example, obtaining the image width: image. getWidth (null). The image can be further processed only when it is loaded into memory.
      • Graphics:
        • The Graphics class provides basic geometric drawing methods, including: Draw line segments, draw rectangles, draw circles, draw color Graphics, draw an ellipse, draw an arc, draw a polygon, etc, for details about how to use the Graphics class in Java, I recommend that you use the Graphics class.
Code Implementation of the Verification Code

The verification code I made here is to display Chinese characters. You can modify the numbers, letters, and combinations in the servlet. You can store these in arrays, you can also convert the ASCII code to random numbers.

First, create a verification code in jsp.

<Div class = "row cl"> <div> <input type = "text" placeholder = "Verification Code" value = "Verification Code:" onblur = "testCheck (this. value); ">  <a id =" kanbuq "onClick =" Checktest (); "> cannot see clearly, change one </a> </div>

Make a Servlet called CheckTestServlet. java

@ WebServlet ("/CheckTestServlet") public class CheckTestServlet extends HttpServlet {private static final long serialVersionUID = 1L; protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// This method generates a response for the verification code. setCharacterEncoding ("UTF-8"); // create an image buffer and set the BufferedImage (int width, int height, int imageType) BufferedImage bImage = new BufferedImage (100, 30, BufferedImage. TYPE_3BYTE_BGR); // create a canvas Graphics g = bImage in the buffer zone. getGraphics (); // set the background color g. setColor (Color. orange); // create a canvas rectangle with a position (0, 0) and a size of GB. fillRect (0, 0,100, 30); // create Random object Random r = new Random (); int index; // store random numbers // StringBuffer sBuffer = new StringBuffer (); // four words for (int I = 0; I <4; I ++) are generated cyclically) {// The first hexadecimal code of the Chinese text is 4e00 to decimal is 19968, and the last one is 9fa0 to decimal is 40869, so the random index between them can be generated = r. nextInt (40869-19968 + 1) + 19968; // generate random numbers // set random color, g. setColor (new Color (r. nextInt (1, 255), r. nextInt (1, 255), r. nextInt (255); // set the text type, size g. setFont (new Font ("", Font. BOLD, 20);/* draw the random number into a hexadecimal Integer. toHexString (index), 16) character conversion (char) (Integer. parseInt, set the position of each text */g. drawString (char) (Integer. parseInt (Integer. toHexString (index), 16) + "", I * 22 + 4, 18); // store it in the StringBuffer for later reading and comparing sBuffer. append (char) (Integer. parseInt (Integer. toHexString (index), 16);} // set the text to request in the session. getSession (). setAttribute ("piccode", sBuffer. toString ();/* read and write the verification code image to the page * write (RenderedImage im, String formatName, OutputStream output) */ImageIO. write (bImage, "jpg", response. getOutputStream ();} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet (request, response );}

If you are doing a js refresh verification code, you can't see it clearly or use it to refresh it.

    function Checktest(){         var time=new Date().getTime();        $("#pic").attr('src',"CheckTestServlet?d="+time)    }

Write another Ajax code to verify whether the user input is correct and return the prompt. This is done using jQuery and js

Function testCheck (num) {$. ajax ({type: "post", // submission Method url: "TestCheckServlet", // submission address async: true, // asynchronous request dataType: "html ", // return type data: {"num": num}, // pass the previous value success: function (data, textStatus) {// Method for successful execution $ ("# checks" ).html (data)}, error: function () {// method of failed execution alert ("error ");}})}

It's a little troublesome to make a Servlet to verify if the value passed by Ajax matches the verification code.

@ WebServlet ("/TestCheckServlet") public class TestCheckServlet extends HttpServlet {private static final long serialVersionUID = 1L; protected void doGet (HttpServletRequest request, response) throws ServletException, IOException {response. setCharacterEncoding ("UTF-8"); PrintWriter out = response. getWriter (); // compare the entered verification code with the random image verification code to determine whether it is equal. if (request. getSession (). getAttribute ("piccode "). toString (). equals (request. getParameter ("num") {out. println ("correct Verification Code");} else {out. println ("Verification code error") ;}} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet (request, request, response );}}

In this way, the verification code has been basically completed, and there are still many content to be modified, tricks, and instructions based on requirements.

 

[Version Declaration] reprinted, please comment on the source

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.