在一些類似於管理系統的項目中,我們在登錄時經常會用到圖片驗證碼。這里把我自己寫的一個小系統(后台是java語言)的驗證碼部分摘出來。
總體思路是后端有一個生成驗證碼圖片的接口,把驗證碼圖片寫入瀏覽器,前端頁面在img標簽里的src屬性里填寫后端生成驗證碼圖片的接口地址即可。
1、java部分-CaptchaController.java
我這里是把后端生成的驗證碼生成圖片返回給瀏覽器時,同時存入到了數據庫中,前端登錄時,后端根據前端輸入的驗證碼和數據庫中的驗證碼作對比,來判斷是否可以登錄。
package com.lin.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.lin.domain.Captcha; import com.lin.service.SysUserService; /** * 驗證碼-controller * @author libo */ @Controller @RequestMapping("/captcha") public class CaptchaController { @Autowired private SysUserService uService; /** * 隨機字符字典 */ private static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u' ,'v', 'w', 'x', 'y', 'z'}; /** * 隨機數 */ private static Random random = new Random(); /** * 獲取4位隨機數 * @return */ private static String getRandomString() { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < 4; i++) { buffer.append(CHARS[random.nextInt(CHARS.length)]); } return buffer.toString(); } /** * 獲取隨機數顏色 * @return */ private static Color getRandomColor() { return new Color(random.nextInt(255),random.nextInt(255), random.nextInt(255)); } /** * 返回某顏色的反色 * @param c * @return */ private static Color getReverseColor(Color c) { return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue()); } /** * 生成驗證碼 * @param request * @param response * @throws ServletException * @throws IOException */ @ResponseBody @RequestMapping(value="/getCaptcha.do", method=RequestMethod.GET) public void outputCaptcha(HttpServletRequest request, HttpServletResponse response, String rad) throws ServletException, IOException { // 設置頁面不緩存 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); String randomString = getRandomString(); //生成的驗證碼 Captcha c = new Captcha(); c.setCaptchaId(rad); c.setCaptcha(randomString.toUpperCase()); Integer id = uService.saveCaptcha(c);//保存驗證碼到數據庫中 if(id > 0){ //驗證碼保存成功 }else{ //驗證碼保存失敗 return; } int width = 100; //驗證碼圖像的寬度 int height = 34; //驗證碼圖像的高度 // 在內存中創建圖象 BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); for(int i=0; i<randomString.length(); i++){ Color color = getRandomColor(); Color reverse = getReverseColor(color); g.setColor(color); //設置字體顏色 g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 25)); //設置字體樣式 g.fillRect(0, 0, width, height); g.setColor(reverse); g.drawString(randomString, 18, 25); } //隨機生成一些點 for (int i = 0, n = random.nextInt(100); i < n; i++) { g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1); } // 隨機產生干擾線,使圖象中的認證碼不易被其它程序探測到 for (int i = 0; i < 10; i++) { g.setColor(getRandomColor()); final int x = random.nextInt(width-1); // 保證畫在邊框之內 final int y = random.nextInt(height-1); final int xl = random.nextInt(width); final int yl = random.nextInt(height); g.drawLine(x, y, x + xl, y + yl); } g.dispose(); //圖像生效 ImageIO.write(bi, "JPEG", response.getOutputStream()); //輸出圖片到頁面 } }
2、html部分-login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>后台管理系統登錄</title> <link rel="stylesheet" href="/common/css/index.css"> <script src="/scripts/apiConfig.js"></script> <script src="/lib/jquery/jquery.min.js"></script> <script src="/lib/aes/aes.min.js"></script> <script src="/common/js/utils.js"></script> </head> <body> <div class="layout"> <div class="top-name">后台管理系統 <span>Background Management System</span> </div> <div class="main"> <div class="item"> <label style="word-spacing: 10px;">郵 箱:</label> <input type="text" id="loginEmail" class="f-s-14" autocomplete="off" placeholder="請輸入郵箱"> <span class="err-tip" id="tipLEmail" ng-class="m-l-15"></span> </div> <div class="item"> <label style="word-spacing: 10px;">密 碼:</label> <input type="password" id="loginPwd" class="f-s-14" autocomplete="off" placeholder="請輸入密碼"> <span class="err-tip " id="tipLPwd" ng-class="m-l-15"></span> </div> <div class="item clearfix"> <label>驗證碼:</label> <input type="text" id="captcha" class="f-s-14" placeholder="請輸入驗證碼" style="width: 200px;"> <a href="javascript:void(0);" onclick="updateCaptcha()" style="height: 36px;width: 100px;float: right;"> <img src="" alt="" id="captcha_img"> </a> <span class="err-tip" id="tipCaptcha" ng-class="m-l-15"></span> </div> <div style="text-align: center;margin-top: -10px;height: 20px;margin-bottom: 5px;"> <span class="err-tip" id="error" ng-class="m-l-15" style="font-size: 14px;"></span> </div> <div class="item"> <button type="button" class="submit" id="submit" style="outline: none;">登 錄</button> </div> </div> </div> </body> <script> //更新驗證碼 var random = ''; function updateCaptcha() { random = new Date().getTime()+''+Math.floor(Math.random() * Math.pow(10, 8)); $('#captcha_img').attr('src', hostObj.host+'/captcha/getCaptcha.do?rad='+random); } $(function () { //頁面加載的時候就獲取驗證碼 updateCaptcha(); $('#loginEmail').blur(function () { checkLoginEmail(); }); $('#loginPwd').blur(function () { checkLoginPwd(); }); $('#captcha').blur(function () { checkCaptcha(); }); $("#submit").click(function() { var flag1 = checkLoginEmail(); var flag2 = checkLoginPwd(); var flag3 = checkCaptcha(); if(!flag1 || !flag2 || !flag3){ return; } $.ajax({ type:'post', url: hostObj.host+'/sysUser/login.do', dataType:"json", data:{ loginEmail:$("#loginEmail").val(), loginPwd:encrypt($("#loginPwd").val()), captcha: $('#captcha').val(), captchaId: random }, success:function(res) { if(res.success == 1){ var user = { id: res.data.id, email: res.data.email, createTime: res.data.createTime.substring(0,19), lastLoginTime: res.data.lastLoginTime.substring(0,19), status: res.data.status } window.location.href = "main.html"; }else{ $('#error').html(res.error.msg); if(res.error.code == 4000){ $('#captcha').focus(); } } }, error:function(res){ $('#error').html('系統錯誤!'); } }); }); function checkLoginEmail() { if($.trim($('#loginEmail').val()) == ''){ $('#tipLEmail').html('請輸入郵箱'); return false; }else{ $('#tipLEmail').html(''); return true; } } function checkLoginPwd() { if($.trim($('#loginPwd').val()) == ''){ $('#tipLPwd').html('請輸入登錄密碼'); return false; }else{ $('#tipLPwd').html(''); return true; } } function checkCaptcha() { if($.trim($('#captcha').val()) == ''){ $('#tipCaptcha').html('請輸入驗證碼'); return false; }else{ $('#tipCaptcha').html(''); return true; } }</script> </html>
3、效果
需要購買阿里雲產品和服務的,點擊此鏈接領取優惠券紅包,優惠購買哦,領取后一個月內有效: https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=fp9ccf07