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

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

亚连
亚连Original
2018-05-23 16:20:561749browse

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();
%>

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>

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;
}

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="";
}
}

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;
}
}

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>

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:
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