Use java to generate background verification code
Nov 06, 2020 pm 03:40 PM Let’s take a look at the effect first:
(Learning video recommendation: java course)
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('valistr','驗證碼不能為空!')"> <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='red'>"+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; /** * 動態(tài)生成圖片 */ 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.創(chuàng)建圖片緩沖區(qū)對象, 并設置寬高和圖像類型 img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 2.得到繪制環(huán)境 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("執(zhí)行成功~!"); }*/ }
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.
