基于jsp+Servlet实现注册页面Ajax验证码

1 篇文章 0 订阅

去年在学校做课设时用到表单验证时遇到有需要用到验证码的地方,于是做了一个小demo。最近记性越来越不好,所以记录一下。用到三个文件,分别为:vercode.jsp,AuthImg.java,CheckVerServlet.java

一、vercode.jsp

1.check()做到输入判空操作,以及向服务端发起异步请求并处理从服务端获得响应

function check() {
	if(document.getElementById("vercode").value==""){
		  document.getElementById("verSpan").innerHTML = "验证码不能为空";
	      return; 
	  }    
 
    var xmlHttp;
    if(
        window.XMLHttpRequest) { //如果是ie7以上浏览器,使用new new XMLHttpRequest()创建对象
        xmlHttp = new XMLHttpRequest();
    }
    else { //如果是ie7以下使用new new XMLHttpRequest()创建对象
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHttp.onreadystatechange = function () {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
          
            if (xmlHttp.responseText == "1") {//从服务端端返回的字符串如果为1,则判定输入验证码正确
                document.getElementById("verSpan").innerHTML = "验证码正确";
           }
           else {
               document.getElementById("verSpan").innerHTML = "验证码不正确";
            }
      }
    }
   
    var v =document.getElementById("vercode").value;
    
    xmlHttp.open("GET", "CheckVerServlet?vercode=" + v + "&random=" + Math.random, true);
    xmlHttp.send();
}

2.refresh()做到刷新验证码,其中src="AuthImg",AuthImg为一个Servlet工具类,其作用是产生验证码,在后面做详细说明

function refresh()  
{  
document.getElementById("authImg").src="AuthImg?now="+new Date();//使用时间作为参数避免浏览器从缓存取图片  
}  
3.delData()作用为:在获得光标时清空输入内容以及提示信息
function delData() {
  
    document.getElementById("vercode").value ="";
    document.getElementById("verSpan").innerHTML="";
}
3.html部分,输入框设置获得焦点事件响应:delData(),失焦点响应事件:check()

     刷新验证码部分包含文件为AuthImg (该文件为一个Java文件,功能为生成一个.jepg的图片)

<body>
 <form>
   <table>
     <tr>  
        <td>验证码:
        <input id="vercode" type="text"  οnblur="check();" οnfοcus="delData();"/><span id="verSpan"></span></td> 
        </tr>
        <tr>
        <td><img alt="" src="AuthImg" id="authImg" ><a href="#" οnclick="refresh()">刷新验证码</a></td>
        <td></td> 
    </tr> 
    </table>
    </form>
</body>

二、Auth.java(生成验证码,验证码为.jepg的图片)

核心部分,在jsp页面获得验证码图片时将验证码字符串存入session 中,然后在服务端做处理时拿到验证码字符串

   // 该变量用来保存系统生成的随机字符串  
        String sRand = "";  
        for (int i = 0; i < 6; 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);  
        }  
      System.out.println("AuthImg::"+sRand);
        // 取得用户Session  
        HttpSession session = request.getSession(true);  
        // 将系统生成的图形验证码添加  
        session.setAttribute("rand", sRand);  
        g.dispose();  
        // 输出图形验证码图片  
        ImageIO.write(image, "JPEG", response.getOutputStream());  

三、CheckVerServlet.java处理异步请求,从vercode.jsp中发起异步请求,这里从session中获得验证码字符串,然后判断用户输入的验证码是否与session中的验证码字符串相等,如果相等则响应写入字符串1,将该字符串传回给vercode.jsp中的onreadystatechange回调函数,如果 写入的值为字符串"1",则提示用户:验证码输入正确,否则则提示验证码输入错误。

 String vercode=request.getParameter("vercode");
		HttpSession session=request.getSession(true);
		if(session.getAttribute("rand")!=null){
			
			String rand=(String) session.getAttribute("rand");
			
			OutputStream os=response.getOutputStream();
			if(rand.equalsIgnoreCase(vercode)){
				os.write("1".getBytes());
			}
		}
		

	}


效果图

1.验证码判空


2.验证码验证正确与否

 

demo完整代码

