首页 > 代码库 > Java验证码和ajax判断

Java验证码和ajax判断

关于来了解相关的api

BufferedImage(int width, int height, int imageType) 构造一个类型为预定义图像类型之一的 BufferedImage

BufferedImage 描述具有可访问图像数据缓冲区的Image 字段摘要(TYPE_INT_RGB)表示一个图像,它具有合成整数像素的 8 位 RGB 颜色分量。

getGraphics() 此方法返回 Graphics2D(Graphics2D 类扩展 Graphics 类,以提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制。它是用于在 Java(tm) 平台上呈现二维形状、文本和图像的基础类。)

jquery 相关api : post请求异步更新

实现效果如图

技术分享

 

 

首相是先关的html代码:

<html>

<head>
    <meta charset="utf-8">
    <title>欢迎注册</title>
    <script type="text/javascript" src="http://www.mamicode.com/js/jquery-1.10.1.js"></script>
    <style>
    #main {
        width:580px;
        height: 400px;
        margin: auto;
        margin-top: 200px;
    }
    
    #main input {
        margin-top: 10px;
    }
    
    .btn {
        width: 80px;
        height: 30px;
        background: green;
        color: white;
        font-size: 18px;
    }
    form{
        width:400pxs;
    }
    #name{
        display: none;
    }
    #uId{
        display: none;
    }
    </style>
</head>
<script type="text/javascript"> 

             $(function(){
                $("#userName").change(function(){
                   var mreg = /^[\u4E00-\u9FA5]{2,4}$/; 
                            if(!mreg.test($("#userName").val())) 
                            {
                                $("#name").css(‘display‘,‘inline‘);
                                $("#btns").attr(‘disabled‘,true);
                                $("#btns").css(‘background‘,‘grey‘);
                               
                            } else{
                                $("#name").css(‘display‘,‘none‘);
                                $("#btns").attr(‘disabled‘,false);
                                $("#btns").css(‘background‘,‘green‘);
                            }

                    var val=$("#userName").val();
                    val=$.trim(val);  //去除空格
                    if (val != null) {
                      var url="/ShoppingCar/valiateUserName";
                      var args={"userName":val,"time":new Date()};
                      	$.post(url, args, function(data) {
                        $("#exist").html(data);
                      });
                    }
                })

                $("#code").change(function() {
                    var value=http://www.mamicode.com/$("#code").val();
                    value=http://www.mamicode.com/$.trim(value);"/ShoppingCar/CodeCheck";
                        //加上时间,防止缓存,这里就相当于发送一个post请求,和表单请求的格式相近,一个变量名,一个值,成对发送
                        var args={"code":value,"time":new Date()};
                        //发送请求,返回的内容封装在data中
                        $.post(url, args, function(data) {
                        $("#checkcode").html(data);
                    });
                  }
                })
             });

             function changeCode() {
                var imgNode = document.getElementById("vimg");
                //重新加载验证码,达到刷新的目的  
                imgNode.src = "http://www.mamicode.com/ShoppingCar/AuthImageServlet?t=" + Math.random();  // 防止浏览器缓存的问题 
            }
     </script>
<body>

  

    <div id="main">
        <h2  style="margin-left: 40px;">请填写以下信息</h2>
        <form action="/ShoppingCar/RegisterServlet" method="post">
                                账 号:
            <input type="text" name="userName" id="userName" /><span id="name" style="color: red"> 名字只能是中文</span>
             <span id="exist"></span>
            <br/> 密 码:
            <input type="password" name="password" />
            <br />
                              验证码:
            <input type="text" name="code" id="code"> <span id="checkcode" ></span><br>
            <img id="vimg"  title="点击更换" onclick="changeCode();" src="http://www.mamicode.com/ShoppingCar/AuthImageServlet" style="margin-left: 99px;margin-top: 10px;"><br/>
            <p style="margin-top:10px;margin-left:42px;">
                    <input type="submit"  value="http://www.mamicode.com/注册" style="margin:auto;" class="btn" id="btns" />
                    <a href="http://www.mamicode.com/ShoppingCar/login.html"><input type="button"  value="http://www.mamicode.com/登入" style="margin:auto;" class="btn" /></a>
            </p>
        </form>
    </div>
  
     
</body>

</html>

  接下来是服务器端生成验证码的servlet

package gqx.shoppingcar.testservlet;

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 AuthImageServlet extends HttpServlet {

	private static final String CONTENT_TYPE = "text/html; charset=gb2312";     
    //设置字母的大小,大小     
    private Font mFont = new Font("Times New Roman", Font.PLAIN, 24);     
    public void init() throws ServletException     
    {     
        super.init();     
    }     
    //指定范围内生成rgb颜色
    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     
    {     
    	//no-cache指示请求或响应消息不能缓存
        response.setHeader("Pragma","No-cache");     
        response.setHeader("Cache-Control","no-cache");     
        response.setDateHeader("Expires", 0);     
        //表明生成的响应是图片     
        response.setContentType("image/jpeg");     
             
        int width=100, height=25;     
      //创建一个图片缓冲区
        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); 
        
      //画随机线     
        for (int i=0;i<15;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 < 10;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);     
        }    
        
        
      //写入文字
        g.setFont(mFont);     
        //生成随机数,并将随机数字转换为字母     
        String sRand="";     
        for (int i=0;i<4;i++)     
        {     
            int itmp = random.nextInt(26) + 65;     
            char ctmp = (char)itmp;     
            sRand += String.valueOf(ctmp);    
            g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))); 
            //使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本。
            //void drawString(String str, int x,int y)		str - 要绘制的 string。 x - x 坐标。   y - y 坐标
            g.drawString(String.valueOf(ctmp),22*i+10,22);     
        }     
    
        HttpSession session = request.getSession(true);     
        session.setAttribute("rand",sRand);     
        g.dispose(); 
        //使用支持给定格式的任意 ImageWriter 将一个图像写入 OutputStream。
        ImageIO.write(image, "JPEG", response.getOutputStream());     
    }     
}

在一个是响应页面发送来的数据,同时做出判断,将结果返回给显示层

package gqx.shoppingcar.testservlet;

import java.io.IOException;
import java.io.PrintWriter;

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 CodeCheck extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String code=request.getParameter("code");
		String result="";
		HttpSession session=request.getSession();
		System.out.println(code);
		String value=http://www.mamicode.com/(String)session.getAttribute("rand");
		if (!code.equals(value)) {
			result="<font color=‘red‘>验证码错误</font>";
			System.out.println("error");
		}else {
			
		}
		 response.setContentType("text/html;charset=UTF-8");
		 System.out.println(result);
		 response.getWriter().print(result);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}

至于名字的检验大同小异

package gqx.shoppingcar.testservlet;

import gqx.shoppingcar.service.impl.SerOperate;

import java.io.IOException;
import java.io.PrintWriter;

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

public class valiateUserName extends HttpServlet {

	/**
	 * 处理ajax验证名字是否已经存在
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name=request.getParameter("userName");
		SerOperate operate =new SerOperate();
		String result=null;
		if (operate.exist(name)) {
			result="<font color=‘red‘>该用户名已经被使用</font>";
			
		}else {
			result=" ";
		}
		response.setContentType("text/html;charset=UTF-8");		
		 response.getWriter().print(result);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}

此处的SerOperate是我在MVC的Service层处理的接口实现类。具体就不写了,会在后面的购物车代码中全部写上去。

 

Java验证码和ajax判断