java實(shí)現(xiàn)簡單的驗(yàn)證碼功能
最近要做一個網(wǎng)站,要求實(shí)現(xiàn)驗(yàn)證碼程序,經(jīng)過不斷調(diào)試,終于成功實(shí)現(xiàn)功能。
一、驗(yàn)證碼生成類
生成驗(yàn)證碼的話需要用到j(luò)ava的Graphics類庫,畫出一個驗(yàn)證碼 廢話不多說,直接上代碼
package verificationCode;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.awt.image.RenderedImage;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.HashMap;import java.util.Map;import java.util.Random;import javax.imageio.ImageIO;public class generateCode { private static int width = 150;// 定義圖片的width private static int height = 48;// 定義圖片的height private static int codeCount = 4;// 定義圖片上顯示驗(yàn)證碼的個數(shù) private static int xx = 25; private static int fontHeight = 42; private static int codeY = 42; private static char[] codeSequence = { ’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’ }; /** * 生成一個map集合 * code為生成的驗(yàn)證碼 * codePic為生成的驗(yàn)證碼BufferedImage對象 * @return */ public static Map<String,Object> generateCodeAndPic() { // 定義圖像buffer BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // Graphics2D gd = buffImg.createGraphics(); // Graphics2D gd = (Graphics2D) buffImg.getGraphics(); Graphics gd = buffImg.getGraphics(); // 創(chuàng)建一個隨機(jī)數(shù)生成器類 Random random = new Random(); // 將圖像填充為白色 gd.setColor(Color.WHITE); gd.fillRect(0, 0, width, height); // 創(chuàng)建字體,字體的大小應(yīng)該根據(jù)圖片的高度來定。 Font font = new Font('Fixedsys', Font.BOLD, fontHeight); // 設(shè)置字體。 gd.setFont(font); // 畫邊框。 gd.setColor(Color.BLACK); gd.drawRect(0, 0, width - 1, height - 1); gd.setFont(font); // 隨機(jī)產(chǎn)生40條干擾線,使圖象中的認(rèn)證碼不易被其它程序探測到。 int red = 0, green = 0, blue = 0; // randomCode用于保存隨機(jī)產(chǎn)生的驗(yàn)證碼,以便用戶登錄后進(jìn)行驗(yàn)證。 StringBuffer randomCode = new StringBuffer(); // 隨機(jī)產(chǎn)生codeCount數(shù)字的驗(yàn)證碼。 for (int i = 0; i < codeCount; i++) { // 得到隨機(jī)產(chǎn)生的驗(yàn)證碼數(shù)字。 String code = String.valueOf(codeSequence[random.nextInt(36)]); // 產(chǎn)生隨機(jī)的顏色分量來構(gòu)造顏色值,這樣輸出的每位數(shù)字的顏色值都將不同。 red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); // 用隨機(jī)產(chǎn)生的顏色將驗(yàn)證碼繪制到圖像中。 gd.setColor(new Color(red, green, blue)); gd.drawString(code, (i + 1) * xx, codeY); // 將產(chǎn)生的四個隨機(jī)數(shù)組合在一起。 randomCode.append(code); } for (int i = 0; i < 60; i++) { red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); // 用隨機(jī)產(chǎn)生的顏色將驗(yàn)證碼繪制到圖像中。 gd.setColor(new Color(red, green, blue)); int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(50); int yl = random.nextInt(50); gd.drawLine(x, y, x + xl, y + yl); } Map<String,Object> map =new HashMap<String,Object>(); //存放驗(yàn)證碼 map.put('code', randomCode); //存放生成的驗(yàn)證碼BufferedImage對象 map.put('codePic', buffImg); return map; } public static void main(String[] args) throws Exception { //創(chuàng)建文件輸出流對象 File file = new File('WebRoot/image/'+System.currentTimeMillis()+'.jpg'); FileOutputStream out = null; try { if (!file.exists()) { // 先得到文件的上級目錄,并創(chuàng)建上級目錄,在創(chuàng)建文件 file.getParentFile().mkdir(); file.createNewFile(); } out = new FileOutputStream(file); Map<String,Object> map = generateCode.generateCodeAndPic(); ImageIO.write((RenderedImage) map.get('codePic'), 'jpeg', out); System.out.println('驗(yàn)證碼的值為:'+map.get('code')); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
二、驗(yàn)證碼驗(yàn)證類
package verificationCode;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet('/checkCode')public class checkCode extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter('code'); response.setCharacterEncoding('utf-8');//保證格式正確 response.setContentType('text/html'); // 驗(yàn)證驗(yàn)證碼 String sessionCode = request.getSession().getAttribute('code').toString(); if (code != null && !''.equals(code) && sessionCode != null && !''.equals(sessionCode)) { if (code.equalsIgnoreCase(sessionCode)) { response.getWriter().println('驗(yàn)證通過!'); } else { response.getWriter().println('驗(yàn)證失敗!'); } } else { response.getWriter().println('驗(yàn)證失敗!'); } }}
三、驗(yàn)證碼傳輸類
用到doget方法
package verificationCode;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.awt.image.RenderedImage;import java.io.IOException;import java.util.HashMap;import java.util.Map;import java.util.Random;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 javax.servlet.http.HttpSession;import verificationCode.generateCode;/** * Servlet implementation class CodeServlet */@WebServlet('/getCode')public class CodeServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 調(diào)用工具類生成的驗(yàn)證碼和驗(yàn)證碼圖片 Map<String, Object> codeMap = generateCode.generateCodeAndPic(); // 將四位數(shù)字的驗(yàn)證碼保存到Session中。 HttpSession session = req.getSession(); session.setAttribute('code', codeMap.get('code').toString()); // 禁止圖像緩存。 resp.setHeader('Pragma', 'no-cache'); resp.setHeader('Cache-Control', 'no-cache'); resp.setDateHeader('Expires', 0); resp.setContentType('image/jpeg'); // 將圖像輸出到Servlet輸出流中。 ServletOutputStream sos; try { sos = resp.getOutputStream(); ImageIO.write((RenderedImage) codeMap.get('codePic'), 'jpeg', sos); sos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
四、jsp驗(yàn)證demo
<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8'%><html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><title>驗(yàn)證碼頁面</title><script type='text/javascript' src='http://m.4tl426be.cn/bcjs/${pageContext.request.contextPath}/js/jquery.js'></script></head><body> <form action='${pageContext.request.contextPath}/checkCode' method='post'> 請輸入驗(yàn)證碼:<input type='text' name='code' /> <div id=random> <img alt='驗(yàn)證碼' src='http://m.4tl426be.cn/bcjs/${pageContext.request.contextPath}/getCode'> </div><button type='button'>改變內(nèi)容</button><br/> <input type='submit' value='提交' /> </form></body><script type='text/javascript'> $(function() { //response.getWriter().println('驗(yàn)證失敗!'); }); $('#b01').click( function changeImg() { $('#random').html('<img id=’imgObj’ alt=’驗(yàn)證碼’ src=’${pageContext.request.contextPath}/getCode’>') var imgSrc = $('#imgObj'); var src = imgSrc.attr('src'); imgSrc.attr('src', chgUrl(src)); }); // 時間戳 // 為了使每次生成圖片不一致,即不讓瀏覽器讀緩存,所以需要加上時間戳 function chgUrl(url) { var timestamp = (new Date()).valueOf(); url = url.substring(0, 20); if ((url.indexOf('&') >= 0)) { url = url + '×tamp=' + timestamp; } else { url = url + '?timestamp=' + timestamp; } return url; }</script></html>
總結(jié)
雖然只是一個小小的demo,但是實(shí)際上用到了許多知識,比如生成驗(yàn)證碼的畫圖,傳輸驗(yàn)證碼doget,驗(yàn)證驗(yàn)證碼的dopost和ajax動態(tài)更換驗(yàn)證碼,麻雀雖小五臟俱全啊。
參考網(wǎng)址: Java實(shí)現(xiàn)驗(yàn)證碼的產(chǎn)生和驗(yàn)證
更多關(guān)于java驗(yàn)證碼的精彩文章請點(diǎn)擊專題: java驗(yàn)證碼大全 進(jìn)行參考
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python利用os模塊編寫文件復(fù)制功能——copy()函數(shù)用法2. php測試程序運(yùn)行速度和頁面執(zhí)行速度的代碼3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. 三個不常見的 HTML5 實(shí)用新特性簡介5. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁6. ajax請求添加自定義header參數(shù)代碼7. Python使用jupyter notebook查看ipynb文件過程解析8. 解決Python 進(jìn)程池Pool中一些坑9. 解決python腳本中error: unrecognized arguments: True錯誤10. IntelliJ IDEA創(chuàng)建普通的Java 項(xiàng)目及創(chuàng)建 Java 文件并運(yùn)行的教程
