實現網站驗證碼切換功能 一、樣例 樣例1、 樣例2、 二、實現原理 三、實現代碼 com.fry.servlet.VerifyCodeServlet verifyCode.html 要讓按鈕一直能點 ...
實現網站驗證碼切換功能
一、樣例
樣例1、
樣例2、
二、實現原理
三、實現代碼
com.fry.servlet.VerifyCodeServlet
1 package com.fry.servlet; 2 3 import javax.imageio.ImageIO; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.awt.*; 10 import java.awt.image.BufferedImage; 11 import java.io.IOException; 12 import java.util.Random; 13 14 /** 15 * Created by fry on 2017/5/31. 16 */ 17 @WebServlet(name = "VerifyCodeServlet", urlPatterns = "/code") 18 public class VerifyCodeServlet extends HttpServlet { 19 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 20 21 } 22 23 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 24 int width = 100; 25 int height = 30; 26 27 String data = "abcdefghijklmnopqrst01234567890"; 28 29 Random random = new Random(); 30 //1、用BufferedImage生成一張圖片,最後一個參數是圖片類型 31 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 32 33 //3、調用image的畫圖對象 34 Graphics graphics = image.getGraphics(); 35 graphics.setColor(Color.gray); 36 //左上角和右下角 37 graphics.fillRect(0, 0, width, height); 38 39 40 graphics.setColor(Color.black); 41 for (int i = 0; i < 4; i++) { 42 //4、隨機生成字元串,取到隨機的位置,就取到了隨機的字元串 43 int position = random.nextInt(data.length()); 44 String randomStr = data.substring(position, position + 1);//分割字元串 45 graphics.drawString(randomStr, width / 5 * (i + 1), 15);//畫字元串 46 47 } 48 49 //2、ImageIO的write()方法可以將圖片轉化為OutputStream類型 50 /** 51 * 第二個參數是要格式化的類型 52 * 最後一個參數是將格式化的圖片寫到response的輸出流中 53 */ 54 ImageIO.write(image, "jpg", response.getOutputStream()); 55 56 57 } 58 }
verifyCode.html
要讓按鈕一直能點
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 9 </body> 10 <center> 11 <h2>切換驗證碼</h2> 12 <!--js代碼--> 13 <script> 14 function changeImageCode() { 15 document.getElementById('btn').isDisabled=true; 16 <!-- 為了使每次的驗證碼都不一樣,防止頁面緩存,所以加上時間,ts是get方式請求傳過去的參數,每次的請求都不一樣,所以頁面沒法緩存--> 17 document.getElementById('identity').src='code?ts='+new Date().getTime(); 18 } 19 </script> 20 <!--從servlet的映射是code的servlet處獲取圖片--> 21 <image src="code" id="identity" onload="btn.disable=false;" style="cursor:pointer; vertical-align:middle"></image> 22 <input type="button" value="看不清,更換驗證碼" onclick="changeImageCode()" id="btn" style="vertical-align:middle"> 23 24 </center> 25 </html>