Home Java javaTutorial JavaWeb code details for implementing verification code function (demo)

JavaWeb code details for implementing verification code function (demo)

Mar 09, 2017 am 10:21 AM
javaweb Verification code

In WEB-APP, it is generally used in: login, registration, buying a certain ticket, flash sales and other scenarios. Everyone has been exposed to this verification code operation. Today, the editor will explain to you how to implement the verification code function in javaweb through example code. What is needed Friends, please refer to the

verification code. Needless to say, it is generally used in WEB-APP: login, registration, buying a certain ticket, flash sales and other scenarios. Everyone has come into contact with them. It can be said that they are all kinds of strange and varied.

DEMO target function

  • Verification code page input.

  • Page replacement verification code (asynchronous implementation).

  • Background verification and return verification results.

Start construction

Page: demo1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
 <title>验证示例</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
 <style type="text/css">
 img {
 width: 87px;
 height: 33px;
 border: 1px solid gray;
 }
 #msg {color: red;} /* 后台返回的验证信息显示为红色 */
 </style>
 </head>
 <body>
 <form action="${pageContext.request.contextPath}/check" method="post" enctype="application/x-www-form-urlencoded">
 验证码:<input type="text" name="code" size="4" maxlength="4" id="code" /> 
 <img id="code-img" src="" alt="验证码" style="display: none;"/> 
 <a href="javascript:void(0)" rel="external nofollow" id="changeCode">看不清?换一张</a> <br/><br/>
 <input type="submit" value="验证"/> <span id="msg">${msg}</span>
 </form>
 </body>
</html>
Copy after login

Description :

 The href attribute of "Can't see clearly? Change one" is written as javascript:void(0) to prevent the page from refreshing. The replacement function here is completed asynchronously by AJAX.

JavaScript tool: util.js (Why use native JS? Feel free~ha)

/**
 * 获取 XMLHttpRequest Object
 * @returns XMLHttpRequest Object
 */
function getXHR() {
 var xmlHttp;
 try { // Firefox, Opera 8.0+, Safari
 xmlHttp = new XMLHttpRequest();
 } catch (e) { // Internet Explorer
 try {
 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
 try {
 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 } catch (e) {
 alert("Sorry, 您的浏览器不支持 AJAX!");
 return false;
 }
 }
 }
 return xmlHttp;
}
Copy after login

JavaScript code in the page

<script type="text/javascript" src="${pageContext.request.contextPath}/js/util.js"></script>
 <script type="text/javascript">
 var xhr = getXHR(); // 获得 XMLHttpRequest 对象
 // 页面加载时加载验证码,但验证码初始为隐藏状态
 window.onload=function() {
 // 为 onreadystatechange 事件注册回调函数。由于 xhr 为全局变量,所以注册后就不用管啦
 xhr.onreadystatechange=function() {
 if(xhr.readyState==4 && xhr.status==200) {
 document.getElementById(&#39;code-img&#39;).src="data:image/png;base64,"+xhr.responseText;
 }
 }
 xhr.open("GET","${pageContext.request.contextPath}/captcha/code",true);
 xhr.send(null);
 }
 // 验证码输入框获得焦点时,验证码状态更改为显示
 document.getElementById(&#39;code&#39;).onfocus=function() {
 document.getElementById(&#39;code-img&#39;).style.display="inline";
 }
 // 异步请求,更换验证码
 document.getElementById(&#39;changeCode&#39;).onclick=function() {
 xhr.open("GET","${pageContext.request.contextPath}/captcha/code",true);
 xhr.send(null);
 }
 </script>
Copy after login

CaptchaCodeServlet.java that generates the verification code

package com.leo.web.captcha;
import java.io.IOException;
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 com.leo.util.ImageUtil;
import cn.dsna.util.images.ValidateCode;
@WebServlet("/captcha/code")
public class CaptchaCodeServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException
 { 
 // 生成验证码(构造参数分别代表:宽度,高度,字符数,干扰线条数)
 ValidateCode code = new ValidateCode(87, 33, 4, 23);
 // 将验证码保存到 session 中,用于验证
 request.getSession().setAttribute("code", code.getCode());
 // 响应返回验证码图片 base64 编码后的数据给浏览器
 response.getWriter().write(ImageUtil.encodeImg2Base64(code.getBuffImg(), "png"));
 }
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException
 {
 this.doGet(request, response);
 }
}
Copy after login

Description:

The new features of Servlet3.0 are used here - configure with annotations url-pattern (it’s quite fun to use), which means that simple projects no longer need web .xml is available, but Tomcat requires 7.0+.

Next, I used a small tool to generate the verification code: ValidateCode.jar. The tool is very simple, and you can write it yourself if you don’t like it. But because there are too few functions, I wrote another ImageUtil. I also plan to open source a verification code tool myself.

ImageUtil.java

package com.leo.util;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import sun.misc.BASE64Encoder;
public class ImageUtil {
 /**
 * 将图片二进制数据进行 base64 编码
 * @param bufImg
 * @return base64 编码后的字符串
 */
 public static String encodeImg2Base64(BufferedImage bufImg, String formatName) {
 ByteArrayOutputStream outputStream = null;
 try {
 outputStream = new ByteArrayOutputStream();
 ImageIO.write(bufImg, formatName, outputStream);
 } catch (IOException e) {
 throw new RuntimeException("Base64 编码失败!"+e.getMessage());
 }
 BASE64Encoder encoder = new BASE64Encoder();
 return encoder.encode(outputStream.toByteArray());
 }
 private ImageUtil() {} // 工具类私有化构造方法是常见的做法
}
Copy after login

Description:

Why should the image binary data be Base64 encoded? Because the <img/> tag can directly set the src attribute value to ${pageContext.request.contextPath}/captcha/code to request the corresponding Servlet to get the binary data for direct display, but the response returned in the AJAX asynchronous request is xhr.responseText . When the data is given directly to the src attribute of the img tag, using Chrome-tool to view it will only result in a bunch of garbled characters that are parsed as text in binary, so It only takes one more step.

Perhaps as a newbie, I don’t know some other convenient techniques. But if you don’t want to use asynchronous, then directly img src is the easiest choice to set as the request address. Changing the verification code is nothing more than listening for the event img src Reset to the address (do it again ask).

Detailed information: JS parses Base64 encoded images in the browser

package com.leo.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/check")
public class CheckServlet extends HttpServlet {
 private static final long serialVersionUID = -6588625852621588221L;
 @Override
 public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException
 {
 String encoding = "UTF-8";
 request.setCharacterEncoding(encoding);
 response.setContentType("text/html;charset="+encoding);
 /* 验证码验证 */
 String inputCode = request.getParameter("code");
 // 获得 session 中的正确验证码
 String realCode = (String) request.getSession().getAttribute("code");
 System.out.println("input: "+inputCode+"\nreal: "+realCode); // 用于 Debug
 if(!(inputCode!=null && realCode!=null &&
 inputCode.equalsIgnoreCase(realCode))) {
 // 若验证码不正确:回到页面并提示错误
 request.setAttribute("msg", "验证码错误!请重新输入");
 request.getRequestDispatcher("/demo1.jsp").forward(request, response);
 return;
 }
 // 验证码正确,响应一句话表示 OK
 response.getWriter().write("验证成功!");
 }
 @Override
 public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException
 {
 doGet(request, response);
 }
}
Copy after login

Note:


The doGet() method initially processes Chinese garbled characters, and the encoding is uniformly set to UTF-8 . In actual projects, coding problems are usually handed over to a Filter to achieve a once and for all effect.

Effect

Warning! warn! ! Face control, please evacuate quickly! ! !

Write at the end

The above is the entire content of the JavaWeb verification code small DEMO. It is best to submit the verification as well. If it becomes asynchronous, something will be wrong here. Friends who have not tried adding verification code function in WEB projects can start it! In actual projects, frameworks such as JQuery are used to handle AJAX, and coupled with a beautiful front-end page, it is perfect.


The above is the detailed content of JavaWeb code details for implementing verification code function (demo). 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)

What should I do if Google Chrome does not display the verification code image? Chrome browser does not display the verification code? What should I do if Google Chrome does not display the verification code image? Chrome browser does not display the verification code? Mar 13, 2024 pm 08:55 PM

What should I do if Google Chrome does not display the verification code image? Sometimes you need a verification code to log in to a web page using Google Chrome. Some users find that Google Chrome cannot display the content of the image properly when using image verification codes. What should be done? The editor below will introduce how to deal with the Google Chrome verification code not being displayed. I hope it will be helpful to everyone! Method introduction: 1. Enter the software, click the "More" button in the upper right corner, and select "Settings" in the option list below to enter. 2. After entering the new interface, click the "Privacy Settings and Security" option on the left. 3. Then click "Website Settings" on the right

How to Analyze Code Auditing in Java Web Security How to Analyze Code Auditing in Java Web Security May 16, 2023 am 08:04 AM

1. JavaWeb Security Basics 1. What is code auditing? In layman’s terms, Java code auditing is to discover security issues in the Java application itself by auditing Java code. Since Java itself is a compiled language, even if there are only class files We can still audit Java code. For uncompiled Java source code files, we can read the source code directly, but for compiled class or jar files, we need to decompile them. Java code auditing itself is not very difficult. As long as you are proficient in the auditing process and common vulnerability auditing techniques, you can complete the code auditing work relatively easily. But the way of Java code auditing is not just to use

Why can't I receive the verification code on my phone? Why can't I receive the verification code on my phone? Aug 17, 2023 pm 02:49 PM

Failure to receive the verification code on your mobile phone is caused by network problems, mobile phone settings problems, mobile phone operator problems and personal settings problems. Detailed introduction: 1. Network problems. The network environment where the mobile phone is located is unstable or the signal is weak, which may cause the verification code to be unable to be delivered in time; 2. Mobile phone setting problems. The text message or voice function of the mobile phone is accidentally turned off, or the The verification code sending number is added to the blacklist, resulting in the verification code not being received normally; 3. Mobile phone operator issues, the mobile phone operator may have malfunctions or maintenance, resulting in the verification code not being delivered in time, etc.

Can virtual numbers receive verification codes? Can virtual numbers receive verification codes? Jan 02, 2024 am 10:22 AM

The virtual number can receive the verification code. As long as the mobile phone number filled in during registration complies with the regulations and the mobile phone number can be connected normally, you can receive the SMS verification code. However, you need to be careful when using virtual mobile phone numbers. Some websites do not support virtual mobile phone number registration, so you need to choose a regular virtual mobile phone number service provider.

PHP image processing case: How to implement the verification code function of images PHP image processing case: How to implement the verification code function of images Aug 17, 2023 pm 12:09 PM

PHP image processing case: How to implement the verification code function of images. With the rapid development of the Internet, verification codes have become one of the important means to protect website security. Verification code is a verification method that uses image recognition technology to determine whether the user is a real user. This article will introduce how to use PHP to implement the verification code function of images, and come with code examples. Introduction A verification code is a picture containing random characters. The user needs to enter the characters in the picture to pass the verification. The main process of implementing verification code includes generating random characters and drawing characters into pictures.

PHP Development Guide: Implementing Verification Code Login PHP Development Guide: Implementing Verification Code Login Jul 01, 2023 am 09:27 AM

With the development of the Internet and the popularity of smartphones, the verification code login function is adopted by more and more websites and applications. Verification code login is a login method that verifies the user's identity by entering the correct verification code to improve security and prevent malicious attacks. In PHP development, implementing a simple verification code login function is not complicated and can be completed through the following steps. Create a database table First, we need to create a table in the database to store verification code information. The table structure can contain the following fields: id: auto-incrementing primary key phon

Verification codes can't stop robots! Google AI can accurately identify blurry text, while GPT-4 pretends to be blind and asks for help Verification codes can't stop robots! Google AI can accurately identify blurry text, while GPT-4 pretends to be blind and asks for help Apr 12, 2023 am 09:46 AM

“The most annoying thing is all kinds of weird (or even perverted) verification codes when you log into a website.” Now, there is good news and bad news. The good news is: AI can do this for you. If you don’t believe me, here are three real cases of increasing recognition difficulty: And these are the answers given by a model called “Pix2Struct”: Are they all accurate and word for word? Some netizens lamented: Sure, the accuracy is better than mine. So can it be made into a browser plug-in? ? Yes, some people said: Even though these cases are relatively simple, if you just fine-tune it, I can't imagine how powerful the effect will be. So, the bad news is - the verification code will soon be unable to stop the robots! (Danger danger danger...) How to do it? Pix2St

How to create a verification code image using PHP? How to create a verification code image using PHP? Sep 13, 2023 am 11:40 AM

How to create a verification code image using PHP? CAPTCHA is a commonly used method to verify whether the user is a human and not a machine. On websites, we often see verification code images, which require users to enter random characters or numbers displayed on the image to complete operations such as login, registration, and commenting. This article will introduce how to use PHP to create a verification code image and provide specific code examples. 1. PHPGD library To create a verification code image, we need to use PHP's GD library. The GD library is an extension for processing images.

See all articles