Home Java Javagetting Started Use java to generate background verification code

Use java to generate background verification code

Nov 06, 2020 pm 03:40 PM
java Verification code

Use java to generate background verification code

Let’s take a look at the effect first:

(Learning video recommendation: java course)

Use java to generate background verification code

1. Applicable requirements

Generate verification code in the background for login verification.

2. Implementation process

1. View layer idea

(1) input is used to enter the verification code, and an img is used to display the verification code

(2) Verify whether the entered verification code is qualified, double-click the img to refresh the verification code, and bind the onblue lost focus event (an event triggered when the mouse loses focus)

(3) Verify in the onblue event,

(4) The src attribute value in img is the method request path for generating verification code in the background (that is, the path of requestMapping). When you click the verification code again, you can dynamically set the src attribute (the original access address is random Timestamp to prevent the browser from not accessing the same path)

Note: The background directly returns the picture, not the characters of the verification code! If characters are returned, the verification code will lose its meaning (the front desk can easily You can obtain the verification code characters and perform multiple malicious visits) (This takes system security into consideration)

2. Back-end ideas
Use the BufferedImage class to create a picture, and then use Graphics2D to process the picture. Just draw (generate random characters and add interference lines). Note: The generated verification code string must be placed in the session for verification of the subsequent login verification code (of course also in the background).

The front-end code is as follows:

            <td class="tds">验证码:</td>
            <td>
                <input type="text" name="valistr" onblur="checkNull(&#39;valistr&#39;,&#39;验证码不能为空!&#39;)">
                <img  src="/static/imghw/default1.png"  data-src="${pageContext.request.contextPath}/servlet/ValiImgServlet"  class="lazy"  id="yzm_img"    style="max-width:90%" onclick="changeYZM(this)"/ alt="Use java to generate background verification code" >
                <span id="valistr_msg"></span>
            </td>
               /**
         * 校验字段是否为空
         */
        function checkNull(name,msg){
            setMsg(name,"")
            var v = document.getElementsByName(name)[0].value;
            if(v == ""){
                setMsg(name,msg)
                return false;
            }
            return true;
        }     
     /**
         * 为输入项设置提示消息
         */
        function setMsg(name,msg){
            var span = document.getElementById(name+"_msg");
            span.innerHTML="<font color=&#39;red&#39;>"+msg+"</font>";
        }
 /**
         * 点击更换验证码
         */
        function changeYZM(imgObj){
            imgObj.src = "${pageContext.request.contextPath}/servlet/ValiImgServlet?time="+new Date().getTime();
        }
Copy after login

The back-end code is as follows:

package cn.tedu.web;

import cn.tedu.util.VerifyCode;

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

/**
 * 获取验证码
 */
public class ValiImgServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //禁止浏览器缓存验证码
        response.setDateHeader("Expires",-1);
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("Pragma","no-cache");
        //生成验证码
        VerifyCode vc = new VerifyCode();
        //输出验证码
        vc.drawImage(response.getOutputStream());
        //获取验证码的值,存储到session中
        String valistr = vc.getCode();
        HttpSession session = request.getSession();
        session.setAttribute("valistr",valistr);
        //打印到控制台
        System.out.println(valistr);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
Copy after login
package cn.tedu.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
 * 动态生成图片
 */
public class VerifyCode {
	// {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
	private static String[] fontNames = { "宋体", "华文楷体", "黑体", "微软雅黑",  "楷体_GB2312" };
	// 可选字符
	//"23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
	private static String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
	// 背景色
	private Color bgColor = new Color(255, 255, 255);
	// 基数(一个文字所占的空间大小)
	private int base = 30;
	// 图像宽度
	private int width = base * 4;
	// 图像高度
	private int height = base;
	// 文字个数
	private int len = 4;
	// 设置字体大小
	private int fontSize = 22;
	// 验证码上的文本
	private String text;

	private BufferedImage img = null;
	private Graphics2D g2 = null;

