Spring框架生成圖片驗(yàn)證碼實(shí)例
這篇文章會(huì)從前臺(tái)頁(yè)面到后臺(tái)實(shí)現(xiàn)完整的講解,下面跟著小編一起來(lái)看看。
1、前臺(tái)的代碼,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>獲取圖片驗(yàn)證碼</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="用戶(hù)名" 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="輸入驗(yàn)證碼"/> </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();//進(jìn)入頁(yè)面就刷新生成驗(yàn)證碼 }); /* 刷新生成驗(yàn)證碼 */ function flushValidateCode(){ var validateImgObject = document.getElementById("codeValidateImg"); validateImgObject.src = "${pageContext.request.contextPath }/getSysManageLoginCode?time=" + new Date(); } /*校驗(yàn)驗(yàn)證碼輸入是否正確*/ 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、后臺(tái)代碼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"; } //登錄獲取驗(yàn)證碼 @RequestMapping("/getSysManageLoginCode") @ResponseBody public String getSysManageLoginCode(HttpServletResponse response, HttpServletRequest request) { response.setContentType("image/jpeg");// 設(shè)置相應(yīng)類(lèi)型,告訴瀏覽器輸出的內(nèi)容為圖片 response.setHeader("Pragma", "No-cache");// 設(shè)置響應(yīng)頭信息,告訴瀏覽器不要緩存此內(nèi)容 response.setHeader("Cache-Control", "no-cache"); response.setHeader("Set-Cookie", "name=value; HttpOnly");//設(shè)置HttpOnly屬性,防止Xss攻擊 response.setDateHeader("Expire", 0); RandomValidateCode randomValidateCode = new RandomValidateCode(); try { randomValidateCode.getRandcode(request, response,"imagecode");// 輸出圖片方法 } catch (Exception e) { e.printStackTrace(); } return ""; } //驗(yàn)證碼驗(yàn)證 @RequestMapping(value = "/checkimagecode") @ResponseBody public String checkTcode(HttpServletRequest request,HttpServletResponse response) { String validateCode = request.getParameter("validateCode"); String code = null; //1:獲取cookie里面的驗(yàn)證碼信息 Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if ("imagecode".equals(cookie.getName())) { code = cookie.getValue(); break; } } //1:獲取session驗(yàn)證碼的信息 //String code1 = (String) request.getSession().getAttribute(""); //2:判斷驗(yàn)證碼是否正確 if(!StringUtils.isEmpty(validateCode) && validateCode.equals(code)){ return "ok"; } return "error"; //這里我沒(méi)有進(jìn)行字母大小模糊的驗(yàn)證處理,感興趣的你可以去試一下! } }
3、生成驗(yàn)證碼的工具類(lèi)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";// 隨機(jī)產(chǎn)生的字符串 private int width = 80;// 圖片寬 private int height = 26;// 圖片高 private int lineSize = 40;// 干擾線數(shù)量 private int stringNum = 4;// 隨機(jī)產(chǎn)生字符數(shù)量 /* * 獲得字體 */ 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); } /* * 獲取隨機(jī)的字符 */ public String getRandomString(int num) { return String.valueOf(randString.charAt(num)); } /** * 生成隨機(jī)圖片 */ public void getRandcode(HttpServletRequest request,HttpServletResponse response,String key) { // BufferedImage類(lèi)是具有緩沖區(qū)的Image類(lèi),Image類(lèi)是用于描述圖像信息的類(lèi) BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// 產(chǎn)生Image對(duì)象的Graphics對(duì)象,改對(duì)象可以在圖像上進(jìn)行各種繪制操作 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); } // 繪制隨機(jī)字符 String randomString = ""; for (int i = 1; i <= stringNum; i++) { randomString = drowString(g, randomString, i); } //1:將隨機(jī)生成的驗(yàn)證碼放入Cookie中 Cookie cookie = new Cookie(key,randomString); response.addCookie(cookie); //2:將隨機(jī)生成的驗(yàn)證碼放入session中 String sessionid = request.getSession().getId(); request.getSession().setAttribute(sessionid+key, randomString); System.out.println("*************" + randomString); //總結(jié):這兩種方式都是很好, //(1):使用cookie的方式,將驗(yàn)證碼發(fā)送到前臺(tái)瀏覽器,不安全!不建議使用。 //(2):使用session的方式,雖然能解決驗(yàn)證碼不發(fā)送到瀏覽器,安全性較高了,但是如果用戶(hù)量太大,這樣的存儲(chǔ)方式會(huì)對(duì)服務(wù)器造成壓力,影響服務(wù)器的性能。不建議使用。 //這里暫時(shí)實(shí)現(xiàn)用這種方式,好的辦法是,在項(xiàng)目中使用的緩存,將生成的驗(yàn)證碼存放到緩存中,設(shè)置失效時(shí)間,這樣既可以實(shí)現(xiàn)安全性也能減輕服務(wù)器的壓力。 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());// 將內(nèi)存中的圖片通過(guò)流動(dòng)形式輸出到客戶(hù)端 } catch (Exception e) { e.printStackTrace(); }finally{ try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e2) { e2.printStackTrace(); } } } }
4、總結(jié)
本文的內(nèi)容到這就結(jié)束了,如果對(duì)里面的地方有不懂的地方,可以留言討論。希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)工作能有所幫助。
- SpringBoot實(shí)現(xiàn)前端驗(yàn)證碼圖片生成和校驗(yàn)
- Spring Security OAuth2集成短信驗(yàn)證碼登錄以及第三方登錄
- Spring Boot 驗(yàn)證碼的生成和驗(yàn)證詳解
- Springboot實(shí)現(xiàn)阿里云通信短信服務(wù)有關(guān)短信驗(yàn)證碼的發(fā)送功能
- SpringBoot實(shí)現(xiàn)短信驗(yàn)證碼校驗(yàn)方法思路詳解
- 實(shí)例詳解Spring Boot實(shí)戰(zhàn)之Redis緩存登錄驗(yàn)證碼
- SpringBoot 集成Kaptcha實(shí)現(xiàn)驗(yàn)證碼功能實(shí)例詳解
- Spring MVC 中 短信驗(yàn)證碼功能的實(shí)現(xiàn)方法
- Spring Security Oauth2.0 實(shí)現(xiàn)短信驗(yàn)證碼登錄示例
- springboot實(shí)現(xiàn)郵箱驗(yàn)證碼功能
相關(guān)文章
Spring Boot支持Crontab任務(wù)改造的方法
這篇文章主要介紹了Spring Boot支持Crontab任務(wù)改造的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01Spring?session?redis?修改默認(rèn)的序列化方法(案例)
這篇文章主要介紹了Spring?session?redis?修改默認(rèn)的序列化方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04Sa-Token記住我模式實(shí)現(xiàn)七天免登錄
這篇文章主要為大家介紹了Sa-Token記住我模式實(shí)現(xiàn)七天免登錄示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07SpringBoot4.5.2 整合HikariCP 數(shù)據(jù)庫(kù)連接池操作
這篇文章主要介紹了SpringBoot4.5.2 整合HikariCP 數(shù)據(jù)庫(kù)連接池操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09Java實(shí)現(xiàn)定時(shí)器的4種方法超全總結(jié)
對(duì)于一些特殊的代碼是需要定時(shí)執(zhí)行的,下面來(lái)看看定時(shí)器該如何編寫(xiě)吧,下面這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)定時(shí)器的4種方法,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05