이 기사에서는 SpringMVC 구현 검증 코드 기능 표시에 대한 특정 코드를 공유합니다. 특정 내용은 다음과 같습니다
먼저 렌더링을 살펴 보겠습니다.
아이디어 :
우선, 검증 코드는 그림, 임의의 문자, 숫자, 패턴 등으로 구성된 그림 이므로이 그림은 확실히 고정되어 있지 않으므로 백엔드에 의해 무작위로 작성되어야합니다. 프론트 엔드는 IG의 SRC를 사용 하여이 제조 방법에 지속적으로 액세스합니다.
1 단계 : 프론트 엔드 페이지 쓰기
로그인은 AJAX 메소드를 사용하므로 클릭 이벤트를 호출하는 데 사용됩니다. 검증 코드의 이미지는 A 태그에 배치되어 검증 코드를 클릭하고 변경할 수 있습니다. IMG의 SRC 속성을 사용하여 이미지가 표시됩니다. SpringMVC를 사용하고 있으므로 배경 방법은 작업을 사용하도록 요청됩니다.
<form> <div id = "login_tip"> 관리자 로그인 </div> <div> <input type = "text"id = "user_code"name = "user_code"placeholder = "sejefter intract"> </div> <div> <input type = "password"id = "user_account"name = "user_account"placeholder = "place" id = "btn_area"> <input type = "text"id = "verificationCode"name = "verificationCode"placeHolder = "verification code를 입력하십시오"> <a href = "javaScript : void (0); rel = "external nofollow"onclick = "verificationcode ()"> <img id = "randcodeimage"src = "verificationCode/Generate.action"/> </a> </a> </a> </a> </a div> <div style = "float;"> <input type = "button"= "id ="id = "sub_btn"gogin () "dogin" "dogin () id = "verification_code"> <b> </b> </div> </form>
2 단계 : JS 코드를 작성하십시오
로그인은 AJXA를 사용하므로 백엔드 로그인은 일부 데이터를 확인하고 잘못된 경우 데이터를 로그인 페이지로 반환합니다. 여기서 검증 코드를 생성하기 위해 메소드를 호출 한 후 임의의 숫자를 추가 해야하는 이유를 설명합니다. 여기서 임의의 숫자 와이 임의 숫자의 매개 변수 이름은 마음대로 작성 될 수 있으며 백엔드는 작업을 수행하지 않습니다. 이 방법은 동일한 메소드를 호출 할 때 브라우저가 캐시되지 않도록하는 메소드이며 이미지 또는 검증 코드 입력을 클릭하면 오류가 자동으로 새로 고침되지 않으며 이미지가 변경됩니다.
<script type = "text/javaScript"> function login () {// $ .ajax ({type : 'post', url : 'uase/query.action', // data : $ ( '#loginInputform'). serialize (), data : { 'user_code': $ ( "#user_code"). : $ ( "#user_account"). val (), 'verificationCode': $ ( "#verificationCode"). val (),}, 'json', success : function (obj) {var rad.random () * math.pow (10, 8)); window.href = 'uase/login.action'; "verificationCode/Generate.action? uuuy ="+rad); val ( ""). } / ***검증 코드 새로 고침* / function verificationcode () {var rad = math.floor (math.random ()*math.pow (10, 8)); // uuuy는 랜덤 매개 변수 이름으로 백엔드로 처리되지 않습니다. 그 목적은 캐시 된 링크 $ ( "#randcodeimage")를 읽는 브라우저를 피하는 것입니다 ( "src", "verificationcode/generate.action? uuuy ="+rad); } </스크립트>3 단계 : 백그라운드 컨트롤러 제어 클래스를 작성하십시오
주요 메소드는 일부 임의의 숫자 생산 방법과 일부 보조 클래스를 사용하는 VerificationCode입니다. 당신은 그들 모두를 사용할 수 있습니다. 유형을 변경할 수있는 검증 코드를 사용했기 때문에 직접 작성한 공개 도구 클래스를 사용했습니다.
@requestmapping ( "/verificationCode") 공개 클래스 verificationCodeController는 httpservlet {private static final long serialversionuid = 1L; / *** 세션을 저장하는 데 사용되는 이름/ 개인 정적 최종 문자열 세션 _key_roand_code = "randcode"; // 상수를 통일하기 위해 할 일/ ** * */ private static final int count = 200; / ** * 그래픽 크기 (너비) */ private static final int width = 105; / ** * 그래픽 크기 (높이) */ 개인 정적 최종 int 높이 = 35; / ***간섭 줄의 길이 = 1.414*linewidth*/ private static final int linewidth = 1; @requestMapping (value = "/generate", method = {requestMethod.post, requestMethod.get}) public void void void request (httpservletrequest request, httpservletreponse 응답) servletexception, ioexception {// 페이지를 캐시 응답 ( "pragma", "no-cache")으로 설정합니다. Response.SetHeader ( "Cache-Control", "No-Cache"); response.setDateHeader ( "만료", 0); // response.setContentType ( "image/png"); // 메모리에서 이미지 생성 최종 BufferedImage Image = New BufferedImage (너비, 높이, BufferedImage.type_int_rgb); // 그래픽 컨텍스트 최종 그래픽 2D 그래픽 = (Graphics2d) image.getGraphics (); // 배경색 그래픽을 설정합니다. // --- 1.color.white는 흰색 그래픽입니다 .FillRect (0, 0, 너비, 높이); // 회절 채우기 // 테두리 색상 설정 // Graphics.setColor (getRandColor (100, 200)); // --- 2. 이것은 숫자 유형으로 색상을 설정하는 것입니다. 색상 모드는 빨간색, 녹색 및 파란색의 세 가지 기본 색상을 사용합니다. 다른 색상은 세 가지 색상 조정을 통해 얻습니다. 이 세 가지 기본 색상의 값은 0 ~ 255 Graphics.DrawRect (0, 0, 너비 -1, 높이 -1)입니다. 최종 랜덤 = 새로운 랜덤 (); // 무작위로 간섭 줄을 생성하여 이미지의 인증 코드를 다른 프로그램에서는 다른 프로그램에서 쉽게 감지 할 수 없습니다 (int i = 0; i <count; i ++) {Graphics.setColor (getRandColor (150, 200)); // --- 3. 최종 int x = random.nextInt (너비 -LINWIDTH -1) + 1; // 경계 내에서 그려지는지 확인하십시오 int y = random.nextInt (높이 -LINEWIDTH -1) + 1; 최종 int xl = random.nextint (linewidth); 최종 int yl = random.nextint (linewidth); Graphics.Drawline (x, y, x + xl, y + yl); } // 무작위로 생성 된 인증 코드 (4 자리 번호) 최종 문자열 resultCode = ExcTracTrandCode ()를 취합니다. for (int i = 0; i <resultCode.length (); i ++) {// 이미지에 인증 코드를 표시하고 호출 함수의 색상이 동일합니다. 씨앗이 너무 가까워서 // graphics.setColor 만 직접 생성 할 수 있습니다 (새 색상 (20 + random.nextInt (130), 20 + random // .nextInt (130), 20 + random.nextInt (130)); // 글꼴 색상 그래픽 설정 .SetColor (Color.Black); // font style set //graphics.setfont(new font ( "arial black", font.italic, 18); Graphics.setFont (New Font ( "Times New Roman", font.bold, 24)); // 문자, 문자 간격, 상단 여백 시스템 .out.print (resultCode.charat (i)); Graphics.DrawString (String.Valueof (resultCode.Charat (i)), (23 * i) + 8, 26); } system.out.println ( "직접 출력 :"+resultCode); // 인증 코드를 세션 request.getSession ()에 저장합니다. // 이미지가 적용됩니다. 그래픽 .dispose (); // 이미지를 페이지로 출력했습니다 imageio.write (image, "jpeg", response.getOutputStream ()); } / *** @return random code* / private string exctrandCode () {Final String randCodetype = resourceutil.getRandcodetype (); int randcodelength = integer.parseint (resourceutil.getrandcodelength ()); if (randcodetype == null) {return randcodeimageenum.number_char.generatest (randcodelength); } else {switch (randcodetype.charat (0)) {case '1': return randcodeimageenum.number_char.generatest (randcodelength); CASE '2': randcodeimageenum.lower_char.generatest (randcodelength); CASE '3': randcodeimageenum.upper_char.generatest (randcodelength); CASE '4': randcodeimageenum.letter_char.generatest (randcodelength); CASE '5': randcodeimageenum.all_char.generatest (randcodelength); CASE '5': randcodeimageenum.all_char.generatest (randcodelength); 기본값 : randcodeimageenum.number_char.generatest (randcodelength); }}}} /*** 설명 : 주어진 숫자에 따라 다른 색상을 생성합니다* @param 이것은 숫자 유형으로 색상을 설정하는 것입니다. 색상 모드는 빨간색, 녹색 및 파란색의 세 가지 기본 색상을 사용합니다. 이 세 가지 기본 색상의 값은 세 가지 색상 조정을 통해 0 ~ 255입니다. 이 세 가지 기본 색상의 값은 0 ~ 255입니다. * @param 이것은 숫자 유형으로 색상을 설정하는 것입니다. 색상 모드는 빨간색, 녹색 및 파란색의 세 가지 기본 색상을 사용합니다. 이 세 가지 기본 색상의 값은 세 가지 색상의 조정에 의해 얻어집니다. 0 ~ 255입니다. * @return 설명 : 반환 색상*/ 개인 색상 getRandColor (int fc, int bc) {// 주어진 임의의 색상 범위 최종 임의 임의 임의 = new Random (); if (fc> 255) {fc = 255; } if (bc> 255) {bc = 255; } 최종 int r = fc + random.nextInt (bc -fc); 최종 int g = fc + random.nextint (bc -fc); 최종 int b = fc + random.nextint (bc -fc); 새로운 색을 반환합니다 (R, G, B); } / *** 검증 코드 보조 클래스* / enum randcodeimageenum { / *** 혼합 문자열* / all_char ( "0123456789ABCDEFGHIJKMNPQRSTUVWXYZABCDEFGHGGHIJKLMNOPRSTUVWXYZ"), // Distourane L을 제거합니다. / ** * 문자 */ letter_char ( "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"),/ ** * 소문자 */ lower_char ( "abcdefghijklmnopqrstuvwxyz"),/ ** */ 번호 */ 번호 */ 번호 */ 번호 ** */ 번호 ** */ 번호 */ ** /*** 대문자 ( "abcdefghijklmnopqrstuvwxyz"); / *** 생성 될 문자열*/ 개인 문자열 charstr; / ** * @param charstr */ private randcodeimageenum (Final String charstr) {this.charstr = charstr; } / *** 생산 랜덤 검증 코드** @param codelength* 검증 코드 길이* @return verification code* / public string generatest (최종 int codelength) {Final StringBuffer sb = new StringBuffer (); 최종 랜덤 = 새로운 랜덤 (); 최종 문자열 sourcestre = getCharstr (); for (int i = 0; i <codelength; i ++) {sb.append (soursestr.charat (random.nextint (soursestr.length ())); } return sb.toString (); } / ** * @return {@link #charstr} * / public string getCharstr () {return charstr; }}}4 단계 : 일반적인 도구 클래스를 작성하십시오
/*** 프로젝트 매개 변수 도구 클래스**/public class resourceutil {private static final resourcebundle bundle = java.util.resourcebundle.getBundle ( "sysconfig"); / *** 임의의 코드 길이를 가져옵니다** @renger and rength code*/ public static string getRandcodelength () {return bundle.getString ( "randcodelength"); } / *** 임의의 코드 유형을 가져옵니다** @Return 랜덤 코드 유형* / public static string getRandCodeType () {return bundle.getString ( "randCodeType"); }}5 단계 : config.properties
randcodelength = 4RandCodeType = 5
6 단계 : 여기서 완료되면 효과를 시도 할 수 있습니다.