Java realizes the generation and verification of verification code

Reprinted from: https://www.cnblogs.com/nanyangke-cjz/p/7049281.html

We all know that in order to prevent our website from being maliciously attacked by some people and hackers, such as the registration page of our website, if we do not add a verification code box when users register, others can write a script to perform operations on your website. Malicious registration, such as registering your website n times per minute, then your website will be attacked and crashed. When we add the verification code, when others write the script, they must first identify your verification code, but it is not so easy to identify the content in the image verification code, which can effectively prevent our website from being malicious. registration attack. Without further ado, let's go directly to the code.

A tool class for generating verification codes and verification code pictures

copy code
1 package com.utils;
 2
 3 import java.awt.Color;
 4 import java.awt.Font;
 5 import java.awt.Graphics;
 6 import java.awt.image.BufferedImage;
 7 import java.awt.image.RenderedImage;
 8 import java.io.FileOutputStream;
 9 import java.io.OutputStream;
10 import java.util.HashMap;
11 import java.util.Map;
12 import java.util.Random;
13
14 import javax.imageio.ImageIO;
15
16 public class CodeUtil {
17 private static int width = 90;// Define the width of the picture
18 private static int height = 20;// Define the height of the picture
19 private static int codeCount = 4;// Define the number of verification codes displayed on the picture
20     private static int xx = 15;
21     private static int fontHeight = 18;
22     private static  int codeY = 16;
23     private static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
24             'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
25     
26     /**
27 * Generate a map collection
28 * code is the generated verification code
29 * codePic is the generated verification code BufferedImage object
30      * @return
31      */
32     public static Map<String,Object> generateCodeAndPic() {
33 // Define the image buffer
34         BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
35         // Graphics2D gd = buffImg.createGraphics();
36         // Graphics2D gd = (Graphics2D) buffImg.getGraphics();
37         Graphics gd = buffImg.getGraphics();
38 // Create a random number generator class
39         Random random = new Random();
40 // fill the image with white
41         gd.setColor(Color.WHITE);
42         gd.fillRect(0, 0, width, height);
43
44 // Create a font, the size of the font should be determined according to the height of the image.
45         Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
46 // Set the font.
47         gd.setFont(font);
48
49 // Draw the border.
50         gd.setColor(Color.BLACK);
51         gd.drawRect(0, 0, width - 1, height - 1);
52
53 // Generate 40 interference lines randomly, so that the authentication code in the image is not easy to be detected by other programs.
54         gd.setColor(Color.BLACK);
55         for (int i = 0; i < 30; i++) {
56             int x = random.nextInt(width);
57             int y = random.nextInt(height);
58             int xl = random.nextInt(12);
59             int yl = random.nextInt(12);
60             gd.drawLine(x, y, x + xl, y + yl);
61         }
62
63 // randomCode is used to save the randomly generated verification code for verification after the user logs in.
64         StringBuffer randomCode = new StringBuffer();
65         int red = 0, green = 0, blue = 0;
66
67 // Randomly generate a verification code of codeCount numbers.
68         for (int i = 0; i < codeCount; i++) {
69 // Get the randomly generated verification code number.
70             String code = String.valueOf(codeSequence[random.nextInt(36)]);
71 // Generate random color components to construct the color value, so that the color value of each digit output will be different.
72             red = random.nextInt(255);
73             green = random.nextInt(255);
74             blue = random.nextInt(255);
75
76 // Draw the captcha into the image with a randomly generated color.
77             gd.setColor(new Color(red, green, blue));
78             gd.drawString(code, (i + 1) * xx, codeY);
79
80 // Combine the four random numbers generated.
81             randomCode.append(code);
82         }
83         Map<String,Object> map  =new HashMap<String,Object>();
84 //Store verification code
85         map.put("code", randomCode);
86 //Store the generated verification code BufferedImage object
87         map.put("codePic", buffImg);
88         return map;
89     }
90
91     public static void main(String[] args) throws Exception {
92 //Create a file output stream object
93         OutputStream out = new FileOutputStream("D://img/"+System.currentTimeMillis()+".jpg");
94         Map<String,Object> map = CodeUtil.generateCodeAndPic();
95         ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", out);
96 System.out.println("The value of the verification code is: "+map.get("code"));
97     }
98 }
copy code

 Next is an application demo using jsp and servlet

1.jsp page code

copy code
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Captcha page</title>
 8 <script type="text/javascript"
 9     src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
10 </head>
11 <body>
12     <form action="${pageContext.request.contextPath}/checkCode" method="post">
13 Please enter the verification code: <input type="text" name="code" style="width: 80px;" /> <img id="imgObj" alt="Verification Code"
14             src="${pageContext.request.contextPath}/getCode"><a href="#" onclick="changeImg()">换一张</a><br/> <input
15             type="submit" value="提交" />
16     </form>
17
18 </body>
19 <script type="text/javascript">
20     $(function() {
21
22     });
23
24     function changeImg() {        
25         var imgSrc = $("#imgObj");    
26         var src = imgSrc.attr("src");        
27         imgSrc.attr("src", chgUrl(src));
28     }
29     
30 // timestamp
31 // In order to make the image generated each time inconsistent, that is, to prevent the browser from reading the cache, it is necessary to add a timestamp
32     function chgUrl(url) {
33         var timestamp = (new Date()).valueOf();
34         url = url.substring(0, 20);
35         if ((url.indexOf("&") >= 0)) {
36             url = url + "×tamp=" + timestamp;
37         } else {
38             url = url + "?timestamp=" + timestamp;
39         }
40         return url;
41     }
42
43 </script>
44 </html>
copy code

2. The servlet that generates the verification code in the background

copy code
package com.code;

import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.utils.CodeUtil;

/**
 * Servlet implementation class CodeServlet
 */
@WebServlet("/getCode")
public class CodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Call the verification code and verification code image generated by the tool class
        Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();

        // Save the four-digit verification code to the Session.
        HttpSession session = req.getSession();
        session.setAttribute("code", codeMap.get("code").toString());

        // Disable image caching.
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);

        resp.setContentType("image/jpeg");

        // Output the image to the servlet output stream.
        ServletOutputStream sos;
        try {
            sos = resp.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace ();
        }

    }

}
copy code

3. The servlet that checks the verification code

copy code
package com.code;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String code = request.getParameter("code");
        // Verify verification code
        String sessionCode = request.getSession().getAttribute("code").toString();
        if (code != null && !"".equals(code) && sessionCode != null && !"".equals(sessionCode)) {
            if (code.equalsIgnoreCase(sessionCode)) {
                response.getWriter().println("Verified!");
            } else {
                response.getWriter().println("Validation failed!");
            }
        } else {
            response.getWriter().println("Validation failed!");
        }
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324522148&siteId=291194637