基于servlet的验证码实现

来源:互联网 发布:linux hba卡 编辑:程序博客网 时间:2024/05/18 03:12

大致分析下,生成验证码的过程

1.利用 BufferedImage在内存中生成一张图片

2.获取画笔Graphics对象

3.生成随机的 验证码利用画笔画到图片上

4.生成干扰线

5.利用 ImageIO将图片输出到前台

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
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;

/**
 * Servlet implementation class imgServlet
 */
public class imgServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public imgServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //定义图片大小
        int width = 100;
        int height = 30;
        
        //在内存中生成图片
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        //获取画笔对象
        Graphics2D g = (Graphics2D) img.getGraphics();
        //画一个填充色为红色的矩形
        g.setColor(Color.yellow);
        g.fillRect(0, 0, width, height);
        //使用画笔对象画一个矩形边框
        g.setColor(Color.red);
        g.drawRect(0, 0, width-1, height-1);
        //生成随机码
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        Random random = new Random();
        Font font = new Font("黑体", Font.BOLD, 20);
        g.setFont(font);
        int x=15;
        for (int i = 0; i < 4; i++) {
            //旋转角度
            int  radian = random.nextInt(60)-30;   //弧度
            double angle = radian*Math.PI/180;     //角度
            g.rotate(angle, x, 20);
            //画出验证码
            int index = random.nextInt(str.length());
            char word = str.charAt(index);
            System.out.println(word);
            g.drawString(""+word,x,20);
            
            g.rotate(-angle, x, 20);
            //每个字符间距20
            x+=20;
            //画出干扰线
            g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
        }
        
        //向浏览器输出图片
        ImageIO.write(img, "jpg", response.getOutputStream());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

原创粉丝点击