前言
很多新手對圖片驗證碼不是很了解,所以本文嘗試通過一個簡單的 JSP 小程序來實現驗證碼功能。文中給出了詳細的示例代碼,文末給出了完整實例代碼的下載地址,下面話不多說了,來一起看看詳細的介紹吧。
效果圖
示例代碼
前臺代碼如下:
<form action="action.jsp/5844.html">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);// 加載圖片 %>
返回圖片的數據流。
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);// 在內存中創建圖像 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();// 隨機產生干擾線 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 = ""; // 隨機產生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);// 調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成 } // 將認證碼存入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()); /* * 加上下面代碼,運行時才不會出現java.lang.IllegalStateException: getOutputStream() has already been called ..........等異常 * response.getOutputStream().flush(); * response.getOutputStream().close(); * response.flushBuffer(); */ // JSP內置對象out和response.getWrite()的區別,兩者的主要區別:1. 這兩個對象的類型是完全不同的…… // response.getWriter(); // http://blog.sina.com.cn/s/blog_7217e4320101l8gq.html // http://www.companysz.com/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("沒提供驗證碼參數"); } else { isCaptchaPass = rand.equals(code); if (!isCaptchaPass) throw new IllegalAccessError("驗證碼不正確"); } return isCaptchaPass; } %>
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答