SoFunction
Updated on 2025-04-07

Detailed explanation of JSP's example of verification code production

Detailed explanation of JSP's example of verification code production

Verification code

The verification code (CAPTCHA) is the abbreviation of "Completely Automated Public Turing test to tell Computers and Humans Apart". It is a public fully automatic program that distinguishes whether a user is a computer or a human. It can prevent: maliciously cracking passwords, swiping tickets, and filling the forum, effectively preventing a hacker from constantly logging in with a specific registered user using a specific program to crack it. In fact, using verification codes is the current way of 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. Since computers cannot answer CAPTCHA's questions, the user who answers the questions can be considered human.

 Jsp production verification code

Running environment: tomcat+eclipse+jdk

Basic idea: Now draw a picture of the verification code on the servlet, let it be displayed on the page, and then use the js method to refresh the verification code. You can use ajax to get the value entered by the user and compare it with the verification code to determine whether it is correct, and it meets the prompt user.

Basic methods:

BufferedImage: 

Imageis an abstract column,BufferedImageyesImageImplementation。


ImageandBufferedImage的主要作用就yes将一副图片加载到内存中。
Java将一副图片加载到内存中的方法yes:
JavaCode 
String imgPath = "d:/"; 
BufferedImage image = (new FileInputStream(imgPath)); 
This method can obtain detailed information about the picture,For example:Get the width of the picture:(null);The image can only be processed further if it is loaded in memory.。


Graphics: 

Graphics provides basic geometric drawing methods, mainly including: drawing line segments, drawing rectangles, drawing circles, drawing colored graphics, drawing ellipses, drawing arcs, drawing polygons, etc. I recommend the specific operation content.Detailed explanation of how to draw using Java's Graphics class

Code implementation of verification code

The verification code I made here is displayed in Chinese. You can modify the number, letter or combination of what you want to display in the servlet. You can store these in an array, or convert ASCII codes to random numbers, depending on your personal preferences

First, we can make a verification code in jsp

<div class="row cl">
    <div>
     <input type="text" placeholder="Verification Code" value="Verification code:" onblur="testCheck();">
     <img  src="CheckTestServlet"> <a  onClick="Checktest();">Can't see clearly,Change one</a> </div>
 </div>

Making a Servlet is called

@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 realizes the generation of verification code          ("utf-8");
          //Create the image buffer to set its size BufferedImage(int width, int height, int imageType)         BufferedImage bImage=new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR);
         //Create canvas on the buffer         Graphics g=();
         //Set background color         ();
         //Create canvas rectangle, position (0, 0) point, size 100, 30         (0, 0, 100, 30);
         //Create a random object         Random r=new Random();
         int index;//Storage random numbers         //Storage of texts obtained         StringBuffer sBuffer=new StringBuffer();
         //The loop generates four words         for (int i = 0; i < 4; i++) {
           //The first hexadecimal code of Chinese characters is 4e00 to decimal, which is 19968, and the last one is 9fa0 and decimal, which is 40869, so a random number between them can be generated           index=(40869-19968+1)+19968;//Generate random numbers           //Set random colors,           (new Color((255), (255), (255)));
           //Set the type and size of the text           (new Font("", , 20));
           /*Print characters, convert random numbers into hexadecimal (index), 16) and then convert characters (char)(,
            Set the position of each text
            */
           ((char)(((index),16))+"", i*22+4, 18);
           //Save it in a StringBuffer for later reading for comparison           ((char)(((index),16)));
        }
         //Set the obtained text into the session         ().setAttribute("piccode", ());
         /*Read and write this verification code image to the page
           * write(RenderedImage im, String formatName, OutputStream output)
         */         
         (bImage, "jpg", ());
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }

When doing a js refresh verification code, it is used to not see clearly or other refresh uses

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

Write another Ajax to verify whether the user input is correct and returns the prompt. This is done with jQuery and requires js to be cited.

function testCheck(num){
    $.ajax({
      type:"post",//Submission method      url:"TestCheckServlet",//Submit address      async:true,//Whether asynchronous request      dataType:"html",//Return Type      data:{"num":num},//Passed value      success:function(data,textStatus){//Successful execution method        $("#checks").html(data)
      },
      error:function(){// Method of failed execution        alert("error");
      }
    })
  } 

If you have some trouble, you can do a servlet to verify whether the value transmitted by Ajax matches the verification code.

@WebServlet("/TestCheckServlet")
public class TestCheckServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ("utf-8");
    PrintWriter out=();
    //Get the input verification code and compare the random image verification code to determine whether it is equal, and return to the prompt user.    if (().getAttribute("piccode").toString().equals(("num"))) {
      ("Verification code is correct");
    }else {
      ("Verification code error");
    }
  }


  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }

}

In this way, the verification code has been basically completed, and there are many contents and patterns that need to be modified according to the needs.

The above is the production of the QR code. If you have any questions, please leave a message or go to the community of this website to communicate and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this website!