jsp页面验证码源代码

合集下载

Jsp网站登录数字+字母验证码实现

Jsp网站登录数字+字母验证码实现

Jsp⽹站登录数字+字母验证码实现image.jsp创建验证码图⽚、CreateImage.jsp输⼊验证码界⾯把值传给验证的页⾯checkImage.jsp.我只修改了下if (rand.equalsIgnoreCase(input)) 不然验证的时候区分⼤⼩写.总的来说还⾏很实⽤!验证码图⽚的⽂件image.jsp<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" pageEncoding="UTF-8" %><%!Color getRandColor(int fc, int bc) {//给定范围获得随机颜⾊Random random = new Random();if (fc > 255)fc = 255;if (bc > 255)bc = 255;int r = fc + random.nextInt(bc - fc);int g = fc + random.nextInt(bc - fc);int b = fc + random.nextInt(bc - fc);return new Color(r, g, b);}%><%//设置页⾯不缓存response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);// 在内存中创建图象int width = 80, height = 20;BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);// 获取图形上下⽂Graphics g = image.getGraphics();//⽣成随机类Random random = new Random();// 设定背景⾊g.setColor(getRandColor(200, 250));g.fillRect(0, 0, width, height);//设定字体g.setFont(new Font("Times New Roman", Font.BOLD, 18));//画边框g.setColor(new Color(0, 0, 0));g.drawRect(0, 0, width - 1, height - 1);// 随机产⽣155条⼲扰线,使图象中的认证码不易被其它程序探测到g.setColor(getRandColor(160, 200));for (int i = 0; i < 155; i++) {int x = random.nextInt(width);int y = random.nextInt(height);int xl = random.nextInt(12);int yl = random.nextInt(12);g.drawLine(x, y, x + xl, y + yl);}// 取随机产⽣的认证码(4位数字)String sRand = "";for (int i = 0; i < 4; i++) {String rand = null;//随机⽣成数字或者字母if (random.nextInt(10) > 5) {rand = String.valueOf((char)(random.nextInt(10) + 48));} else {rand = String.valueOf((char)(random.nextInt(26) + 65));}sRand += rand;// 将认证码显⽰到图象中g.setColor(new Color(random.nextInt(80), random.nextInt(80), random.nextInt(80)));//调⽤函数出来的颜⾊相同,可能是因为种⼦太接近,所以只能直接⽣成g.drawString(rand, 15 * i + 10, 16);}// 将认证码存⼊SESSIONsession.setAttribute("rand", sRand);// 图象⽣效g.dispose();// 输出图象到页⾯ImageIO.write(image, "JPEG", response.getOutputStream());%>使⽤验证码图⽚的⽂件CreateImage.jsp<%@ page contentType="text/html;charset=gb2312" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>认证码输⼊页⾯</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="0"></head><body><form method=post action="checkImage.jsp"><table><tr><td align=left>系统产⽣的认证码:</td><td><img id="code" border=0 src="image.jsp"><a href="#" onClick="javascript:var dt=new Date();document.getElementById('code').src='image.jsp?dt='+dt;">看不清验证码请单击这⾥</a></td> <!--这⾥的image.jsp?dt='+dt;很重要,如果只是改为image.jsp则不会有图⽚改变的效果,因为浏览器认为SRC没有改变,所以⼀定要⽣成⼀个随时在改变的dt来实现这⼀功能--></tr><tr><td align=left>输⼊上⾯的认证码:</td><td><input type=text name=rand maxlength=4 value=""></td></tr><tr><td colspan=2 align=center><input type=submit value="提交检测"></td></tr></table></form></body></html>验证的页⾯checkImage.jsp<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %><html><head><title>认证码验证页⾯</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="0"></head><body><%String rand = (String)session.getAttribute("rand");String input = request.getParameter("rand");%>系统产⽣的认证码为: <%= rand %><br>您输⼊的认证码为: <%= input %><br><br><%if (rand.equalsIgnoreCase(input)) {%><font color=green>输⼊相同,认证成功!</font><%} else {%><font color=red>输⼊不同,认证失败!</font><%}%></body></html>。

js实现简单的验证码

js实现简单的验证码

js实现简单的验证码验证码⼤家应该不陌⽣,主要是为了⽹站的安全性,防⽌恶意注册和登陆。

验证码实现的⽅式各有不同,下⾯是⼀段⽤javascript实现的验证码效果,供⼤家参考之⽤,希望能够给⼤家带来帮助。