<!--vercode.jsp>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="javax.servlet.http.HttpSession" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">  
//刷新验证码  
function refresh()  
{  
document.getElementById("authImg").src="AuthImg?now="+new Date();//使用时间作为参数避免浏览器从缓存取图片  
}  
function check() {
	if(document.getElementById("vercode").value==""){
		  document.getElementById("verSpan").innerHTML = "验证码不能为空";
	      return; 
	  }    
   
  
    var xmlHttp;
    if(window.XMLHttpRequest) { //如果是ie7以上浏览器,使用new new XMLHttpRequest()创建对象
        xmlHttp = new XMLHttpRequest();
    }
    else { //如果是ie7以下使用new new XMLHttpRequest()创建对象
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHttp.onreadystatechange = function () {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
          
            if (xmlHttp.responseText == "1") {//从服务端端返回的字符串如果为1,则判定输入验证码正确
                document.getElementById("verSpan").innerHTML = "验证码正确";
           }
           else {
               document.getElementById("verSpan").innerHTML = "验证码不正确";
            }
      }
    }
   
    var v =document.getElementById("vercode").value;
    
    xmlHttp.open("GET", "CheckVerServlet?vercode=" + v + "&random=" + Math.random, true);
    xmlHttp.send();
}
function delData() {
  
    document.getElementById("vercode").value ="";
    document.getElementById("verSpan").innerHTML="";
}
</script>  
</head>
<body>
 <form>
   <table>
     <tr>  
        <td>验证码:
        <input id="vercode" type="text"  οnblur="check();" οnfοcus="delData();"/><span id="verSpan"></span></td> 
        </tr>
        <tr>
        <td><img alt="" src="AuthImg" id="authImg" ><a href="#" οnclick="refresh()">刷新验证码</a></td>
        <td></td> 
    </tr> 
    </table>
    </form>
</body>
</html>
<!--AuthImg.java>
package com.verify.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
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;

/**
 * Servlet implementation class AuthImg
 */
public class AuthImg extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Font myFont = new Font("Arial Black", Font.PLAIN, 16);  
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AuthImg() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init() throws ServletException {  
        super.init();  
    }  

    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);  
    }  
  
    @Override  
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  
        // 阻止生成的页面内容被缓存,保证每次重新生成随机验证码  
        response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        response.setContentType("image/jpeg");  
        // 指定图形验证码图片的大小  
        int width = 100, 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(myFont);  
        // 随机生成线条,让图片看起来更加杂乱  
        g.setColor(getRandColor(160, 200));  
        for (int i = 0; i < 155; i++) {  
            int x = random.nextInt(width - 1);// 起点的x坐标  
            int y = random.nextInt(height - 1);// 起点的y坐标  
            int x1 = random.nextInt(6) + 1;// x轴偏移量  
            int y1 = random.nextInt(12) + 1;// y轴偏移量  
            g.drawLine(x, y, x + x1, y + y1);  
        }  
        // 随机生成线条,让图片看起来更加杂乱  
        for (int i = 0; i < 70; i++) {  
            int x = random.nextInt(width - 1);  
            int y = random.nextInt(height - 1);  
            int x1 = random.nextInt(12) + 1;  
            int y1 = random.nextInt(6) + 1;  
            g.drawLine(x, y, x - x1, y - y1);  
        }  
  
        // 该变量用来保存系统生成的随机字符串  
        String sRand = "";  
        for (int i = 0; i < 6; 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);  
        }  
      System.out.println("AuthImg::"+sRand);
        // 取得用户Session  
        HttpSession session = request.getSession(true);  
        // 将系统生成的图形验证码添加  
        session.setAttribute("rand", sRand);  
        g.dispose();  
        // 输出图形验证码图片  
        ImageIO.write(image, "JPEG", response.getOutputStream());  
      
       
    }  
  
    // 随机生成一个字符  
    private String getRandomChar() {  
        int rand = (int) Math.round(Math.random() * 2);// 将0~2的小数四舍五入生成整数  
        long itmp = 0;  
        String  ctmp ="/u0000";  
        // 根据rand的值来决定是生成一个大写字母、小写字母和数字  
        switch (rand) {  
        // 生成大写字母的情形  
        case 1:  
            itmp = Math.round(Math.random() * 25 + 65);  
            ctmp = (char) itmp+"";  
            return String.valueOf(ctmp);  
            // 生成小写字母  
        case 2:  
            itmp = Math.round(Math.random() * 25 + 97);  
            ctmp = (char) itmp+"";  
            return String.valueOf(ctmp);  
            // 生成数字  
        default:  
            itmp = Math.round(Math.random() * 9);  
            return String.valueOf(itmp);  
        }  
    }
   
	
}

<!--CheckVerServlet.java-->
package com.verify.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class CheckVerServlet
 */
public class CheckVerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckVerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	

        String vercode=request.getParameter("vercode");
		HttpSession session=request.getSession(true);
		if(session.getAttribute("rand")!=null){
			
			String rand=(String) session.getAttribute("rand");
			
			OutputStream os=response.getOutputStream();
			if(rand.equalsIgnoreCase(vercode)){
				os.write("1".getBytes());
			}
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}





  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值