	/**
	 * 生成验证码图片
	 */
	public void drawImage(OutputStream outputStream) {
		// 1.创建图片缓冲区对象, 并设置宽高和图像类型
		img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 2.得到绘制环境
		g2 = (Graphics2D) img.getGraphics();
		// 3.开始画图
		// 设置背景色
		g2.setColor(bgColor);
		g2.fillRect(0, 0, width, height);

		StringBuffer sb = new StringBuffer();// 用来装载验证码上的文本

		for (int i = 0; i < len; i++) {
			// 设置画笔颜色 -- 随机
			// g2.setColor(new Color(255, 0, 0));
			g2.setColor(new Color(getRandom(0, 150), getRandom(0, 150),getRandom(0, 150)));

			// 设置字体
			g2.setFont(new Font(fontNames[getRandom(0, fontNames.length)], Font.BOLD, fontSize));

			// 旋转文字(-45~+45)
			int theta = getRandom(-45, 45);
			g2.rotate(theta * Math.PI / 180, 7 + i * base, height - 8);

			// 写字
			String code = codes.charAt(getRandom(0, codes.length())) + "";
			g2.drawString(code, 7 + i * base, height - 8);
			sb.append(code);
			g2.rotate(-theta * Math.PI / 180, 7 + i * base, height - 8);
		}

		this.text = sb.toString();

		// 画干扰线
		for (int i = 0; i < len + 2; i++) {
			// 设置画笔颜色 -- 随机
			// g2.setColor(new Color(255, 0, 0));
			g2.setColor(new Color(getRandom(0, 150), getRandom(0, 150),
					getRandom(0, 150)));
			g2.drawLine(getRandom(0, 120), getRandom(0, 30), getRandom(0, 120),
					getRandom(0, 30));
		}
		//TODO:
		g2.setColor(Color.GRAY);
		g2.drawRect(0, 0, this.width-1, this.height-1);
		// 4.保存图片到指定的输出流
		try {
			ImageIO.write(this.img, "JPEG", outputStream);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			// 5.释放资源
			g2.dispose();
		}
	}

	/**
	 * 获取验证码字符串
	 * @return
	 */
	public String getCode() {
		return this.text;
	}

	/*
	 * 生成随机数的方法
	 */
	private static int getRandom(int start, int end) {
		Random random = new Random();
		return random.nextInt(end - start) + start;
	}

	/*public static void main(String[] args) throws Exception {
		VerifyCode vc = new VerifyCode();
		vc.drawImage(new FileOutputStream("f:/vc.jpg"));
		System.out.println("执行成功~!");
	}*/
}
Copy after login

Summary:

Introduction: It is "Completely Automated Public Turing test to tell Computers and "Humans Apart" (the abbreviation of "Fully Automated Turing Test to Distinguish Computers and Humans") is a public, fully automated program that distinguishes whether a user is a computer or a human.

History: It is the abbreviation of "Completely Automated Public Turing test to tell Computers and Humans Apart". It is a public fully automated test to distinguish whether the user is a computer or a human. program.

Function: Prevent malicious cracking of passwords, ticket brushing, forum flooding, and page brushing.

Category: Gif animation verification code, mobile phone SMS verification code, mobile phone voice verification code, video verification code

Common verification codes:

(1) four-digit sum Letters may be letters or numbers, a random 4-digit string, the most primitive verification code, and the verification effect is almost zero. The CSDN website user login uses GIF format, a commonly used random digital picture verification code. The characters on the picture are quite satisfactory, and the verification effect is better than the previous one.

(2) Chinese characters are the latest verification code currently registered, which is randomly generated and difficult to type, such as the QQ complaint page.

(3) MS hotmail application is in BMP format, with random numbers, random uppercase English letters, random interference pixels, and random positions.

(4) Korean or Japanese, now the MS registration on Paopao HF requires Korean, which increases the difficulty.

(5) Google's Gmail registration is in JPG format, with random English letters, random colors, random positions, and random lengths.

(6) Other major forums are in XBM format, and the content is random

(7) Advertising verification code: Just enter part of the content in the advertisement, which is characterized by bringing additional content to the website Income can also refresh users. Advertising verification code

(8) Question verification code: The question verification code is mainly filled in in the form of question and answer. It is easier to identify and enter than the modular verification code. The system can generate questions such as "1 2=?" for users to answer. Of course, such questions are randomly generated. Another type of question verification code is a text-based question verification code, such as generating the question "What is the full name of China?". Of course, some websites also provide prompt answers or direct answers after the question.

Related recommendations:Getting started with java

The above is the detailed content of Use java to generate background verification code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles