Home >Java >Javagetting Started >Use java to generate background verification code

Use java to generate background verification code

王林
王林forward
2020-11-06 15:40:391934browse

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  id="yzm_img" src="${pageContext.request.contextPath}/servlet/ValiImgServlet"   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();
        }

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);
    }
}
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("执行成功~!");
	}*/
}

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:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete