Home > Java > javaTutorial > body text

JavaWeb code details for implementing verification code function (demo)

黄舟
Release: 2017-03-09 10:21:36
Original
2153 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template