运⾏效果图:代码如下:<html><head><title>js验证码</title><style type="text/css">.code{background:url(code_bg.jpg);font-family:Arial;font-style:italic;color:blue;font-size:30px;border:0;padding:2px 3px;letter-spacing:3px;font-weight:bolder;float:left;cursor:pointer;width:150px;height:60px;line-height:60px;text-align:center;vertical-align:middle;}a{text-decoration:none;font-size:12px;color:#288bc4;}a:hover{text-decoration:underline;}</style><script type="text/javascript">var code;function createCode(){code = "";var codeLength = 6; //验证码的长度var checkCode = document.getElementById("checkCode");var codeChars = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); //所有候选组成验证码的字符,当然也可以⽤中⽂的 for(var i = 0; i < codeLength; i++){var charNum = Math.floor(Math.random() * 52);code += codeChars[charNum];}if(checkCode){checkCode.className = "code";checkCode.innerHTML = code;}}function validateCode(){var inputCode=document.getElementById("inputCode").value;if(inputCode.length <= 0){alert("请输⼊验证码!");}else if(inputCode.toUpperCase() != code.toUpperCase()){alert("验证码输⼊有误!");createCode();}else{alert("验证码正确!");}}</script></head><body onload="createCode()"><form id="form1" runat="server" onsubmit="validateCode()"><div><table border="0" cellspacing="5" cellpadding="5" ><tr><td></td><td><div class="code" id="checkCode" onclick="createCode()" ></div></td><td><a href="#" onclick="createCode()">看不清换⼀张</a></td></tr><tr><td>验证码:</td><td><input style="float:left;" type="text" id="inputCode" /></td><td>请输⼊验证码</td></tr><tr><td></td><td><input id="Button1" onclick="validateCode();" type="button" value="确定" /></td><td></td></tr></table></div></form></body></html>希望本⽂所述对⼤家学习javascript程序设计有所帮助。

(完整版)JSP登陆页面代码

(完整版)JSP登陆页面代码
response.sendRedirect("login.htm");
}
%>
如果输入信息有误,则回到登录页面,重新输入登录信息。
注册页面:reg.jsp
请输入您的注册信息:
<table>
<form action="/user/Reg" method="post" name="regform" onsubmit="return regconfirm();">
session.setAttribute("login","ok");
session.setMaxInactiveInterval(-1);
%>
<jsp:forward page="main.jsp"/>
<%
}else{
out.println("用户名或密码输入错误!");
}
%>
如果登录成功,则设定login的值为ok,提交到下一步验证页面,则进入main.jsp页面,否则,如果输入的用户名和密码不合法就打印错误信息,main.jsp页面代码如下:
<tr><td>密码:</td><td><input type="password" name="user_pwd" id="user_pwd" size="20" maxlength=10 onBlur="checkPWD();">*可以包含字母数字(区分大小写),6-10位</td>

验证码邮箱检验jsp代码

验证码邮箱检验jsp代码
var email = $("#tbCommentEmail").val();
var authenNum = $("#tbAuthenCode").val();
var authenId = $("#span_comment_test").html();
$("#lnkRereshAuthenCode").html("<span style='color:red'>刷新中...</span>");
return false;
}
function RefreshImg(response){
$("#imgAuthenCode").attr("src","/Modules/CaptchaImage/ValidCodeImage.aspx?id="+encodeURIComponent(response));
ShowCommentMsg(data.d["ReturnData"]);//"抱歉!评论提交失败!请与管理员联系。");
$("#span_comment_posted").html('');
}
// AjaxPost("/ws/CommentService.asmx/RefreshAuthenCode","{}",ShowAuthenCodeOk);
//}
$("#wrapAuthenCode").show();
}
var comment = {};

验证码代码

验证码代码

