驗證碼校驗共三步
1.創建驗證碼
2.發送驗證碼
3.驗證碼校驗
創建生成驗證碼的工具類
public class RandomValidateCode { private Random random = new Random(); private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";// 隨機產生的字符串 private int width = 80;// 圖片寬 private int height = 26;// 圖片高 private int lineSize = 40;// 干擾線數量 private int stringNum = 4;// 隨機產生字符數量 /* * 獲得字體 */ private Font getFont() { return new Font("Fixedsys", Font.CENTER_BASELINE, 18); } /* * 獲得顏色 */ private Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc - 16); int g = fc + random.nextInt(bc - fc - 14); int b = fc + random.nextInt(bc - fc - 18); return new Color(r, g, b); } /* * 繪制字符串 */ private String drowString(Graphics g, String randomString, int i) { g.setFont(getFont()); g.setColor(new Color(random.nextInt(101), random.nextInt(111), random .nextInt(121))); String rand = String.valueOf(getRandomString(random.nextInt(randString .length()))); randomString += rand; g.translate(random.nextInt(3), random.nextInt(3)); g.drawString(rand, 13 * i, 16); return randomString; } /* * 繪制干擾線 */ private void drowLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(13); int yl = random.nextInt(15); g.drawLine(x, y, x + xl, y + yl); } /* * 獲取隨機的字符 */ public String getRandomString(int num) { return String.valueOf(randString.charAt(num)); } /** * 生成隨機圖片 */ public void getRandcode(HttpServletRequest request,HttpServletResponse response,String key) { // BufferedImage類是具有緩沖區的Image類,Image類是用於描述圖像信息的類 BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// 產生Image對象的Graphics對象,改對象可以在圖像上進行各種繪制操作 g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18)); g.setColor(getRandColor(110, 133)); // // 繪制干擾線 // for (int i = 0; i <= lineSize; i++) { // drowLine(g); // } // 繪制隨機字符 String randomString = ""; for (int i = 1; i <= stringNum; i++) { randomString = drowString(g, randomString, i); } //1:將隨機生成的驗證碼放入Cookie中 Cookie cookie = new Cookie(key,randomString); response.addCookie(cookie); //2:將隨機生成的驗證碼放入session中 String sessionid = request.getSession().getId(); request.getSession().setAttribute(sessionid+key, randomString); System.out.println("*************" + randomString); //總結:這兩種方式都不是很好, //(1):使用cookie的方式,將驗證碼發送到前台瀏覽器,不安全!不建議使用。 //(2):使用session的方式,雖然能解決驗證碼不發送到瀏覽器,安全性較高了,但是如果用戶量太大,這樣的存儲方式會對服務器造成壓力,影響服務器的性能。不建議使用。 //這里暫時實現用這種方式,好的辦法是,在項目中使用的緩存,將生成的驗證碼存放到緩存中,設置失效時間,這樣既可以實現安全性也能減輕服務器的壓力。 g.dispose(); try { ByteArrayOutputStream tmp = new ByteArrayOutputStream(); ImageIO.write(image, "png", tmp); tmp.close(); Integer contentLength = tmp.size(); response.setHeader("content-length", contentLength + ""); response.getOutputStream().write(tmp.toByteArray());// 將內存中的圖片通過流動形式輸出到客戶端 } catch (Exception e) { e.printStackTrace(); }finally{ try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e2) { e2.printStackTrace(); } } } }
發送驗證碼
// 獲取驗證碼 @RequestMapping("/login/getSysManageLoginCode") @ResponseBody public String getSysManageLoginCode(HttpServletResponse response, HttpServletRequest request) { System.out.println("獲取驗證碼"); response.setContentType("image/jpeg");// 設置相應類型,告訴瀏覽器輸出的內容為圖片 response.setHeader("Pragma", "No-cache");// 設置響應頭信息,告訴瀏覽器不要緩存此內容 response.setHeader("Cache-Control", "no-cache"); response.setHeader("Set-Cookie", "name=value; HttpOnly");//設置HttpOnly屬性,防止Xss攻擊 response.setDateHeader("Expire", 0); RandomValidateCode randomValidateCode = new RandomValidateCode(); try { randomValidateCode.getRandcode(request, response,"imagecode");// 輸出圖片方法 } catch (Exception e) { e.printStackTrace(); } return ""; }
驗證碼校驗
//驗證碼驗證 @RequestMapping(value = "/login/checkImageCode") @ResponseBody public String checkTcode(HttpServletRequest request,HttpServletResponse response) { String validateCode = request.getParameter("validateCode"); String code = null; //1:獲取cookie里面的驗證碼信息 Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if ("imagecode".equals(cookie.getName())) { code = cookie.getValue(); break; } } //1:獲取session驗證碼的信息 //String code1 = (String) request.getSession().getAttribute(""); //2:判斷驗證碼是否正確 if(!StringUtils.isEmpty(validateCode)){ // 全部轉化為小寫 validateCode = validateCode.toLowerCase(); code = code.toLowerCase(); if(validateCode.equals(code)) { return "ok"; } } return "error"; }