這篇文章會從前臺頁面到后臺實現完整的講解,下面跟著小編一起來看看。
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;@Controllerpublic 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、總結
本文的內容到這就結束了,如果對里面的地方有不懂的地方,可以留言討論。希望本文的內容對大家的學習工作能有所幫助。
新聞熱點
疑難解答