\n \n <\/span>\n <\/div>\n \n <\/div> \n <\/form>\n<\/div>\n \n<\/body>\n<\/html><\/pre>Rendering: <\/p>
<\/p>
The changes in the verification code in the picture received by the console are as follows: <\/p>
<\/p>
When you click to refresh the page, the verification The code will also change, but when we can't see the verification code clearly, just click on the verification code and it will be refreshed. In this way, partial refresh can be achieved with JavaScript. <\/p>
In
, add a question mark and a string of suffix numbers. When refreshing, let the suffix numbers continue to change, then the formed verification code will also will continue to change. One method we can use is to replace the suffix number with date. Date gets the local time. The time changes at any time. This ensures that the refresh verification code can change at any time. <\/p>
The code is as follows: <\/p>
function myRefersh( e ) {\n\t\n\tconst source = e.src ; \/\/ 獲得原來的 src 中的內(nèi)容\n\t\/\/console.log( \"source : \" + source ) ;\n\t\n\tvar index = source.indexOf( \"?\" ) ; \/\/ 從 source 中尋找 ? 第一次出現(xiàn)的位置 (如果不存在則返回 -1 )\n\t\/\/console.log( \"index : \" + index ) ;\n\t\n\tif( index > -1 ) { \/\/ 如果找到了 ? 就進(jìn)入內(nèi)部\n\t\tvar s = source.substring( 0 , index ) ; \/\/ 從 source 中截取 index 之前的內(nèi)容 ( index 以及 index 之后的內(nèi)容都被舍棄 )\n\t\t\/\/console.log( \"s : \" + s ) ;\n\t\t\n\t\tvar date = new Date(); \/\/ 創(chuàng)建一個(gè) Date 對(duì)象的 一個(gè) 實(shí)例\n\t\tvar time = date.getTime() ; \/\/ 從 新創(chuàng)建的 Date 對(duì)象的實(shí)例中獲得該時(shí)間對(duì)應(yīng)毫秒值\n\t\te.src = s + \"?time=\" + time ; \/\/ 將 加了 尾巴 的 地址 重新放入到 src 上\n\t\t\n\t\t\/\/console.log( e.src ) ;\n\t} else {\n\t\tvar date = new Date();\n\t\te.src = source + \"?time=\" + date.getTime();\n\t}\n\t\n}<\/pre>"}
Home
Java
Javagetting Started
Use java to implement a verification code function
Use java to implement a verification code function
Sep 02, 2020 pm 03:55 PM
java
Verification code

Verification codes can be seen everywhere in our daily lives. It can protect the security of our accounts to a certain extent, so how to achieve it?
(Learning video recommendation: java course)
The implementation of the verification code verification function in Java is actually very simple: a Graphics class is used to draw letters on the drawing board, and a certain number is randomly selected. A number of letters are randomly generated, and then several interference lines are randomly generated on the drawing board.
First, write a verification code generation helper class to draw random letters:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public final class GraphicHelper {
/**
* 以字符串形式返回生成的驗(yàn)證碼,同時(shí)輸出一個(gè)圖片
*
* @param width
* 圖片的寬度
* @param height
* 圖片的高度
* @param imgType
* 圖片的類型
* @param output
* 圖片的輸出流(圖片將輸出到這個(gè)流中)
* @return 返回所生成的驗(yàn)證碼(字符串)
*/
public static String create(final int width, final int height, final String imgType, OutputStream output) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.setColor(Color.getColor("F8F8F8"));
graphic.fillRect(0, 0, width, height);
Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN, Color.RED, Color.BLACK, Color.ORANGE,
Color.CYAN };
// 在 "畫板"上生成干擾線條 ( 50 是線條個(gè)數(shù))
for (int i = 0; i < 50; i++) {
graphic.setColor(colors[random.nextInt(colors.length)]);
final int x = random.nextInt(width);
final int y = random.nextInt(height);
final int w = random.nextInt(20);
final int h = random.nextInt(20);
final int signA = random.nextBoolean() ? 1 : -1;
final int signB = random.nextBoolean() ? 1 : -1;
graphic.drawLine(x, y, x + w * signA, y + h * signB);
}
// 在 "畫板"上繪制字母
graphic.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
for (int i = 0; i < 6; i++) {
final int temp = random.nextInt(26) + 97;
String s = String.valueOf((char) temp);
sb.append(s);
graphic.setColor(colors[random.nextInt(colors.length)]);
graphic.drawString(s, i * (width / 6), height - (height / 3));
}
graphic.dispose();
try {
ImageIO.write(image, imgType, output);
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
Then, create a servlet to fix the image size and handle the usage scenarios of the verification code, and Capture the verification code generated by the page (the captured QR code must be consistent with the verification code entered by the user to pass).
import java.io.IOException;
import java.io.OutputStream;
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(urlPatterns = "/verify/regist.do" )
public class VerifyCodeServlet extends HttpServlet {
private static final long serialVersionUID = 3398560501558431737L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 獲得 當(dāng)前請(qǐng)求 對(duì)應(yīng)的 會(huì)話對(duì)象
HttpSession session = request.getSession();
// 從請(qǐng)求中獲得 URI ( 統(tǒng)一資源標(biāo)識(shí)符 )
String uri = request.getRequestURI();
System.out.println("hello : " + uri);
final int width = 180; // 圖片寬度
final int height = 40; // 圖片高度
final String imgType = "jpeg"; // 指定圖片格式 (不是指MIME類型)
final OutputStream output = response.getOutputStream(); // 獲得可以向客戶端返回圖片的輸出流
// (字節(jié)流)
// 創(chuàng)建驗(yàn)證碼圖片并返回圖片上的字符串
String code = GraphicHelper.create(width, height, imgType, output);
System.out.println("驗(yàn)證碼內(nèi)容: " + code);
// 建立 uri 和 相應(yīng)的 驗(yàn)證碼 的關(guān)聯(lián) ( 存儲(chǔ)到當(dāng)前會(huì)話對(duì)象的屬性中 )
session.setAttribute(uri, code);
System.out.println(session.getAttribute(uri));
}
}
(recommended related tutorials: Getting Started with Java)
Then write an HTML registration page to check it out:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注冊(cè)</title>
<link rel="stylesheet" href="styles/general.css">
<link rel="stylesheet" href="styles/cell.css">
<link rel="stylesheet" href="styles/form.css">
<script type="text/javascript" src="js/ref.js"></script>
<style type="text/css" >
.logo-container {
margin-top: 50px ;
}
.logo-container img {
width: 100px ;
}
.message-container {
height: 80px ;
}
.link-container {
height: 40px ;
line-height: 40px ;
}
.link-container a {
text-decoration: none ;
}
</style>
</head>
<body>
<div class="container form-container">
<form action="/wendao/regist.do" method="post">
<div class="form"> <!-- 注冊(cè)表單開始 -->
<div class="form-row">
<span class="cell-1">
<i class="fa fa-user"></i>
</span>
<span class="cell-11" style="text-align: left;">
<input type="text" name="username" placeholder="請(qǐng)輸入用戶名">
</span>
</div>
<div class="form-row">
<span class="cell-1">
<i class="fa fa-key"></i>
</span>
<span class="cell-11" style="text-align: left;">
<input type="password" name="password" placeholder="請(qǐng)輸入密碼">
</span>
</div>
<div class="form-row">
<span class="cell-1">
<i class="fa fa-keyboard-o"></i>
</span>
<span class="cell-11" style="text-align: left;">
<input type="password" name="confirm" placeholder="請(qǐng)確認(rèn)密碼">
</span>
</div>
<div class="form-row">
<span class="cell-7">
<input type="text" name="verifyCode" placeholder="請(qǐng)輸入驗(yàn)證碼">
</span>
<span class="cell-5" style="text-align: center;">
<img src="/static/imghw/default1.png" data-src="/demo/verify/regist.do" class="lazy" οnclick="myRefersh(this)" alt="Use java to implement a verification code function" >
</span>
</div>
<div class="form-row" style="border: none;">
<span class="cell-6" style="text-align: left">
<input type="reset" value="重置">
</span>
<span class="cell-6" style="text-align:right;">
<input type="submit" value="注冊(cè)">
</span>
</div>
</div> <!-- 注冊(cè)表單結(jié)束 -->
</form>
</div>
</body>
</html>
Rendering:

The changes in the verification code in the picture received by the console are as follows:

When you click to refresh the page, the verification The code will also change, but when we can't see the verification code clearly, just click on the verification code and it will be refreshed. In this way, partial refresh can be achieved with JavaScript.
In
, add a question mark and a string of suffix numbers. When refreshing, let the suffix numbers continue to change, then the formed verification code will also will continue to change. One method we can use is to replace the suffix number with date. Date gets the local time. The time changes at any time. This ensures that the refresh verification code can change at any time.
The code is as follows:
function myRefersh( e ) {
const source = e.src ; // 獲得原來的 src 中的內(nèi)容
//console.log( "source : " + source ) ;
var index = source.indexOf( "?" ) ; // 從 source 中尋找 ? 第一次出現(xiàn)的位置 (如果不存在則返回 -1 )
//console.log( "index : " + index ) ;
if( index > -1 ) { // 如果找到了 ? 就進(jìn)入內(nèi)部
var s = source.substring( 0 , index ) ; // 從 source 中截取 index 之前的內(nèi)容 ( index 以及 index 之后的內(nèi)容都被舍棄 )
//console.log( "s : " + s ) ;
var date = new Date(); // 創(chuàng)建一個(gè) Date 對(duì)象的 一個(gè) 實(shí)例
var time = date.getTime() ; // 從 新創(chuàng)建的 Date 對(duì)象的實(shí)例中獲得該時(shí)間對(duì)應(yīng)毫秒值
e.src = s + "?time=" + time ; // 將 加了 尾巴 的 地址 重新放入到 src 上
//console.log( e.src ) ;
} else {
var date = new Date();
e.src = source + "?time=" + date.getTime();
}
}
The above is the detailed content of Use java to implement a verification code function. 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
How to iterate over a Map in Java?
Jul 13, 2025 am 02:54 AM
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)->
Comparable vs Comparator in Java
Jul 13, 2025 am 02:31 AM
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
How to handle character encoding issues in Java?
Jul 13, 2025 am 02:46 AM
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
How does a HashMap work internally in Java?
Jul 15, 2025 am 03:10 AM
HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded
JavaScript Data Types: Primitive vs Reference
Jul 13, 2025 am 02:43 AM
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.
What is the 'static' keyword in Java?
Jul 13, 2025 am 02:51 AM
InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,
Using std::chrono in C
Jul 15, 2025 am 01:30 AM
std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)
What is a ReentrantLock in Java?
Jul 13, 2025 am 02:14 AM
ReentrantLock provides more flexible thread control in Java than synchronized. 1. It supports non-blocking acquisition locks (tryLock()), lock acquisition with timeout (tryLock(longtimeout, TimeUnitunit)) and interruptible wait locks; 2. Allows fair locks to avoid thread hunger; 3. Supports multiple condition variables to achieve a more refined wait/notification mechanism; 4. Need to manually release the lock, unlock() must be called in finally blocks to avoid resource leakage; 5. It is suitable for scenarios that require advanced synchronization control, such as custom synchronization tools or complex concurrent structures, but synchro is still recommended for simple mutual exclusion requirements.
See all articles