Java Web Implementation of verification code -- super simple code

Keywords: Java JSP Session

1. Front end display

HTML:

<h3>Verification Code:</h3>
<input type="text" name="validationCode" id="validationCode" placeholder="Please enter the verification code" lay-verify="required"> 
<img src="validate.jsp" id="validationCode_img" title="Invisibility?Change another one" onclick="loadimage();return false;" name="validationCode_img" align="middle">

JS:

//Load the captcha image, and add time after it to ensure that the captcha will refresh every time the page is refreshed
function loadimage(){
            document.getElementById("validationCode_img").src= "validate.jsp?time=" + new Date().getTime();
        }

2. Use a page to generate the verification code image. Here I use the JSP page validate.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="java.awt.Graphics2D"%>
<%@page import="java.awt.Color"%>
<%@page import="java.awt.Font"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.util.Random"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Verification Code</title>
</head>
<body>
<%
    int width = 60;
    int height = 20;
    // Create a Image
    BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
    Graphics2D g = buffImg.createGraphics();
    
    // Create a random number generator
    Random random = new Random();
    
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    
    // To create a font, the size of the font should be based on the height of the picture
    Font font = new Font("Times New Roman", Font.PLAIN, 18);
    // Set font
    g.setFont(font);
    
    // Draw borders
    g.setColor(Color.BLACK);
    g.drawRect(0, 0, width - 1, height - 1);
    
    // Randomly generate 160 interference lines
    g.setColor(Color.LIGHT_GRAY);
    for (int i = 0; i < 160; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int x1 = random.nextInt(12);
        int y1 = random.nextInt(12);
        g.drawLine(x, y, x + x1, y + y1);
    }
    
    // randomCode Used to save randomly generated verification code
    StringBuffer randomCode = new StringBuffer();
    int red = 0, green = 0, blue = 0;
    
    // Random generation of 4-digit verification code
    for (int i = 0; i < 4; i++) {
        // Get randomly generated verification code number
        String strRand = String.valueOf(random.nextInt(10));
    
        // Generate random color components to construct color values
        red = random.nextInt(110);
        green = random.nextInt(50);
        blue = random.nextInt(50);
    
        // Draw verification code into image with randomly generated color
        g.setColor(new Color(red, green, blue));
        g.drawString(strRand, 13 * i + 6, 16);
    
        randomCode.append(strRand);
    }
    
    // Save the four digit verification code to session in
    //HttpSession session = request.getSession();
    session.setAttribute("randomCode", randomCode.toString());
    
    // Disable image caching
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    
    response.setContentType("image/jpeg");
    // Output image to servlet Output stream
    ServletOutputStream sos = response.getOutputStream();
    ImageIO.write(buffImg, "jpeg", sos);
    sos.close();
    //sos = null;
    out.clear();
    out = pageContext.pushBody();
%>
</body>
</html>

3. The verification code generated in the validate.jsp page is actually generated in the java backend, so it is stored in the session. We only need to bring the verification code filled in to the backend when the user submits it. Here I use the ajax request, and the backend only needs to judge whether the verification code is the same as in the session.

Posted by mikefn on Wed, 13 Nov 2019 06:02:09 -0800