이 기사는 프론트 데스크 페이지에서 후면 책상까지 완전히 설명됩니다. 아래를 살펴 보겠습니다.
1. 전경 코드, image.jsp
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/tr/html4/loose.dtd"> html> html> http-quiv ="content-type "content ="text/html; charset = utf-8 "> </title verification code </title> <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 = "value ="> <div> <div> <div> <div> <div> <div> <div>. name='loginName' id="loginName" placeholder="username" value="" class='form-control'/> </div> </div> <div> <input type="password" autocomplete="off" id="pwd" name="pwd" placeholder="password" class='form-control'/> </div> </div> <div> <input id = "validatecode"onblur = "Checkimg (this.value)"name = "validatecode"type = "text"placeholder = "verification code enth verification code"/> </div> <span> <img id = "codevalidateimg"onclick = "javascript : flushvalidatecode ();"/> <p> <a. href = "JavaScript : FlushValidateCode ();" > one </a> </p> </div> <div> <span> </span> </div> <div> <div> <입력 유형 = "checkbox"name = "remember"value = "1"class = 'Icheck-me'data-skin = "square"data-color = "blue"id = "remember"> </div </label " onclick = "javaScript : submitorform ();" class = 'btn btn-primary'> </div> </form> <script type = "text/javaScript"> $ (document) .ready (function () {flushvalidatecode (); // 검증 코드를 새로 고침하고 생성});/* flushvalideTecode (var vastion valideTecode () {var vasygebob valigate valideTecode () {var vasygeb validecode = {var vastion valideTecode (); document.getElementById ( "codeValidateImg"); validAmgoBject.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
패키지 com.dufyun.springmvc.web.controller; import javax.servlet.http.cookie; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletrespons; import org.springframephamework.stereotty.controller; org.springframework.util.stringutils; import org.springframework.web.bind.annotation.requestmapping; import org.sprameframework.bind.annotation.responsebody; import com.dufy.javaweb.test.randomvalidatecode; @requestmapping (value = "/toimg") public String toimg () {return "image/image"; } // 검증 코드를 가져 오기 위해 로그인 @requestmapping ( "/getsysmanagelogincode") @ResponseBody Public String getSysmanageLogincode (httpservletResponse 응답, httpservletrequest request) {responion.setcontentType ( "image/jpeg"); Response.SetHeader ( "Pragma", "No-Cache"); // 응답 헤더 정보를 설정하여 브라우저 에이 컨텐츠 응답을 캐시하지 말라고 지시합니다 .Setheader ( "Cache-Control", "No-Cache"); Response.SetHeader ( "set-cookie", "name = value; httponly"); // xs 공격을 방지하기 위해 httponly 속성을 설정합니다. randomvalidatecode randomvalidatecode = new randomvalidatecode (); {randomvalidatecode.getRandcode (요청, 응답, "imageCode"); // output image method} catch (예외 e) {e.printstacktrace (); } 반품 ""; } // 확인 코드 verification @requestMapping (value = "/CheckimageCode") @ResponseBody public string checkTcode (httpservletRequest request, httpservletResponse 응답) {String validecode = request.getParameter ( "validateCode"); 문자열 코드 = null; // 1 : 쿠키 쿠키에서 확인 코드 정보를 가져옵니다 [] 쿠키 = request.getCookies (); for (쿠키 쿠키 : 쿠키) {if ( "imageCode".Equals (cookie.getName ())) {code = cookie.getValue (); 부서지다; }} // 1 : 세션 확인 코드의 정보를 가져옵니다. // String Code1 = (string) request.getSession (). getAttRibute ( ""); // 2 : (! stringUtils.isempty (validateCode) && validAteCode.equals (code)) {return "ok"; } "오류"를 반환합니다. // 여기서 문자 크기 퍼지 처리의 검증을 수행하지 않았습니다. 관심이 있으시면 시도해 볼 수 있습니다! }}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; javax.servlet.http.cookie; import javax.servlet.http.httpervletrequest; import javax.servlet.http.httpservletresponse; public class randomvalidatecode {private random = new random (); 개인 문자열 randstring = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 무작위로 생성 된 문자열 private int width = 80; // 그림 너비 개인 int 높이 = 26; // 그림 높이 개인 int lineize = 40; // interferfern int stringnum = 4; 무작위로 생성 된 문자/**/ privity getfont*/ private getfont* font font font*/ private getfont (// font ( "고정식", font.center_baseline, 18); } /** get color* / 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); 새로운 색을 반환합니다 (R, G, B); } /** Draw String* / private String drawString (그래픽 g, String RandomString, int i) {g.setfont (getfont ()); g.setColor (new color (random.nextint (101), random.nextint (111), random .nextint (121)); 문자열 rand = string.valueof (getRandomString (random.nextInt (randstring.length ())); RandomString += rand; g.translate (random.nextint (3), random.nextint (3)); G.DrawString (rand, 13 * i, 16); 랜덤 스트링을 반환; } /** 간섭 선을 그립니다* / private void drawline (그래픽 g) {int x = random.nextint (width); int y = random.nextInt (높이); 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 요청, httpservletreponse 응답, 문자열 키) {// bufferedImage 클래스는 버퍼가있는 이미지 클래스이며 이미지 정보 버퍼링 이미지를 설명하는 데 사용되는 클래스입니다. 그래픽 g = image.getGraphics (); // 이미지 객체의 그래픽 객체 생성. 객체 G.fillRect (0, 0, 너비, 높이)를 수정하여 이미지에서 다양한 드로잉 작업을 수행 할 수 있습니다. g.setfont (New Font ( "Times New Roman", font.roman_baseline, 18)); G. 세트 콜러 (getrandcolor (110, 133)); // (int i = 0; i <= lineize; i ++) {drawline (g); } // 임의 문자열을 그립니다. String RandomString = ""; for (int i = 1; i <= stringnum; i ++) {randomstring = drawString (g, randomstring, i); } // 1 : 무작위로 생성 된 검증 코드를 쿠키 쿠키 쿠키에 넣습니다. 응답 .addcookie (쿠키); // 2 : 무작위로 생성 된 검증 코드를 세션 string sessionId = requestSession (). getId ()에 넣습니다. request.getSession (). setAttribute (sessionId+key, randomString); System.out.println ( "************" + RandomString); // 요약 : 두 방법 모두 양호합니다. // (1) : 쿠키를 사용하여 검증 코드를 프론트 브라우저로 보내 안전하지 않습니다! 사용하는 것이 권장되지 않습니다. // (2) : 세션 방법을 사용하면 검증 코드가 브라우저로 전송되지 않는 문제를 해결할 수 있지만 사용자 수가 너무 커지면 스토리지 방법이 서버에 압력을 가하고 서버의 성능에 영향을 미칩니다. 사용하는 것이 권장되지 않습니다. //이 방법은 여기에서 일시적으로 구현됩니다. 가장 좋은 방법은 생성 된 검증 코드를 프로젝트에 사용 된 캐시에 저장하고 무효화 시간을 설정하는 것입니다. 이는 보안을 달성 할뿐만 아니라 서버의 압력을 줄일 수 있습니다. g.dispose (); try {bytearrayoutputStream tmp = new BytearRayoutputStream (); imageio.write (image, "png", tmp); tmp.close (); 정수 contentlength = tmp.size (); response.setheader ( "Content-Length", ContentLength + ""); response.getoutputStream (). 쓰기 (tmp.tobytearRay ()); // 흐름에서 클라이언트에 메모리의 이미지를 출력} catch (예외 e) {e.printstacktrace (); } 마침내 {try {response.getOutputStream (). flush (); response.getOutputStream (). Close (); } catch (예외 e2) {e2.printstacktrace (); }}}} 4. 요약
이 기사의 내용은 여기서 끝납니다. 내부의 내용을 이해하지 못하면 메시지를 남겨두고 논의 할 수 있습니다. 이 기사의 내용이 모든 사람의 연구와 작업에 도움이되기를 바랍니다.