Java笔记-java web实现验证码
生活随笔
收集整理的這篇文章主要介紹了
Java笔记-java web实现验证码
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
原理其實(shí)就是用java將隨機(jī)生成的數(shù)字。
畫到畫板上。
把這幾個字符,增強(qiáng),斜體啥的。
最后增加干擾線即可。
?
程序運(yùn)行截圖如下:
輸入錯誤后:
輸入正確就可以進(jìn)行跳轉(zhuǎn)了
?
關(guān)鍵代碼如下:
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//1. 創(chuàng)建畫板BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//2. 創(chuàng)建畫板Graphics2D pen = img.createGraphics();//3. 生成隨機(jī)內(nèi)容String code = randCode(4);request.getSession().setAttribute("valiCode", code);//4. 繪制內(nèi)容// 4.1 設(shè)置繪制區(qū)域pen.fillRect(0, 0, width, height);// 4.2 設(shè)置字體pen.setFont(new Font("微軟雅黑", Font.BOLD, fontsize + random.nextInt(5)));// 4.3 按順序逐個繪制字符for(int i = 0; i < code.length(); i++){pen.setColor(randColor());pen.drawString(code.charAt(i) + "", 5 + i * fontsize, (fontsize + height) / 2 + random.nextInt(5));}// 4.4 繪制噪音線for(int i = 0; i < 3; i++){pen.setColor(randColor());pen.setStroke(new BasicStroke(3));pen.drawLine(random.nextInt(width / 2), random.nextInt(height), random.nextInt(width), random.nextInt(height));}//5.保存圖片并發(fā)送ServletOutputStream out = response.getOutputStream();ImageIO.write(img, "png", out);out.flush();out.close();}源碼打包下載地址:
https://github.com/fengfanchen/Java/tree/master/vailSampleDemo
?
總結(jié)
以上是生活随笔為你收集整理的Java笔记-java web实现验证码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++设计模式-代理模式
- 下一篇: 系统架构师学习笔记-基于构件的开发