Home Web Front-end JS Tutorial Ajax+Struts2 implements verification code verification function (graphic tutorial)

Ajax+Struts2 implements verification code verification function (graphic tutorial)

May 23, 2018 pm 04:20 PM
Function accomplish

This article mainly introduces the relevant information about the example code of Ajax Struts2 to implement the verification code verification function. It is very good and has reference value. Friends in need can refer to it

As we all know, verification code plays an important role in our lives. It is very common in China. Many companies are tossing around with various verification codes. Here is a brief case to implement the function of verification codes (ps: I actually hate verification codes).

What I’m sharing today is to use ajax to dynamically verify whether the verification code input is correct. What we use here is ajax struts2 for this verification. Let's create a new web project. Then you need to import the corresponding package of struts. Then we need to write a class to generate the verification code.

The name here is 01_image.jsp. The main function of this type is to generate a verification code, which contains various drawing lines, random numbers, etc. I set up a 5-digit verification here. If you want to change It can be changed into other formats. The general idea is to add letters to the loop that generates numbers.

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
public Color getColor(){
Random random = new Random();
int r = random.nextInt(256);//0-255
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r,g,b);
}
public String getNum(){
String str = "";
Random random = new Random();
for(int i=0;i<5;i++){
str += random.nextInt(10);//0-9
}
return str;
}
%>
<%
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", 0);
BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(new Color(200,200,200));
g.fillRect(0,0,80,30);
for (int i = 0; i < 50; i++) {
Random random = new Random();
int x = random.nextInt(80);
int y = random.nextInt(30);
int xl = random.nextInt(x+10);
int yl = random.nextInt(y+10);
g.setColor(getColor());
g.drawLine(x, y, x + xl, y + yl);
}
g.setFont(new Font("serif", Font.BOLD,16));
g.setColor(Color.BLACK);
String checkNum = getNum();//"2525"
StringBuffer sb = new StringBuffer();
for(int i=0;i<checkNum.length();i++){
sb.append(checkNum.charAt(i)+" ");//"2 5 2 5"
}
g.drawString(sb.toString(),15,20);
session.setAttribute("CHECKNUM",checkNum);//2525
//通过字节输出流输出
ImageIO.write(image,"jpeg",response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
Copy after login

Next, write the html page for entering the verification code. I have it in a jsp file. Name it checkcode.jsp

<th>验证码:</th>
<td><input type="text" name="checkcode" id="checkcodeID" maxlength="5" /></td>
<td><img src="01_image.jsp" id="imgID" /></td>
<td id="resID"></td>
</tr> 
</table>
</form>
Copy after login

and then add javascript code to this file. Of course, an ajax is used here. The coding steps for ajax have been written in detail before, so we will use it directly here. After writing ajax.js, place it under the js directory, and then find a checkcode.jsp to introduce the content of the Chinese js file ajax.js:

//创建AJAX异步对象,即XMLHttpRequest
function createAJAX(){
var ajax = null;
try{
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch(e1){
try{
ajax = new XMLHttpRequest();
}catch(e2){
alert("你的浏览器不支持ajax,请更换浏览器");
}
}
return ajax;
}
Copy after login

Then there is the js content in chenkcode

//去掉两边的空格
function trim(str){
str=str.replace(/^\s*/,"");//从左侧开始,把空格去掉
str=str.replace(/\s*$/,""); //从右侧开始,把K歌都去掉
return str;
}
document.getElementById("checkcodeID").onkeyup=function(){
var checkcode=this.value;
checkcode=trim(checkcode);
if(checkcode.length==5){
var ajax=createAJAX();
var method="POST";
var url = "${pageContext.request.contextPath}/checkRequest?time="+new Date().getTime();
ajax.open(method,url);
//设置ajax请求头为post,它会将请求的汉字自动进行utf-8的编码
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
var content="checkcode="+checkcode;
ajax.send(content);
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
var tip=ajax.responseText;
var img=document.createElement("img");
img.src=tip;
img.style.width="14px";
img.style.height="14px";
var td=document.getElementById("resID");
td.innerHTML="";
td.appendChild(img);
}
} 
} 
}else{
var td=document.getElementById("resID");
td.innerHTML="";
}
}
Copy after login

Then start writing the server-side code. For verification, you need such a class:

package cn.tf.checkcode;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
//验证码检查
public class CheckcodeAction extends ActionSupport{
private String checkcode;
public void setCheckcode(String checkcode) {
this.checkcode = checkcode;
}
/**
* 验证
* @throws IOException 
*/
public String check() throws IOException {
//图片路径
String tip="images/a.jpg";
//从服务器获取session中的验证码
String checkcodeServer=(String) ActionContext.getContext().getSession().get("CHECKNUM");
if(checkcode.equals(checkcodeServer)){
tip="images/b.jpg";
}
//以IO流的方式将tip变量输出到ajax异步对象中
HttpServletResponse response=ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw=response.getWriter();
pw.write(tip);
pw.flush();
pw.close();
return null;
}
}
Copy after login

Finally, write the corresponding method in the struts.xml file.

<struts>
<package name="myPackage" extends="struts-default" namespace="/"> 
<action 
name="checkRequest" 
class="cn.tf.checkcode.CheckcodeAction" 
method="check">
</action>
</package>
</struts>
Copy after login

The running results are as follows: if the verification is successful, a green tick will be returned, and if it is an error, a red cross will be returned.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Ajax clicks to continuously load the data list (graphic tutorial)

A brief discussion on ajax request technology

Very practical ajax user registration module

The above is the detailed content of Ajax+Struts2 implements verification code verification function (graphic tutorial). 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 Article Tags

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)

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

The difference between vivox100s and x100: performance comparison and function analysis

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones?

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

What exactly is self-media? What are its main features and functions?

PHP Tips: Quickly Implement Return to Previous Page Function PHP Tips: Quickly Implement Return to Previous Page Function Mar 09, 2024 am 08:21 AM

PHP Tips: Quickly Implement Return to Previous Page Function

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account?

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

PHP Programming Guide: Methods to Implement Fibonacci Sequence

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

Master how Golang enables game development possibilities

See all articles