欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java生成验证码

程序员文章站 2022-06-18 08:50:10
1. 本质:图片 2. 目的:防止恶意表单注册 3.代码: package cn.itcast.web.servlet; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet ......

1. 本质:图片

2. 目的:防止恶意表单注册
3.代码:
package cn.itcast.web.servlet;

import javax.imageio.imageio;
import javax.servlet.servletexception;
import javax.servlet.servletoutputstream;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.io.ioexception;
import java.util.random;

@webservlet("/checkcodeservlet")
public class checkcodeservlet extends httpservlet {
    protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {


        int width = 100;
        int height = 50;

        //1.创建一对象,在内存中图片(验证码图片对象)
        bufferedimage image = new bufferedimage(width,height,bufferedimage.type_int_rgb);


        //2.美化图片
        //2.1 填充背景色
        graphics g = image.getgraphics();//画笔对象
        g.setcolor(color.pink);//设置画笔颜色
        g.fillrect(0,0,width,height);

        //2.2画边框
        g.setcolor(color.blue);
        g.drawrect(0,0,width - 1,height - 1);

        string str = "abcdefghijklmnopqrstuvwxyzabcdefghigklmnopqrstuvwxyz0123456789";
        //生成随机角标
        random ran = new random();

        for (int i = 1; i <= 4; i++) {
            int index = ran.nextint(str.length());
            //获取字符
            char ch = str.charat(index);//随机字符
            //2.3写验证码
            g.drawstring(ch+"",width/5*i,height/2);
        }


        //2.4画干扰线
        g.setcolor(color.green);

        //随机生成坐标点

        for (int i = 0; i < 10; i++) {
            int x1 = ran.nextint(width);
            int x2 = ran.nextint(width);

            int y1 = ran.nextint(height);
            int y2 = ran.nextint(height);
            g.drawline(x1,y1,x2,y2);
        }


        //3.将图片输出到页面展示
        imageio.write(image,"jpg",response.getoutputstream());


    }

    protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
        this.dopost(request,response);
    }
}