Servlet验证码的实现

最近在学servlet的知识,了解了验证码的编写。再写一 遍加深印象!

//前面的导包什么的就不写了,IDE都会自动生成直接进入Servlet的编写吧
@WebServlet("/checkcode")
public class CheckCode extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
            //创建图片对象,相当于一个画板,并在构造函数中传入宽、高、图片类型
            BufferedImage img=new BufferedImage(90, 30,BufferedImage.TYPE_INT_BGR);
            //通过img对象获取画图对象
            Graphics pen=img.getGraphics();
            //提前这设置好验证码会用到的字符
            String[] codes= 
 {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"		,"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
				"0","1","2","3","4","5","6","7","8","9"};
            //创建随机数对象用于生成4位随机字符
                Random random=new Random();
            //声明一个字符串用在放生成的随机字符
            String code="";
                for(int i=0;i<=3;i++){
                        //随机生成四次连接到code字符串61代表数组长度
                        code=code+codes[random.nexInt(61)];
                                    }
            //设置文字颜色
            pen.setColor(Color.BULE);
            //向画板生成验证码,分别传入字符串以及绘画的位置
            pen.drawString(code,20,15);
            //简单生成以后可以向页面输出,传入“画板”对象,输出图片的格式,输出流;
            ImageIo.write(img,"jpg",response.getOutputStream());
             ImageIO.write(img, "jpg", response.getOutputStream());
                           
 }

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

 以上一个简陋的验证码Servlet就编写好了,还可以加上干扰线,已经字体旋转等,可以去查一下JavaEE的API进行实现。打一遍只为自己熟悉。现在都是用点击图片以及拖拉拼图条进行验证了,这个基本快被淘汰了。希望自己以后如果有机会从事这个行业再去学习!!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值