검증 코드의 기능 : 일반적으로 시스템을 로그인하거나 시스템을 등록 할 때 사용자 동작을 컴퓨터 프로그램 동작과 구별하기 위해 검증 코드를 입력해야합니다. 목적은 악의적 인 등록, 무차별 대전 암호 균열 등을 방지하는 것입니다.
검증 코드 구현에 대한 아이디어 : 서버를 사용하여 숫자와 문자를 무작위로 생성하는 기능을 실현하여 그림을 형성하고 JSP 페이지를 사용하여 확인 코드 및 사용자 입력 검증 코드를 표시 한 다음 서버 클래스를 사용하여 그림 및 사용자가 데이터 입력을 얻으려면 두 데이터가 일관됩니다.
코드 구현
1. 숫자와 영어로 무작위로 생성 된 서버 클래스를 작성하십시오. 소스 코드 :
패키지 com; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.image.bufferedimage; import java.io.bytearrayoutputstream; import java.io.ioexception; import java.io.printwriter; import javax.image.imageo.imageoio.imageoio.imageoio.image.image. javax.servlet.servletexception; import javax.servlet.servletoutputstream; import javax.servlet.http.httpservlet; import javax.servlet.http.httervletrequest; import javax.servlet.httpervletr renthing; import; javax.servlet.http.httpsession; public class logcheck는 httpservlet {public logcheck () {super (); } public void destroy () {super.destroy (); } public void doget (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {dopost (요청, 응답); }/*핵심 구현 코드*/public void dopost (httpservletrequest 요청, httpservletrepronse 응답) servletexception, ioexception {response.setContentType ( "image/jpeg"); httpsession session = request.getSession (); int 너비 = 60; int 높이 = 20; // 브라우저 가이 이미지 응답을 캐시하지 않도록 설정합니다 .SetHeader ( "Pragma", "No-Cache"); Response.SetHeader ( "Cache-Control", "No-Cache"); response.setDateHeader ( "만료", 0); // 메모리 이미지를 만들고 그래픽 컨텍스트를 가져옵니다. bufferedImage image = new bufferedImage (너비, 높이, bufferedImage.type_int_rgb); 그래픽 g = image.getGraphics (); /** 무작위 검증 코드 생성* 검증 코드를 정의하는 문자 테이블*/ String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char [] rands = 새로운 char [4]; for (int i = 0; i <4; i ++) {int rand = (int) (math.random () *36); rands [i] = chars.charat (rand); } /** 이미지 생성* 배경 그리기* / g.setColor (새 색상 (0xDCDCDC)); G.FillRect (0, 0, 너비, 높이); /** 무작위로 120 간섭점*/ for (int i = 0; i <120; i ++) {int x = (int) (math.random ()* width); int y = (int) (math.random ()*높이); int red = (int) (math.random ()*255); int green = (int) (math.random ()*255); int blue = (int) (math.random ()*255); g.setColor (새 색상 (빨간색, 녹색, 파란색)); g.sudoval (x, y, 1, 0); } g.setColor (color.black); g.setfont (new font (null, font.italic | font.bold, 18)); // 다른 높이에서 검증 코드의 다른 문자 G.DrawString ( ""+rands [0], 1, 17); G.DrawString ( ""+rands [1], 16, 15); G.DrawString ( ""+rands [2], 31, 18); G.DrawString ( ""+rands [3], 46, 16); g.dispose (); // 이미지를 클라이언트에 붙여 넣습니다. servletoutputStream sos = response.getOutputStream (); BytearRayoutputStream Baos = 새로운 BytearRayoutputStream (); imageio.write (image, "jpeg", baos); 바이트 [] buffer = baos.tobytearray (); 응답 .setContentLength (buffer.length); sos.write (버퍼); baos.close (); sos.close (); session.setattribute ( "checkcode", 새 문자열 (rands)); } public void init ()가 servletexception {// 코드를 여기에 넣습니다}} 2. 검증 코드를 표시하는 데 사용되는 페이지 :
<%@ page language = "java"import = "java.util.*"pageEncoding = "utf-8"%> <%string path = request.getContextPath (); String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.get.gteRverport () <! "-// w3c // dtml 4.01 과도기 // en"> <html> <head> <base href = "<%= basepath%>"> <title> index </title> <meta http-equiv = "pragma"content = "no-cache"> http-equiv = "만료"content = "0"> <meta http-equiv = "keywords"content = "keyword1, keyword2, keyword3"> <meta http-equiv = "description"content = "this page">-<link rel = "stylesheet"type "text/css"href = styles.cs.cs. <body> <form action = "yanzheng"method = "post"> <input type = "text"name = "name"size = "5"maxlength = "4"> <a href = "index.jsp"> <img src = "logcheck"> </a> <br> <input type = "value ="</html> </html> </html> </html>
3. 입력 된 검증 코드가 올바른지 확인하는 데 사용됩니다.
패키지 com; import java.io.ioexception; import java.io.printwriter; import javax.jms.session; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.htttp.htttpletrequest; 가져 오기; javax.servlet.http.httpervletresponse; import javax.servlet.http.httpsession; import javax.servlet.http.httpsession; public class yanzheng은 httpservlet {public yanzheng () {super (); } public void destroy () {super.destroy (); } public void doget (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {dopost (요청, 응답); } /*핵심 코드* / public void dopost (httpservletrequest request, httpservletreponse 응답) servletexception, ioexception {string info = null; /*입력 값 가져 오기*/ 문자열 값 1 = request.getParameter ( "name"); /*이미지 값 가져 오기*/ httpsession session = request.getSession (); 문자열 value2 = (string) session.getAttribute ( "checkcode"); /*두 값을 비교 (문자는 사례에 민감하지 않습니다)*/ if (value2.equalsignorecase (value1)) {info = "villification code input coren"; } else {info = "확인 코드 입력 오류"; } system.out.println (정보); request.setAttribute ( "info", info); request.getRequestDisPatcher ( "/login.jsp"). FORMPER (요청, 응답); } public void init ()가 servletexception {// 코드를 여기에 넣습니다}}4. 입력 구조 인터페이스를 표시합니다 (입력 검증 코드가 올바른지 여부) :
<%@ page language = "java"import = "java.util.*"pageEncoding = "utf-8"%> <%string path = request.getContextPath (); String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.get.gteRverport () <! "-// w3c // dtml 4.01 Transitional // en"> <html> <head> <base href = "<%= basepath%>"> <title> my jsp 'login.jsp'시작 페이지 </title> <meta http-equiv = "pragma" "no-cache"> <meta http-http--requiv. content = "no-cache"> <meta http-equiv = "만료"content = "0"> <meta http-equiv = "keywords"content = "keyword1, keyword2, keyword3"> <meta http-equiv = "description ="이것은 내 페이지입니다 ">-<link rel ="text/css " href = "styles.css"> -> </head> <body> < %= requesttribute ( "info") %> </body> </html>
5. 프로젝트 구조 및 효과 스크린 샷 :
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.