1 public class VerifyCodeController { 2 3 private int width = 90;//定義圖片的width 4 private int height = 20;//定義圖片的height 5 private int codeCount = 4;//定義圖片上顯示驗證碼的個數 6 private int xx = 15; 7 private int fontHeight = 18; 8 private int codeY = 16; 9 char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 10 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 11 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; 12 13 @RequestMapping("/getVerifyCode") 14 public void getVerifyCode(HttpServletRequest req, HttpServletResponse resp) 15 throws IOException { 16 // 定義圖像buffer 17 BufferedImage buffImg = new BufferedImage(width, height, 18 BufferedImage.TYPE_INT_RGB); 19 // Graphics2D gd = buffImg.createGraphics(); 20 //Graphics2D gd = (Graphics2D) buffImg.getGraphics(); 21 Graphics gd = buffImg.getGraphics(); 22 // 創建一個隨機數生成器類 23 Random random = new Random(); 24 // 將圖像填充為白色 25 gd.setColor(Color.WHITE); 26 gd.fillRect(0, 0, width, height); 27 28 // 創建字體,字體的大小應該根據圖片的高度來定。 29 Font font = new Font("Fixedsys", Font.BOLD, fontHeight); 30 // 設置字體。 31 gd.setFont(font); 32 33 // 畫邊框。 34 gd.setColor(Color.BLACK); 35 gd.drawRect(0, 0, width - 1, height - 1); 36 37 // 隨機產生40條干擾線,使圖象中的認證碼不易被其它程序探測到。 38 gd.setColor(Color.BLACK); 39 for (int i = 0; i < 40; i++) { 40 int x = random.nextInt(width); 41 int y = random.nextInt(height); 42 int xl = random.nextInt(12); 43 int yl = random.nextInt(12); 44 gd.drawLine(x, y, x + xl, y + yl); 45 } 46 47 // randomCode用於保存隨機產生的驗證碼,以便用戶登錄后進行驗證。 48 StringBuffer randomCode = new StringBuffer(); 49 int red = 0, green = 0, blue = 0; 50 51 // 隨機產生codeCount數字的驗證碼。 52 for (int i = 0; i < codeCount; i++) { 53 // 得到隨機產生的驗證碼數字。 54 String code = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]); 55 // 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色值都將不同。 56 red = random.nextInt(255); 57 green = random.nextInt(255); 58 blue = random.nextInt(255); 59 60 // 用隨機產生的顏色將驗證碼繪制到圖像中。 61 gd.setColor(new Color(red, green, blue)); 62 gd.drawString(code, (i + 1) * xx, codeY); 63 64 // 將產生的四個隨機數組合在一起。 65 randomCode.append(code); 66 } 67 // 將四位數字的驗證碼保存到Session中。 68 HttpSession session = req.getSession(); 69 System.out.print(randomCode); 70 session.setAttribute("verifycode", randomCode.toString()); 71 72 // 禁止圖像緩存。 73 resp.setHeader("Pragma", "no-cache"); 74 resp.setHeader("Cache-Control", "no-cache"); 75 resp.setDateHeader("Expires", 0); 76 77 resp.setContentType("image/jpeg"); 78 79 // 將圖像輸出到Servlet輸出流中。 80 ServletOutputStream sos = resp.getOutputStream(); 81 ImageIO.write(buffImg, "jpeg", sos); 82 sos.close(); 83 84 }