JSP實用教程之簡易圖片驗證碼的實現(xiàn)方法(附源碼)
前言
很多新手對圖片驗證碼不是很了解,所以本文嘗試通過一個簡單的 JSP 小程序來實現(xiàn)驗證碼功能。文中給出了詳細的示例代碼,文末給出了完整實例代碼的下載地址,下面話不多說了,來一起看看詳細的介紹吧。
效果圖
示例代碼
前臺代碼如下:
<form action="action.jsp" method="POST"> <label> 用戶名: <input type="text" name="name" data-singleTips="請輸入用戶名" value="admin" /> </label> <label> 密碼: <input type="password" name="password" /> </label> <!-- 驗證碼 --> <label class="captchaCode"> 驗證碼: <img src="img.jsp" style="cursor: pointer;" onclick="this.src=this.src + '?' + new Date().valueOf();" /> <input type="text" name="captchaImgCode" /> </label> <div> <input type="submit" value="登錄" /> </div> </form>
驗證碼圖片從何而來? img.jsp 是也:
<%@include file="captcha.jsp"%> <% init(pageContext);// 加載圖片 %>
返回圖片的數(shù)據(jù)流。
action.jsp 這里不作用戶名或密碼的檢驗,只是單純驗證碼檢驗。
如果輸入驗證碼通過,顯示如下:
反之,給出已捕獲的異常:
action.jsp 就是調用 captcha.jsp 里面的 isPass(pageContext, captchaImgCode)
方法,以及捕獲已知異常。
<%@page pageEncoding="UTF-8"%> <%@include file="captcha.jsp"%> <% String captchaImgCode = request.getParameter("captchaImgCode"); try { if (isPass(pageContext, captchaImgCode)) { out.println("驗證碼通過!"); } } catch (Throwable e) { out.println(e); } %>
核心 captcha,jsp 代碼:
<%@page pageEncoding="UTF-8" import="java.io.IOException, java.awt.*, java.awt.image.BufferedImage, java.util.Random, javax.imageio.ImageIO"%> <%! // 定義Captcha 類 public static class Captcha { /** * 默認寬度 60 */ private int width = 60; /** * 默認高度 20 */ private int height = 20; /** * 驗證碼 */ private String code; /** * 生成驗證碼圖片 * * @return 圖片對象 */ public BufferedImage get() { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 在內(nèi)存中創(chuàng)建圖像 Graphics g; g = image.getGraphics(); // 獲取圖形上下文 g.setColor(getRandColor(200, 250)); // 設定背景 g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); // 設定字體 g.setColor(getRandColor(160, 200)); Random random = new Random();// 隨機產(chǎn)生干擾線 for (int i = 0; i < 155; i++) { int x = random.nextInt(width), y = random.nextInt(height); int xl = random.nextInt(12), yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } String sRand = ""; // 隨機產(chǎn)生4位驗證碼 for (int i = 0; i < 4; i++) { String rand = String.valueOf(random.nextInt(10)); sRand += rand; g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110))); // 將認證碼顯示到圖象中 g.drawString(rand, 13 * i + 6, 16);// 調用函數(shù)出來的顏色相同,可能是因為種子太接近,所以只能直接生成 } // 將認證碼存入SESSION // session.setAttribute("rand", sRand); setCode(sRand); g.dispose();// 圖象生效 return image; } /** * 生成隨機顏色 * * @param fc * @param bc * @return */ private Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; Random random = new Random(); int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * 獲取高度 * * @return */ public int getHeight() { return height; } /** * 設置高度 * * @param height * 高度 */ public void setHeight(int height) { this.height = height; } /** * 獲取驗證碼 * * @return */ public String getCode() { return code; } /** * 設置驗證碼 * * @param code * 驗證碼 */ public void setCode(String code) { this.code = code; } /** * 獲取寬度 * * @return */ public int getWidth() { return width; } /** * 設置寬度 * * @param width * 寬度 */ public void setWidth(int width) { this.width = width; } } /** * SESSION 的鍵值 */ public static final String SESSION_KEY = "rand"; /** * 顯示驗證碼圖片并將認證碼存入 Session * * @param response * 響應對象 * @param session * 會話對象 */ public static void init(HttpServletResponse response, HttpSession session) { Captcha img = new Captcha(); // 不用緩存 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpg"); try { ImageIO.write(img.get(), "JPEG", response.getOutputStream()); /* * 加上下面代碼,運行時才不會出現(xiàn)java.lang.IllegalStateException: getOutputStream() has already been called ..........等異常 * response.getOutputStream().flush(); * response.getOutputStream().close(); * response.flushBuffer(); */ // JSP內(nèi)置對象out和response.getWrite()的區(qū)別,兩者的主要區(qū)別:1. 這兩個對象的類型是完全不同的…… // response.getWriter(); // http://blog.sina.com.cn/s/blog_7217e4320101l8gq.html // http://www.dbjr.com.cn/kf/201109/103284.html // pageContext.getOut().clear(); } catch (IOException e) { e.printStackTrace(); } session.setAttribute(SESSION_KEY, img.getCode()); // 將認證碼存入 SESSION System.out.println("生成驗證碼:" + img.getCode()); } /** * 顯示驗證碼圖片并將認證碼存入 Session(For JSP) * * @param pageContext * 頁面上下文對象 */ public static void init(PageContext pageContext) { init((HttpServletResponse) pageContext.getResponse(), pageContext.getSession()); } /** * 判斷用戶輸入的驗證碼是否通過 * * @param pageContext * 頁面上下文對象 * @return true 表示通過 * @throws Throwable */ public static boolean isPass(PageContext pageContext, String code) throws Throwable { boolean isCaptchaPass = false; String rand = (String) pageContext.getSession().getAttribute(SESSION_KEY); System.out.println("rand:" + rand); System.out.println("CaptchaCode:" + code); if (rand == null) throw new UnsupportedOperationException("請刷新驗證碼。"); else if (code == null || code.equals("")) { throw new IllegalArgumentException("沒提供驗證碼參數(shù)"); } else { isCaptchaPass = rand.equals(code); if (!isCaptchaPass) throw new IllegalAccessError("驗證碼不正確"); } return isCaptchaPass; } %>
完整代碼下載:http://xiazai.jb51.net/201707/yuanma/Captcha(jb51.net).rar
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
JSP application(return String)用法詳例
JSP中application(return String)用法詳例,需要用的朋友可以參考下代碼。2009-10-10JSP輸出HTML時產(chǎn)生的大量空格和換行的去除方法
在WEB應用中,如果使用jsp作為view層的顯示模板,都會被空格/空換行問題所困擾.2009-10-10基于javaweb+jsp實現(xiàn)企業(yè)車輛管理系統(tǒng)
這篇文章主要為大家詳細介紹了javaweb+jsp實現(xiàn)企業(yè)車輛管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11struts2中一個表單中提交多個請求的例子(多個提交按鈕)
在很多Web應用中,為了完成不同的工作,一個HTML form標簽中可能有兩個或多個submit按鈕,Struts2中提供了另外一種方法,使得無需要配置可以在同一個action類中執(zhí)行不同的方法(默認執(zhí)行的是execute方法)2014-04-04