Servlet 实现随机验证码

首先说明一下随机验证码的流程。


从流程图可以看出,我们需要做一下几步工作。


  1. 通过后台Servlet生成随机图片。
  2. 创建Session会话,并通过登录页面进行验证。
  3. 刷新随机图片超链接后,更换验证码图片。
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.individuals.web.servlet;

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.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Barudisshu
 */
@WebServlet(name = "ImageCodeMakerServlet", urlPatterns = {"/ImageCodeMakerServlet"})
public class ImageCodeMakerServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置页面不缓存
        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.createGraphics();

        //创建随机对象
        Random random = new Random();

        //用随机颜色填充图像背景
        g.setColor(new Color(255, 255, 255));

        //图像形状
        g.fillRect(0, 0, width, height);

        //设置字体
        g.setFont(new Font("Tahoma", Font.PLAIN, 20));

        //随机数字符串
        String sRand = "";

        for (int i = 0; i < 4; i++) {
            //生成四个数字字符
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
            //生成随机颜色
            g.setColor(new Color(100 + random.nextInt(155), random.nextInt(100), 100 + random.nextInt(155)));
            //将随机数字画在图像上
            g.drawString(rand, (12 + random.nextInt(2)) * i + 6, 18);
        }

        //生成干扰线
        for (int k = 0; k < 24; k++) {
            g.setColor(getRandomColor(0, 255));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(6);
            int y1 = random.nextInt(6);
            g.drawLine(x, y, x + x1, y + y1);
        }
        
        //生成干扰像素点
        for (int i = 0; i < 10; i++) {
            g.setColor(getRandomColor(50, 180));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g.drawOval(x, y, 1, 1);
        }
        
        //将生成的随机数字写入Session会话
        request.getSession().setAttribute("randcode", sRand);

        //使图像生效
        g.dispose();

        //输出图像到页面
        ImageIO.write(image, "JPEG", response.getOutputStream());

    }

    /**
     * 产生一个随机颜色
     *
     * @param fc 颜色分量最小值
     * @param bc 颜色分量最大值
     * @return
     */
    public Color getRandomColor(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);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

实现点击图片更新随机验证码。需要在URL上加上Math.random(),通过不同参数的URL地址响应,否则访问同一个URL资源将不更新。 


$('#verification').click(function () {
        $('#verification').attr('src', 'ImageCodeMakerServlet?' + Math.random());
    });


转载于:https://my.oschina.net/Barudisshu/blog/149842

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值