Java Web制作登錄驗(yàn)證碼實(shí)現(xiàn)代碼解析
圖例如下
具體操作如下:
新建一個(gè)servlet,代碼如下:標(biāo)記一個(gè)WebServlet,
1 @WebServlet(urlPatterns = {'/checkCode'}) //驗(yàn)證碼Servlet
繪制驗(yàn)證碼圖片的核心代碼:
int width = 100; int height = 50; //創(chuàng)建圖片對(duì)象 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //美化圖片 Graphics g = image.getGraphics(); //1:填充背景 g.setColor(Color.pink); g.fillRect(0, 0, width, height); //畫(huà)邊框 g.setColor(Color.blue); g.drawRect(0, 0, width - 1, height - 1); //生成一個(gè)驗(yàn)證碼字符串 String strCheckCode = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; Random random = new Random(); StrCheckCode = ''; for (int i = 1; i <= 4; i++) { int index = random.nextInt(strCheckCode.length()); char ch = strCheckCode.charAt(index); StrCheckCode += ch;//拼接驗(yàn)證碼 g.drawString(ch + '', width / 5 * i, height / 2); } //畫(huà)干擾線 for (int i = 0; i < 5; i++) { int x1 = random.nextInt(width); int x2 = random.nextInt(width); int y1 = random.nextInt(height); int y2 = random.nextInt(height); g.drawLine(x1, x2, y1, y2); } //輸出,顯示出來(lái) ImageIO.write(image, 'jpg', resp.getOutputStream()); }
首先是new一個(gè)BufferedImage,然后給定長(zhǎng)和寬,之后是指邊框和背景色,接著使用隨機(jī)數(shù)生成4個(gè)字符繪制在圖片上,接著使用DrawLine繪隨機(jī)制干擾線,
然后在前端頁(yè)面引入圖片,然后給圖片綁定點(diǎn)擊事件,點(diǎn)擊后重新訪問(wèn)servlet即可:
//點(diǎn)擊驗(yàn)證碼圖片,重新生成新驗(yàn)證 $(function () { $('#imgCheckCode').click(function () {var img = document.getElementById('imgCheckCode');var date = new Date();img.src = 'http://localhost:8080/blogs_war_exploded/checkCode?op=setCheckCode&a=' + date; }) })
<div class='inputCheckCode'> <div class='inputCheckCodeLeftIco'>➤</div> <div class='inputCheckCodeRightInput'><input type='text' name='checkCode' placeholder='驗(yàn)證碼' autocomplete='off'/> </div> <img src='http://localhost:8080/blogs_war_exploded/checkCode?op=setCheckCode' id='imgCheckCode'> </div>
最后輸出即可,效果如下:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車3. ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖4. .net如何優(yōu)雅的使用EFCore實(shí)例詳解5. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)6. python 爬取京東指定商品評(píng)論并進(jìn)行情感分析7. python基礎(chǔ)之匿名函數(shù)詳解8. Python獲取B站粉絲數(shù)的示例代碼9. ajax動(dòng)態(tài)加載json數(shù)據(jù)并詳細(xì)解析10. 通過(guò)CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫(huà)特效