验证码Servlet源代码:package sjzpc.webmessage.control;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class ImageCode extends HttpServlet {private static final long serialVersionUID= 8165458985542870320L;//设置图形验证码中的字符串的字体的大小private Font mFont= new Font("Arial Black", Font.PLAIN, 16);public void init() throws ServletException {super.init();}/***生成随机颜色*@param fc*@param bc*@return*/Color getRandColor(int fc, int bc) {Random random = new Random();if (fc > 255)fc = 255;if (bc > 255)bc = 255;int r = fc + random.nextInt(bc - fc);int g = fc + random.nextInt(bc - fc);int b = fc + random.nextInt(bc - fc);return new Color(r, g, b);}public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//生成服务器相应的service方法//阻止生成的页面内容被缓存,保证每次重新生成随机验证码 response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);response.setContentType("image/jpeg");//指定图形验证码图片的大小;int width = 80;//宽度int height = 20;//高度BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);// 准备在图片中绘制内容Graphics g = image.getGraphics();Random random = new Random();g.setColor(getRandColor(200, 250));g.fillRect(1, 1, width - 1, height - 1);g.setColor(new Color(102, 102, 102));g.drawRect(0, 0, width - 1, height - 1);g.setFont(mFont);g.setColor(getRandColor(160, 200));//生成随机线条for (int i = 0; i < 155; i++) {int x = random.nextInt(width - 1);int y = random.nextInt(height - 1);int xl = random.nextInt(6) + 1;int yl = random.nextInt(12) + 1;g.drawLine(x, y, x + xl, y + yl);}for (int i = 0; i < 70; i++) {int x = random.nextInt(width - 1);int y = random.nextInt(height - 1);int xl = random.nextInt(12) + 1;int yl = random.nextInt(6) + 1;g.drawLine(x, y, x - xl, y - yl);}String sRand = "";//生成随机的字符串并加入到图片中int LEN = 4; //控制随机码的长度for (int i = 0; i < LEN; i++) {String tmp = getRandomChar();sRand += tmp;g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));g.drawString(tmp, 15 * i + 10, 15);}HttpSession session = request.getSession(true);// log.debug("随机生成的字符串为"+sRand);//将其自动转换为小写。

jsp页面验证码

jsp页面验证码

AJAX+jsp无刷新验证码实例(完整代码)1.login.jsp<%@ pagelanguage="java"contentType="text/html;charset=gb2312"import = "java.util.*"import = "java.sql.*"import = "java.text.*"import = "java.io.*"%><%@ include file="../conn.jsp"%><%request.setCharacterEncoding("gb2312");%><%String username=request.getParameter("name");String pass=request.getParameter("pws");String num=request.getParameter("num");String random=(String)session.getAttribute("random");if(num!=null&&random!=null){if(num.equals(random)){Statement stmt=conn.createStatement();ResultSet rs=stmt.executeQuery("select * from admin where admin='"+username+"' and pass='"+pass+"'");if(rs.next()){String id=rs.getString("id");session.setAttribute("id",id);response.sendRedirect("admin.jsp");}rs.close();stmt.close();conn.close();}}%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>两岸咖啡</title><link href="../include/style.css" rel="stylesheet" type="text/css" /><script src="net.js"></script><script type="text/javascript">var times=0;function subform(){var gtext=this.req.responseText;var info=document.getElementById("info");if(gtext.indexOf("validate_successful")!=-1){//info.innerHTML="<font color=green>验证码通过</font>";document.forms["form"].submit();//当得到的值表示合法,则验证码通过。

jsp登陆源代码

jsp登陆源代码

denglu.jsp<%@ page contentType="text/html; charset=GB2312" language="java" import="java.util.*,java.text.*"%><html><head><title>登陆界面</title></head><body bgcolor="#7e98f6"><center><%@include file="util/main.jsp"%>(页面头部)<form action="dlxx.jsp" method=post name=form><img src="image/3.jpg">(图片自己放一张并改名字和地址(image))<table bgcolor="#7e98f6" height="150"><tr><td>用户名:<input type="text" name="yonghu" value=""/><tr><td>密码:<input type="text" name="pass" value=""/><tr><td><input type="submit" name="submit" value="提交"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" name="submit" value="重置"/></table></form><jsp:include page="util/foot.jsp" flush="true"/>(页面尾部)</body></html>dlxx.jsp<%@ page contentType="text/html; charset=GB2312" language="java" import="java.util.*,java.text.*"%><%@page import="java.sql.*"%><html><body><%@include file="util/main.jsp"%><body bgcolor="#7e98f6"><br/><br/><br/><br/><br/><br/><br/><font size="华文楷体"><center><%String yonghu1=request.getParameter("yonghu");String pass1=request.getParameter("pass");String dpass="";try{Class.forName ("com.microsoft.sqlserver.jdbc.SQLServerDriver");String url="jdbc:sqlserver://localhost:1433;DataBaseName=liu";(数据库名)String dlname="sa";String dlpass="123";Connection conn=DriverManager.getConnection(url,dlname,dlpass);Statement ss=conn.createStatement();String cx="select yh_pass from yh where yh_name='"+yonghu1+"'";(yh_pass/yh_name数据库列表名,yh表名)ResultSet rs=ss.executeQuery(cx);if(rs.next()){dpass=rs.getString("yh_pass");}rs.close();ss.close();conn.close();}catch(Exception e){out.println(e.toString());}if(dpass.equals(pass1)){response.sendRedirect("weclome.jsp");(欢迎页面)}else{out.print(yonghu1+"不是数据库中用户,登录失败!!");out.print("<br><br>用户名="+yonghu1);out.print("<br><br>密码="+dpass);out.print("<br><br>密码="+pass1);}%><br/><br/><br/><br/><br/><jsp:include page="util/foot.jsp" flush="true"/></body></html>。

jsp页面验证码源代码

jsp页面验证码源代码

jsp页面验证码源代码在java后台中生成验证码的ImageIO传到前端页面显示,同时把验证码的v alue值传入session 中用于与用户输入的验证码进行匹配,在用户验证中使用ajax技术,在不刷新页面的同时进行验证码验证。

程序结构图:VerifyCodeUtils程序主要内容为通过Java生成验证码的图片,以及验证码的value值,程序如下:package utils;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.util.HashMap;import java.util.Map;import java.util.Random;publicclass VerifyCodeUtils {privatestatic BufferedImage image = null;privatestatic Random random = new Random();//在自己定义的一些数中,生成4位随机数publicstatic String getVerifyCode() {String str = "";char[] code = newchar[]{'A','B','C','D','E','F','G','H','I ','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i',' j','k','m','n','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7','8','9'};Random random = new Random();for(int i = 0; i <4; i++) {str += String.valueOf(code[random.nextInt(code.length)]);}return str;}//生成验证码图像publicstatic Map getVerifyCode(int width, int heigth) {VerifyCodeUtils.image = new BufferedImage(width, heigth, Bu fferedImage.TYPE_INT_RGB);Graphics2D g = (Graphics2D) VerifyCodeUtils.image.g etGraphics();String verifyCode = getVerifyCode();Map map = new HashMap();map.put("verifyCode", verifyCode);//将图像填充为白色g.setColor(Color.WHITE);g.fillRect(0, 0, width, heigth);//设置字体g.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, heigth-10));//画边框。

JSP验证码大全之中文验证码(源码)

JSP验证码大全之中文验证码(源码)

在上一篇内容中介绍了有关JSP中产生数字验证码图片的过程,本文将继续介绍有关JSP中的另一种验证码的实现,即中文验证码在JSP中的实现,使用中文验证码的好处是能提高验证的有效性,提高验证的安全度,因为中文相对于英文或数字笔画结构相对比较复杂,从而增加了分析程序解析验证码图片并读取验证信息的难度。

在文中并分析中文验证的实现过程。

二、JSP中实现中文验证码源码如下:ChineseVal.jsp<%@page pageEncoding="gb2312" contentType="image/jpeg" import="java x.imageio.*,java.util.*,java.awt.image.*,java.awt.*"%><%!//在此处获取并生成随机颜色Color getRandColor(Random random, int ff, int cc) {if(ff > 255)ff = 255;if(cc > 255)cc = 255;int r = ff + random.nextInt(cc - ff);int g = ff + random.nextInt(cc - ff);int b = ff + random.nextInt(cc - ff);return new Color(r, g, b);}%><%//在此处设置JSP页面无缓存response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);// 设置图片的长宽int width = 130;int height = 30;//设定被随机选取的中文字,此处中文字内容过多,不一一列出,只是举例说明下。

jsp实现简单图片验证码功能

jsp实现简单图片验证码功能

jsp实现简单图⽚验证码功能本⽂实例为⼤家分享了jsp实现简单图⽚验证码的具体代码,供⼤家参考,具体内容如下⼀、实现的功能分析(1)在登陆页⾯加验证码的功能,起到⼀定的安全性。

在输⼊正确的验证码,⽤户名和密码的情况下,才可以实现登录。

(2)实现查询数据库的功能。

在登陆后的页⾯中,显⽰⽤户名和密码,并且设置有⼀个超链接,实现查询数据库的功能。

(3)代码核⼼是:随机⽣成验证码,并且显⽰在页⾯上。

同时要和输⼊框中的输⼊验证码进⾏校验。

(4)主页⾯使⽤img标签的src属性引⼊验证页⾯的jsp⽂件。

(5)验证码的实现页⾯使⽤BufferedImage类的⽅法产⽣图⽚。

(6)使⽤Graphics类的各种⽅法实现验证码的构成。

⼆、代码实现(1)登录页⾯:index.jsp⽂件。

<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html><html><head><meta charset="utf-8"><title>登录页⾯</title></head><body><form action="LoginServlet" method="post">⽤户名:<input name="username" type="text" value=""/><br/><br/>密码:<input name="password" type="password" value=""/><br/><br/>验证码: <input type="text" name="checkCode" height="20px " value=""/><img src="CodeServlet"/><span>${error_code}</span><br/><input type="submit" value="提交"></form></body></html>(2)登录后的页⾯:user.jsp⽂件。

jsp验证码_源代码

jsp验证码_源代码

jsp验证码实现源代码演示程序包括三个文件:1.login.jsp:登录页面2.code.jsp:生成验证码图片页面3.check.jsp:验证结果code.jsp<%@ page contentType="image/jpeg" import="java.awt.*, java.awt.image.*,java.util.*,javax.imageio.*" %><%// 在内存中创建图象int width=60, height=20;BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 获取图形上下文Graphics g = image.getGraphics();// 设定背景色g.setColor(new Color(0xDCDCDC));g.fillRect(0, 0, width, height);//画边框g.setColor(Color.black);g.drawRect(0,0,width-1,height-1);// 随机产生的认证码(4位数字)String rand =""+ (Math.random()*10000);rand = rand.substring(0,rand.indexOf("."));switch(rand.length()){case 1: rand = "000"+rand; break;case 2: rand = "00"+rand; break;case 3: rand = "0"+rand; break;default: rand = rand.substring(0,4); break;}// 将认证码存入SESSIONsession.setAttribute("rand",rand);// 将认证码显示到图象中g.setColor(Color.black);Integer tempNumber = new Integer(rand);String numberStr = tempNumber.toString();g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));String Str = numberStr.substring(0,1);g.drawString(Str,8,17);Str = numberStr.substring(1,2);g.drawString(Str,20,15);Str = numberStr.substring(2,3);g.drawString(Str,35,18);Str = numberStr.substring(3,4);g.drawString(Str,45,15);// 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到Random random = new Random();for (int i=0;i<20;i++){int x = random.nextInt(width);int y = random.nextInt(height);g.drawOval(x,y,0,0);}// 图象生效g.dispose();// 输出图象到页面ImageIO.write(image, "JPEG", response.getOutputStream());//在页面上调用 <img src="/yourPath/checkNum.jsp" />%>login.jsp<%@ page contentType="text/html;charset=gb2312" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>认证码输入页面</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="0"></head><body><form method=post action="check.jsp"><table><tr><td align=left>系统产生的认证码:</td><td><img border=0 src="code.jsp"></td></tr><tr><td align=left>输入上面的认证码:</td><td><input type=text name=rand maxlength=4 value=""></td></tr><tr><td colspan=2 align=center><input type=submit value="提交检测"></td> </tr></form></body></html>check.jsp<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %><html><head><title>认证码验证页面</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="0"></head><body><%String rand = (String)session.getAttribute("rand");String input = request.getParameter("rand");%>系统产生的认证码为: <%= rand %><br>您输入的认证码为: <%= input %><br><br><%if (rand.equals(input)) {%><font color=green>输入相同,认证成功!</font><%} else {%><font color=red>输入不同,认证失败!</font> <%}%></body></html。

(完整版)Jsp学生信息管理系统登录验证全代码

(完整版)Jsp学生信息管理系统登录验证全代码
</font></td>
<td align=centerSTYLE='cursor:
hand'><font size=2>
<div class="b2bbutton"id="bt4"
imer);theTimer=setTimeout('turnPage()',speed);check Bt();"> 5</div>
</script></TD>
</TR>
</table> <hr color="green"width="540">
<table align="center">
<tr>
<td>用户名: <input type="text"name="username"size="8"maxlength="6"></td>
}
public String getUsername(){
return username;
}
public void setUsername(String username){this .username=username;
}
public String getPassword(){
return password
</font></td>
<td align=centerSTYLE='cursor:

JSP验证码动态生成方法

JSP验证码动态生成方法

JSP验证码动态⽣成⽅法在登录应⽤中,为防⽌恶意登录,常常需要服务器动态⽣成验证码并存储在session作⽤范围中,最后以图像形式返回给客户端显⽰下边的代码实现的功能:写⼀个JSP页,动态⽣成⼀个验证码,存储在session作⽤范围内,并以图像形式返回给客户端显⽰。

另写⼀个JSP页⾯,引⽤此JSP页⾯⽣成的验证码;authen.jsp代码如下:<%@ page import="java.awt.*,java.awt.image.*,java.util.*,com.sun.image.codec.jpeg.*" %><%!//根据提供的ab产⽣随机的颜⾊变化范围Color getColor(int a,int b){int n=b-a;Random rd=new Random();int cr=a+rd.nextInt(n);int cg=a+rd.nextInt(n);int cb=a+rd.nextInt(n);return new Color(cr,cg,cb);}%><% //下边三⾏取消客户端游览器缓存验证码的功能response.setHeader("Pragma","No-cache");response.setHeader("Cache-Control","no-cache");response.setDateHeader("Expires", 0);int width=60, height=20;//在内存中⽣成⼀个图像BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = image.getGraphics();Random random = new Random();g.setColor(getColor(200,250));g.fillRect(0, 0, width, height);g.setFont(new Font("Times New Roman",Font.BOLD,18));g.setColor(getColor(160,200));for (int i=0;i<160;i++){int x = random.nextInt(width);int y = random.nextInt(height);int xl = random.nextInt(12);int yl = random.nextInt(12);g.drawLine(x,y,x+xl,y+yl);}String number=String.valueOf(1000+random.nextInt(8999));String name=request.getParameter("name");session.setAttribute(name,number);g.setColor(getColor(20,130));int x=(int)(width*0.2);int y=(int)(height*0.8);g.drawString(number,x,y);g.dispose();JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(response.getOutputStream());encoder.encode(image);out.close();%>再建⼀个test.jsp页⾯调⽤验证码:<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>⽆标题⽂档</title></head><body><% //同样实现取消客户端缓存response.setHeader("Pragma","No-cache");response.setHeader("Cache-Control","no-cache");response.setDateHeader("Expires", 0);String name="loginCode";%>验证码:<img src="authen.jsp?name=<%=name%>" /></body></html>在上述的两个页⾯中都有取消客户端缓存的功能,这是因为再有的游览器中,⽐如使⽤的IE游览器的游览⽅式,会先将图⽚放在缓存中,当再次请求的时候会现在内存中查找是不是已经有了,有的话就不在请求,这使得在刷新验证码的时候失败,所以要使游览器不读取缓存的图⽚,就需要取消缓存。

JSP验证码大全之验证码使用与乱码解决

JSP验证码大全之验证码使用与乱码解决

JSP验证码大全之验证码使用与乱码解决2009-06-22 14:51 以上两篇文章的内容介绍了有关JSP中产生数字验证码跟中文验证码的源代码并做了分析,本文中介绍如何对以上产生的数字跟中文验证码进行使用,以及如何解决中文验证码的乱码无法正确验证的问题。

对验证码的使用分为两个部分,分别为验证码的调用和验证过程,以下分别做说明介绍。

三、在JSP中调用验证码使用验证码直接在图片处调用产生验证码的JSP文件即可,同时在刷新验证码按钮处的js代码中使用JSP验证码文件,页面源码如下。

<form id="dForm" method=post action="val.jsp"><ul class="sFrm"><li><b></b><img id="code" border=0 src="Num.jsp"/><input type="button" value="看不清,换一张" onClick="document.getElementById('code').src='ColorChinese.jsp'"><div class="clear0"></div></li> <li><b>验证码</b><input type="text" name="input" maxlength=8 value="" styleClass="sIpt itemFm "><div class="clear0"></div></li><li class="bar"><b></b><input type="submit" value="验证测试" styleClass="logbtn3"></li></ul></form>四、在JSP中验证码的验证过程以及中文乱码处理获取用户输入的验证码并与Session中的验证码比较,相同即通过,否则拒绝,对于JSP中中文验证码的处理注意要在页面中定义JSP页面编码跟获取Session的字符编码一致,此处使用的是统一的GB2312编码,否则将出现验证码无法成功验证的情况。

JavaScript实现页面动态验证码的实现示例

JavaScript实现页面动态验证码的实现示例

JavaScript实现页⾯动态验证码的实现⽰例引⾔:现在很多在⽤户登陆或注册的时候为了防⽌程序攻击,加⼊了动态验证的技术,⼀般是让⽤户输⼊随即⽣成的验证码来实现。

我⾃⼰写了⼀个没有跟后台交互的,就在前端验证,发出来给⼤家看看。

效果图:实现思路:把数字和字母放到⼀个数组中,通过随机的⽅式取得数组下标,总共取4个组成验证码;把验证码渲染出来(⼀个⼀个的渲染);绘制⼀定数量的⼲扰线,随机颜⾊;输⼊验证码,输⼊4位以后去验证,正确显⽰钩,错误显⽰叉并且刷新验证码。

编写构造函数⽂本构造函数//⽂字的构造函数function Text(o){this.x=0,//x坐标this.y=0,//y坐标this.text='',//内容this.font=null;//字体this.textAlign=null;//对齐⽅式this.init(o);}Text.prototype.init=function(o){for(var key in o){this[key]=o[key];}}Text.prototype.render=function(context){this.ctx=context;innerRender(this);function innerRender(obj){var ctx=obj.ctx;ctx.save()ctx.beginPath();ctx.translate(obj.x,obj.y);if(obj.font){ctx.font=obj.font;}if(obj.textAlign){ctx.textAlign=obj.textAlign;}if(obj.fill){//是否填充obj.fillStyle?(ctx.fillStyle=obj.fillStyle):null;ctx.fillText(obj.text,0,0);}ctx.restore();}return this;}线段构造函数//直线的构造function Line(ctx,o){this.x=0,//x坐标this.y=0,//y坐标this.startX=0,//开始点x位置this.startY=0, //开始点y位置this.endX=0,//结束点x位置this.endY=0;//结束点y位置this.thin=false;//设置变细系数this.ctx=ctx;this.init(o);}Line.prototype.init=function(o){for(var key in o){this[key]=o[key];}}Line.prototype.render=function(){innerRender(this);function innerRender(obj){var ctx=obj.ctx;ctx.save()ctx.beginPath();ctx.translate(obj.x,obj.y);if(obj.thin){ctx.translate(0.5,0.5);}if(obj.lineWidth){//设定线宽ctx.lineWidth=obj.lineWidth;if(obj.strokeStyle){ctx.strokeStyle=obj.strokeStyle;}//划线ctx.moveTo(obj.startX, obj.startY);ctx.lineTo(obj.endX, obj.endY);ctx.stroke();ctx.restore();}return this;}按长度获取验证码//根据指定长度⽣成随机字母数字Verifiable.prototype.randomWord=function(range){var str = "",pos,arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; for(var i=0; i<range; i++){pos = Math.round(Math.random() * (arr.length-1));str += arr[pos];}return str;}绘制⽂字//绘制⽂字Verifiable.prototype.drawText=function(){var that=this;var count = 4;//⽂字个数var textW = 40;//⽂字所占宽var code=this.code = this.randomWord(count);var codeArr = code.split("");var text,x ;codeArr.forEach(function(c,i){x = that.w/count*i+textW/2;//绘制⽂字text = new Text({x:x,y:textW-10,text:c,font:'30px ans-serif',textAlign:'center',fill:true,fillStyle:'#412D6A'});that.renderArr.push(text);})}此时效果:绘制⼲扰线//绘制⼲扰线Verifiable.prototype.interfering=function(){var count = this.lineCount=20,line,ctx=this.ctx;var startX,startY,endX,endY,color;for(var i=0;i<count;i++){//随机开始坐标,结束坐标、颜⾊startX = _.getRandom(0,140);startY = _.getRandom(0,40);endX = _.getRandom(0,140);endY = _.getRandom(0,40);color = _.getRandomColor();//定义⼀条直线line = new Line(ctx,{x:0,y:0,startX:startX,startY:startY,endX:endX,endY:endY,strokeStyle:color})this.renderArr.push(line);}}此时效果如下:加⼊页⾯布局<!DOCTYPE html><html lang="zh"><head><meta charset="UTF-8"><title>verifiable</title><style>width:140px;height:40px;position:absolute;}#inputDiv{width:220px;position:absolute;margin:0 auto;left:0;top:30px;right:0;bottom:0;}#container{width:220px;height:60px;position:absolute;margin:0 auto;left:0;top:60px;right:0;bottom:0;}.refresh{position:absolute;left:140px;}</style></head><body><div id='inputDiv'>验证码:<input size=10 id='codeInput'><img id='stateImg' style="vertical-align: middle;width:20px"></img></div><div id="container"><div id='box'></div><a href="javascript:void 0" class="refresh" onclick="refresh()">换⼀张</a></div></body><script type="text/javascript" src='verifiable.js'></script><script type="text/javascript">var box = document.getElementById('box');var stateImg = document.getElementById('stateImg');var codeInput = document.getElementById('codeInput');verifiable.init(box,codeInput,stateImg);//换⼀张function refresh(){verifiable.renderArr.length=0;verifiable.draw();}</script></html>加⼊输⼊框事件//输⼊框事件Verifiable.prototype.inputValid=function(input){var val = input.value;if(val.length<4) return ;if(this.code==val){console.log('suc');this.result(0);}else{this.result(1);}}加⼊成功、失败验证//处理结果Verifiable.prototype.result=function(result){var codeInput = this.codeInput;var stateImg = this.stateImg;if(result==0){//成功stateImg.src="./images/suc.jpeg";codeInput.readOnly=true;}else {//失败codeInput.readOnly=false;stateImg.src="./images/fail.jpeg";this.renderArr.length=0;this.draw();}}完成到此这篇关于JavaScript实现页⾯动态验证码的实现⽰例的⽂章就介绍到这了,更多相关JavaScript 动态验证码内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

JavaWeb通过JSP的Servlet生成数字、字母、中文混合验证码

JavaWeb通过JSP的Servlet生成数字、字母、中文混合验证码
ctmp = String.valueOf((char) itmp);
break;
case 2: // 生成汉字
String[] rBase = { "0", "1", "2", "3", "4", "5", "6", "7", "8",
"9", "a", "b", "c", "d", "e", "f" };
// 生成第2位的位码
int r4;
if (r3 == 10) {
r4 = random.nextInt(15) + 1; //生成1到16之间的随机数
} else if (r3 == 15) {
int g = s + random.nextInt(e - s); //随机生成RGB颜色中的g值
int b = s + random.nextInt(e - s); //随机生成RGB颜色中的b值
return new Color(r, g, b);
}
public void service(HttpServletRequest request, HttpServletResponse response)
<tr>
<td>&nbsp;</td>
<td colspan="2"><input name="Submit" type="submit" class="btn_bg" value="登录">

JSP实现登录功能之添加验证码

JSP实现登录功能之添加验证码

JSP实现登录功能之添加验证码jsp登陆验证,⽹页登陆验证带验证码校验,登录功能之添加验证码part_1:专门⽤于⽣成⼀个验证码图⽚的类:VerificationCode.Javapackage cn.mike.javase.test;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Random;import javax.imageio.ImageIO;import org.junit.Test;/*** @author : Administrator* @function : 这是⽤来测试随机⽣成验证码图⽚的类;*/public class VerificationCode {/*** 单元测试,试⼀下能不能⾃动⽣成验证码图⽚*/// 这个函数是单元测试时使⽤的,这⾥private⼀下外⾯就调⽤不到了;/* @Test *//* public */private void test_fun() {VerificationCode vc = new VerificationCode();BufferedImage image = vc.getImage();try {// ⽣成验证码图⽚,并保存到指定的路径VerificationCode.output(image, new FileOutputStream(new File(".\\image\\vcode_2.jpg")));} catch (FileNotFoundException e) {e.printStackTrace();}// 将随机⽣成的⽂本内容输出到控制台,⽤于校验System.out.println(vc.getText());}private int w = 70;// 宽private int h = 35;// ⾼private String text;// ⽂本内容(验证码字符串)private Random r = new Random();private String[] fontNames = { "宋体", "华⽂楷体", "⿊体", "微软雅⿊", "楷体_GB2312" };// 随机字符集合中不包括0和o,O,1和l,因为这些不易区分private String codes = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYXZ";// 验证码图⽚的背景⾊:⽩⾊private Color bgColor = new Color(255, 255, 255);/*** 返回⼀个验证码图⽚buffer对象:BufferedImage*/public BufferedImage getImage() {BufferedImage image = createImage();// 获取绘图环境(画笔⼯具)Graphics2D g2 = (Graphics2D) image.getGraphics();// sb :⽤来保存验证码字符串⽂本内容StringBuilder sb = new StringBuilder();for (int i = 0; i < 4; ++i) {// 随机⽣成4个字符String s = randomChar() + "";sb.append(s);float x = i * 1.0F * w / 4;g2.setFont(randomFont());g2.setColor(randomColor());g2.drawString(s, x, h - 5);}this.text = sb.toString();// 记录验证码⽂本内容drawLine(image);// 画⼲扰线return image;}/*** @return 获取验证码⽂本内容*/public String getText() {return text;}/*** @param image* @param out* 将⽂本写到指定的输出流。

JS实现简单短信验证码界面

JS实现简单短信验证码界面

JS实现简单短信验证码界⾯1.要实现短信验证码界⾯,⾸先要有⼀个⽂本框,旁边是按钮,点击时开始倒计时。

2.先创建⽂本框和按钮,按钮设置对应的id,然后在js中通过id获取按钮这个元素,对其执⾏操作。

同时应设置倒计时时间以及计时器变量,并使点击发送按钮后倒计时结束前⽆法继续点击按钮重新发送。

3.倒计时结束后,清除计时器,并使⽂字改变为“重新发送验证码”,恢复对按钮能操作的功能,同时使倒计时的数从5秒重新开始以便点击后重新倒计时。

<head><meta charset="UTF-8"><title>js发送短信验证码</title></head><body><input type="text"/><button id="bt01">发送验证码</button></body><script type="text/javascript">var bt01 = document.getElementById("bt01");bt01.onclick = function() {bt01.disabled = true; //当点击后倒计时时候不能点击此按钮var time = 5; //倒计时5秒var timer = setInterval(fun1, 1000); //设置定时器function fun1() {time--;if(time>=0) {bt01.innerHTML = time + "s后重新发送";}else{bt01.innerHTML = "重新发送验证码";bt01.disabled = false; //倒计时结束能够重新点击发送的按钮clearTimeout(timer); //清除定时器time = 5; //设置循环重新开始条件}}}</script>总结以上所述是⼩编给⼤家介绍的JS实现简单短信验证码界⾯,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

jsp页面验证码源代码在java后台中生成验证码的ImageIO传到前端页面显示,同时把验证码的v alue值传入session 中用于与用户输入的验证码进行匹配,在用户验证中使用ajax技术,在不刷新页面的同时进行验证码验证。

程序结构图:VerifyCodeUtils程序主要内容为通过Java生成验证码的图片,以及验证码的value值,程序如下:package utils;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.util.HashMap;import java.util.Map;import java.util.Random;publicclass VerifyCodeUtils {privatestatic BufferedImage image = null;privatestatic Random random = new Random();//在自己定义的一些数中,生成4位随机数publicstatic String getVerifyCode() {String str = "";char[] code = newchar[]{'A','B','C','D','E','F','G','H','I ','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i',' j','k','m','n','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7','8','9'};Random random = new Random();for(int i = 0; i <4; i++) {str += String.valueOf(code[random.nextInt(code.length)]);}return str;}//生成验证码图像publicstatic Map getVerifyCode(int width, int heigth) {VerifyCodeUtils.image = new BufferedImage(width, heigth, Bu fferedImage.TYPE_INT_RGB);Graphics2D g = (Graphics2D) VerifyCodeUtils.image.g etGraphics();String verifyCode = getVerifyCode();Map map = new HashMap();map.put("verifyCode", verifyCode);//将图像填充为白色g.setColor(Color.WHITE);g.fillRect(0, 0, width, heigth);//设置字体g.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, heigth-10));//画边框。

g.setColor(VerifyCodeUtils.getColor());g.drawRect(0, 0, width, heigth);//随机产生干扰线,使图象中的认证码不易被其它程序探测到g.setColor(Color.BLACK);for (int i = 0; i <50; i++) {int x = VerifyCodeUtils.random.nextInt(width);int y = VerifyCodeUtils.random.nextInt(heigth);int xl = VerifyCodeUtils.random.nextInt(5);int yl = VerifyCodeUtils.random.nextInt(5);g.setColor(getColor());g.drawLine(x, y, x + xl, y + yl);}char c;for(int i = 0; i <4; i++) {c = verifyCode.charAt(i);g.drawString(c+"", i*20+40, heigth-10);}map.put("image", VerifyCodeUtils.image);return map;}//随机化颜色publicstatic Color getColor() {int red = 0, green = 0, blue = 0;// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。

red = VerifyCodeUtils.random.nextInt(255);green = VerifyCodeUtils.random.nextInt(255);blue = VerifyCodeUtils.random.nextInt(255);returnnew Color(red,green,blue);}}VerifyCodeServlet把VerifyCodeUtils生成的验证码图片通过io流传入前端显示,代码如下:package Servlet;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Map;import javax.imageio.ImageIO;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 utils.VerifyCodeUtils;/*** Servlet implementation class VerifyCodeServlet*/@WebServlet("/")publicclass VerifyCodeServlet extends HttpServlet { privatestaticfinallong serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public VerifyCodeServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, Ht tpServletResponse response)*/protectedvoid doGet(HttpServletRequest request, HttpServlet Response response) throws ServletException, IOException {response.setHeader("Expires", "-1");response.setHeader("Cache-Control", "no-cache");response.setHeader("Pragma", "no-cache");response.setHeader("Content-type", "image/jpeg");Map map = VerifyCodeUtils.getVerifyCode(223, 50);//把verifyCode的数值传入session中用于验证用户输入的验证码是否正确request.getSession().setAttribute("verifyCode", map.get(" verifyCode").toString().toUpperCase());//通过IO流传入前端显示ImageIO.write((BufferedImage) map.get("image"), "jpg", res ponse.getOutputStream());}/*** @see HttpServlet#doPost(HttpServletRequest request, H ttpServletResponse response)*/protectedvoid doPost(HttpServletRequest request, HttpServle tResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}页面jsp代码如下:<%@ pagelanguage="java"contentType="text/html; charset=utf -8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional/ /EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type"content="text/html; charset =utf-8"><base id="base"href="${pageContext.request.contextPath}"><title>验证码测试界面</title><style>div{float:left;}input{width:223px;height:31px;margin-right:20px;}img{width:223px;height:35px;}p{margin:10px;}</style></head><body><script src="${pageContext.request.contextPath}/JS/demo.js "></script><div><input type="text"name="verifyCode"id="verifyCode"placehol der="验证码"onblur="check_verifyCode()"></div><div><img src="${pageContext.request.contextPath}/servlet/Verif yCodeServlet"style="width: 100%"onclick="this.src=this.sr c + '?' + Math.random()"/></div><div><p id = "tip"></p></div></body></html>js实现ajax代码如下:/****/function check_verifyCode(){var XMLHttpReqVerifyCode = null;var url =document.getElementById("base").href +"/servlet/Te stVerifyCodeServlet";var verifyCode = document.getElementById("verifyCode").valu e;var tip = document.getElementById("tip");var errorTip = "输入的验证码不正确";var successTip = "输入的验证码正确";tip.innerHTML=errorTip;if(verifyCode==null || verifyCode==""){tip.innerHTML=errorTip;tip.style.color = "red";}else{if(window.XMLHttpRequest) {//DOM2浏览器XMLHttpReqVerifyCode = new XMLHttpRequest();} elseif(window.ActiveXObject) {//使用json语法创建数组var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', ' MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP '];for(var i = 0; i <MSXML.length; i++) {try{XMLHttpReqVerifyCode = new ActiveXObject(MSXML[i]);} catch(e) {}}}XMLHttpReqVerifyCode.open("POST",url, true);XMLHttpReqVerifyCode.setRequestHeader("Content-Type", "ap plication/x-www-form-urlencoded");XMLHttpReqVerifyCode.onreadystatechange = function testVeri fyCodeServletResponse(){if(XMLHttpReqVerifyCode.readyState == 4&& (XMLHttpReqVerif yCode.status == 200 || XMLHttpReqVerifyCode.status == 304)) {if(XMLHttpReqVerifyCode.responseText == 1){tip.innerHTML = successTip;tip.style.color = "green";}elseif(XMLHttpReqVerifyCode.responseText == 0){tip.innerHTML = errorTip;tip.style.color = "red";}}}XMLHttpReqVerifyCode.send("code="+verifyCode);}//ajax前后台交互function createXMLHttpRequest(XMLHttpReq) {if(window.XMLHttpRequest) {//DOM2浏览器XMLHttpReq = new XMLHttpRequest();} elseif(window.ActiveXObject) {//使用json语法创建数组var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', ' MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP '];for(var i = 0; i <MSXML.length; i++) {try{XMLHttpReq = new ActiveXObject(MSXML[i]);} catch(e) {}}return XMLHttpReq;}}}TestVerifyCodeServlet与js交互代码为:package Servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** Servlet implementation class TestVerifyCodeServlet */@WebServlet("/TestVerifyCodeServlet")publicclass TestVerifyCodeServlet extends HttpServlet { privatestaticfinallong serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public TestVerifyCodeServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, Ht tpServletResponse response)*/protectedvoid doGet(HttpServletRequest request, HttpServlet Response response) throws ServletException, IOException {// TODO Auto-generated method stubString codeTrue = (String) request.getSession().get Attribute("verifyCode");String codeInput = request.getParameter("code");System.out.println(codeInput);response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter();//打印流if(codeInput!=null){if(codeInput.toUpperCase().equals(codeTrue)){out.println("1");}else{out.println("0");}}}/*** @see HttpServlet#doPost(HttpServletRequest request, H ttpServletResponse response)*/protectedvoid doPost(HttpServletRequest request, HttpServle tResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}xml代码为<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-insta nce"xmlns="/xml/ns/javaee"xsi:schemaLo cation="/xml/ns/javaee http://java.sun. com/xml/ns/javaee/web-app_2_5.xsd"version="2.5"><display-name></display-name><welcome-file-list><welcome-file>demo.jsp</welcome-file></welcome-file-list><servlet><servlet-name>VerifyCodeServlet</servlet-name><servlet-class>Servlet.VerifyCodeServlet</servlet-class></servlet><servlet-mapping><servlet-name>VerifyCodeServlet</servlet-name><url-pattern>/servlet/VerifyCodeServlet</url-pattern></servlet-mapping><servlet><servlet-name>TestVerifyCodeServlet</servlet-name><servlet-class>Servlet.TestVerifyCodeServlet</servlet-cla ss></servlet><servlet-mapping><servlet-name>TestVerifyCodeServlet</servlet-name><url-pattern>/servlet/TestVerifyCodeServlet</url-pattern></servlet-mapping></web-app>结果显示:。

相关文档
最新文档