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">驗(yàn)證碼:</td> <td> <input type="text" name="valistr" onblur="checkNull('valistr','驗(yàn)證碼不能為空!')"> <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> /** * 校驗(yàn)字段是否為空 */ function checkNull(name,msg){ setMsg(name,"") var v = document.getElementsByName(name)[0].value; if(v == ""){ setMsg(name,msg) return false; } return true; } /** * 為輸入項(xiàng)設(shè)置提示消息 */ function setMsg(name,msg){ var span = document.getElementById(name+"_msg"); span.innerHTML="<font color='red'>"+msg+"</font>"; } /** * 點(diǎn)擊更換驗(yàn)證碼 */ 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; /** * 獲取驗(yàn)證碼 */ public class ValiImgServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //禁止瀏覽器緩存驗(yàn)證碼 response.setDateHeader("Expires",-1); response.setHeader("Cache-Control","no-cache"); response.setHeader("Pragma","no-cache"); //生成驗(yàn)證碼 VerifyCode vc = new VerifyCode(); //輸出驗(yàn)證碼 vc.drawImage(response.getOutputStream()); //獲取驗(yàn)證碼的值,存儲(chǔ)到session中 String valistr = vc.getCode(); HttpSession session = request.getSession(); session.setAttribute("valistr",valistr); //打印到控制臺(tái) 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; /** * 動(dòng)態(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); // 基數(shù)(一個(gè)文字所占的空間大小) private int base = 30; // 圖像寬度 private int width = base * 4; // 圖像高度 private int height = base; // 文字個(gè)數(shù) private int len = 4; // 設(shè)置字體大小 private int fontSize = 22; // 驗(yàn)證碼上的文本 private String text; private BufferedImage img = null; private Graphics2D g2 = null; /** * 生成驗(yàn)證碼圖片 */ public void drawImage(OutputStream outputStream) { // 1.創(chuàng)建圖片緩沖區(qū)對象, 并設(shè)置寬高和圖像類型 img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 2.得到繪制環(huán)境 g2 = (Graphics2D) img.getGraphics(); // 3.開始畫圖 // 設(shè)置背景色 g2.setColor(bgColor); g2.fillRect(0, 0, width, height); StringBuffer sb = new StringBuffer();// 用來裝載驗(yàn)證碼上的文本 for (int i = 0; i < len; i++) { // 設(shè)置畫筆顏色 -- 隨機(jī) // g2.setColor(new Color(255, 0, 0)); g2.setColor(new Color(getRandom(0, 150), getRandom(0, 150),getRandom(0, 150))); // 設(shè)置字體 g2.setFont(new Font(fontNames[getRandom(0, fontNames.length)], Font.BOLD, fontSize)); // 旋轉(zhuǎn)文字(-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++) { // 設(shè)置畫筆顏色 -- 隨機(jī) // 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(); } } /** * 獲取驗(yàn)證碼字符串 * @return */ public String getCode() { return this.text; } /* * 生成隨機(jī)數(shù)的方法 */ 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)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,
