网页验证码的实现

一、生成验证码

package com.bobo.servlet;

import java.io.IOException;

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

import com.bobo.util.AuthCode;

public class Yanzhengma extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        process(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        process(request, response);
    }

    private void process(HttpServletRequest request,
            HttpServletResponse response) {
        // TODO Auto-generated method stub
        String authCode = AuthCode.getAuthCode();
        request.getSession().setAttribute("authCode", authCode); // 将验证码保存到session中,便于以后验证

        try {
            // 发送图片
            ImageIO.write(AuthCode.getAuthImg(authCode), "JPEG",
                    response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

二、通过servlet输出验证码

package com.bobo.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

public class AuthCode {
    public static final int AUTHCODE_LENGTH = 5;        //验证码长度
    public static final int SINGLECODE_WIDTH = 17;    //单个验证码宽度
    public static final int SINGLECODE_HEIGHT = 40;    //单个验证码高度
    public static final int SINGLECODE_GAP = 4;        //单个验证码之间间隔
    public static final int IMG_WIDTH = AUTHCODE_LENGTH * (SINGLECODE_WIDTH + SINGLECODE_GAP);
    public static final int IMG_HEIGHT = SINGLECODE_HEIGHT;
    
    public static String getAuthCode() {
        String authCode = "";
        for(int i = 0; i < AUTHCODE_LENGTH; i++) {
            authCode += (new Random()).nextInt(10);
        }
        return authCode;
    }
    
    public static BufferedImage getAuthImg(String authCode) {
        //设置图片的高、宽、类型
        //RGB编码:red、green、blue
        BufferedImage img = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_BGR);
        //得到图片上的一个画笔
        Graphics g = img.getGraphics();
        //设置画笔的颜色,用来做背景色
        g.setColor(Color.YELLOW);
        //用画笔来填充一个矩形,矩形的左上角坐标,宽,高
        g.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
        //将画笔颜色设置为黑色,用来写字
        g.setColor(Color.BLACK);
        //设置字体:宋体、不带格式的、字号
        g.setFont(new Font("宋体", Font.PLAIN, SINGLECODE_HEIGHT + 5));
        
        //输出数字
        char c;
        for(int i = 0; i < authCode.toCharArray().length; i++) {
            //取到对应位置的字符
            c = authCode.charAt(i);
            //画出一个字符串:要画的内容,开始的位置,高度
            g.drawString(c + "", i * (SINGLECODE_WIDTH + SINGLECODE_GAP)+ SINGLECODE_GAP / 2, IMG_HEIGHT);
        }
        Random random = new Random();
        //干扰素
        for(int i = 0; i < 20; i++) {
            int x = random.nextInt(IMG_WIDTH);
            int y = random.nextInt(IMG_HEIGHT);
            int x2 = random.nextInt(IMG_WIDTH);
            int y2 = random.nextInt(IMG_HEIGHT);
            g.drawLine(x, y, x + x2, y + y2);
        }
        return img;
    }

     
}

三、前端html利用img标签来呈现验证码

 <div class="div-authCode form-group">
                            <div class="col-xs-7">
                                <label for="authCode" class="sr-only"></label>
                                <input type="text" id="authCode" name="authCode" class="form-control input-lg" placeholder="请输入验证码">
                            </div>
                            <div class="col-xs-5">
                                <img src="Yanzhengma?" class="auth-img" id="auth-code-img" alt="验证码">
                            </div>
                       </div> 

四,为img标签添加点击事件,通过更改其src属性来更换验证码

//验证码图片点击,切换随机数
var authCodeImg=document.getElementById("auth-code-img");
EventUtil.addHandler(authCodeImg, "click", function(){     
    this.src=this.src+"?";
});

 

posted @ 2015-08-06 09:47  bobo的学习笔记  阅读(444)  评论(0编辑  收藏  举报