使用Ajax实现对验证码验证提示(struts+jsp+Ajax)

前端之家收集整理的这篇文章主要介绍了使用Ajax实现对验证码验证提示(struts+jsp+Ajax)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

image.jsp:验证码图片生成

<%@ 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<4;i++){
			str += random.nextInt(10);//0-9
		}
		return str;
	}
%>
<%
	response.setHeader("pragma","mo-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,80,30);
	
	
	for (int i = 0; i < 30; 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();
%>

checkcode.jsp验证码输入页面(Ajax验证提示

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>验证码检查</title>
<script type="text/javascript" src="js/ajax.js"></script>
</head>
<body>

	<form>
		<table border="0" align="center">
			<tr>
				<th>验证码:</th>
				<td><input size="2" type="text" name="checkcode"
					id="checkcodeID" maxlength="4" />
				</td>
				<td><img src="01_image.jsp" />
				<td id="res"></td>//用来添加图片提示输入的验证码是否正确
			</tr>
		</table>
	</form>

	<script type="text/javascript">
		//去掉二边的空格
		function trim(str) {
			"  zhaojun  "
			str = str.replace(/^\s*/,"");//"zhaojun  " 	
			str = str.replace(/\s*$/,"");//"zhaojun"
			return str;
		}
	</script>

	<script type="text/javascript">
		document.getElementById("checkcodeID").onkeyup = function() {
			var checkcode = this.value;
			checkcode = trim(checkcode);//2525
			if (checkcode.length == 4) {
				//NO1)
				var ajax = createAJAX();
				//NO2)
				var method = "POST";
				var url = "${pageContext.request.contextPath}/checkRequest?time="
						+ new Date().getTime();
				ajax.open(method,url);
				//NO3)
				ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
				//NO4)
				var content = "checkcode=" + checkcode;
				ajax.send(content);

				//--------------------------------------------------------等待

				//NO5)
				ajax.onreadystatechange = function() {
					if (ajax.readyState == 4) {
						if (ajax.status == 200) {
							//NO6)
							var tip = ajax.responseText;

							//NO7)
							var img = document.createElement("img");
							img.src = tip;
							img.style.width = "14px";
							img.style.height = "14px";
							var td = document.getElementById("res");
							td.innerHTML = "";
							td.appendChild(img);
						}
					}
				}
			} else {
				//清空图片
				var td = document.getElementById("res");
				td.innerHTML = "";
			}
			function createAJAX() {
				var ajax = null;
				try {
					ajax = new ActiveXObject("microsoft.xmlhttp");
				} catch (e1) {
					try {
						ajax = new XMLHttpRequest();
					} catch (e2) {
						alert("你的浏览器不支持ajax,请更换浏览器");
					}
				}
				return ajax;
			}
		}
	</script>

</body>
</html>

checkcodeAction.java:action处理

public class CheckcodeAction extends ActionSupport {
	//客户端验证码
		private String checkcode;//2525
		//注入客户端验证码
		public void setCheckcode(String checkcode) {
			this.checkcode = checkcode;
		}
		/**
		 * 验证
		 */	
		public String check() throws Exception {
			//图片路径
			String tip = "images/MsgError.gif";
			//从服务器获取session中的验证码
			String checkcodeServer = (String) ActionContext.getContext().getSession().get("CHECKNUM");
			//将客户端的验证码与服务端的验证码进行比较
			if(checkcode.equals(checkcodeServer)){
				tip = "images/MsgSent.gif";
			}
			//以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();
			//以下方式不是最好的,但可以完成AJAX异步交互
			return null;
		}
}

web.xml对struts核心过滤器的配置

<filter>
		<filter-name>StrutsPrepareAndExecuteFilter</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>StrutsPrepareAndExecuteFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

struts.xml配置 action

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<package name="myPackage" extends="json-default" namespace="/">
		<action name="checkRequest" class="action.CheckcodeAction"
			method="check">
		</action>
	</package>
</struts>
原文链接:https://www.f2er.com/ajax/160508.html

猜你在找的Ajax相关文章