Spring框架生成圖片驗證碼實例。本站提示廣大學習愛好者:(Spring框架生成圖片驗證碼實例)文章只能為提供參考,不一定能成為您想要的結果。以下是Spring框架生成圖片驗證碼實例正文
這篇文章會早年台頁面到後台完成完全的講授,上面隨著小編一路來看看。
1、前台的代碼,image.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>獲得圖片驗證碼</title> <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-1.10.2.min.js"></script> </head> <body> <form action="##" method='post'> <input type="hidden" id="userId" name="userId" value=""> <div class="form-group"> <div class="email controls"> <input type="text" name='loginName' id="loginName" placeholder="用戶名" value="" class='form-control'/> </div> </div> <div class="form-group"> <div class="pw controls"> <input type="password" autocomplete="off" id="pwd" name="pwd" placeholder="暗碼" class='form-control'/> </div> </div> <div class="form-group"> <div class="email controls"> <input id="validateCode" onblur="checkImg(this.value)" name="validateCode" type="text" class="form-control" placeholder="輸出驗證碼"/> </div> <span class="y_yzimg"><img id="codeValidateImg" onClick="javascript:flushValidateCode();"/></span> <p class="y_change"><a href="javascript:flushValidateCode();" >換一張</a></p> </div> <div class="form-group"> <span class="text-danger"></span> </div> <div class="submit"> <div class="remember"> <input type="checkbox" name="remember" value="1" class='icheck-me' data-skin="square" data-color="blue" id="remember"> <label for="remember">記住我</label> </div> <input type="button" value="登錄" onclick="javascript:submitForm();" class='btn btn-primary'> </div> </form> <script type="text/javascript"> $(document).ready(function() { flushValidateCode();//進入頁面就刷重生成驗證碼 }); /* 刷重生成驗證碼 */ function flushValidateCode(){ var validateImgObject = document.getElementById("codeValidateImg"); validateImgObject.src = "${pageContext.request.contextPath }/getSysManageLoginCode?time=" + new Date(); } /*校驗驗證碼輸出能否准確*/ function checkImg(code){ var url = "${pageContext.request.contextPath}/checkimagecode"; $.get(url,{"validateCode":code},function(data){ if(data=="ok"){ alert("ok!") }else{ alert("error!") flushValidateCode(); } }) } </script> </body> </html>
2、後台代碼ImageGenController.java
package com.dufyun.springmvc.web.controller; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.dufy.javaweb.test.RandomValidateCode; @Controller public class ImageGenController { @RequestMapping(value="/toImg") public String toImg(){ return "image/image"; } //登錄獲得驗證碼 @RequestMapping("/getSysManageLoginCode") @ResponseBody public String getSysManageLoginCode(HttpServletResponse response, HttpServletRequest request) { 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 = "/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.equals(code)){ return "ok"; } return "error"; //這裡我沒有停止字母年夜小隱約的驗證處置,感興致的你可以去試一下! } }
3、生成驗證碼的對象類RandomValidateCode.java
package com.dufy.javaweb.test; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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(); } } } }
4、總結
本文的內容到這就停止了,假如對外面的處所有不懂的處所,可以留言評論辯論。願望本文的內容對年夜家的進修任務能有所贊助。