A dynamic random verification code can be generated in just a few steps, with the final effect such as:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/74/D9/wKioL1YscJvQIeqDAAF7uMWlQBA873.jpg "title=" Cheetah 20151025140145.png "alt=" Wkiol1yscjvqieqdaaf7umwlqba873.jpg "/>
One front desk Display page login.jsp
Where the verification code is shown is a picture, the link is to generate a code for the servlet, and click on the picture after the changeimg () to trigger the JS function, so that it dynamically generate a new verification code, the function of the parameter t=math.random () does not participate in the generation of verification code, Its function simply means that each commit is not the same request, need to be processed separately, the complete login.jsp code is as follows:
<%@ page language= "java" contenttype= "Text/html; charset=utf-8" pageencoding= "UTF-8"%><%string path = request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%><! doctype html public "-//w3c//dtd html 4.01 transitional//en" "HTTP// Www.w3.org/TR/html4/loose.dtd ">
Two modifications to Web. xml
Add a node with the following code:
<!--verification codes--<servlet> <servlet-name>drawValidateCode</servlet-name> <servlet-class> ;com.zifangsky.onlinefriend.servlet.member.handledrawvalidatecode</servlet-class> </servlet> < Servlet-mapping> <servlet-name>drawValidateCode</servlet-name> <url-pattern>/ Helpdrawvalidatecode</url-pattern> </servlet-mapping>
Three back-end servlet files Handledrawvalidatecode.java
This file is primarily responsible for processing the foreground request and returning the generated captcha image, while the random characters on the image are stored in the session for verification at login, Handledrawvalidatecode.java complete code is as follows:
package com.zifangsky.onlinefriend.servlet.member;import java.awt.color;import java.awt.font; Import java.awt.graphics;import java.awt.graphics2d;import java.awt.image.bufferedimage;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.servletconfig;import javax.servlet.servletexception;import javax.servlet.http.httpservlet;import javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;import javax.servlet.http.httpsession;/** * generate random images for verification code * */public class handledrawvalidatecode extends httpservlet{private static final long serialversionuid = 1l;private static final int width = 120; //Picture Width private static final int height = 30; //Picture height public void init (servletconfig config) Throws servletexception{super.init (config);} Public void dopost (Httpservletrequest request,httpservletresponse response) throws servletexception,ioexception{request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8") ); Httpsession session = request.getsession (TRUE);//Create a picture bufferedimage bufferedimage = new bufferedimage (WIDTH,&NBSP;HEIGHT,&NBSP;BUFFEREDIMAGE.TYPE_INT_RGB);//Get Picture Graphics graphics = bufferedimage.getgraphics ();//Set Picture background color setbackground (graphics);//Set Picture border Setbordor (graphics);// Draw the line of interference in the picture, with 4 colors, a total of 20 lines Drawrandomline (graphics,color.green);d rawrandomline (Graphics,new color (246,255,145) );d Rawrandomline (Graphics,new color (225,174,252));d Rawrandomline (Graphics,new color (120,202,254));// Write random characters on the picture and record the generated sequence String randomtext = drawrandomtext ((graphics2d) graphics);// Save the generated characters in session session.setattribute ("Checkcode", randomtext);//Set the response header to notify the browser to open res as a picturePonse.setcontenttype ("Image/jpeg");//Set Response header control browser do not cache Response.setdateheader ("Expries", -1); Response.setheader ("Cache-control", "No-cache"); Response.setheader ("Pragma", "No-cache");// Write the picture to the browser imageio.write (bufferedimage, "JPG", response.getoutputstream ());} /** * Set Picture background color * */private void setbackground (graphics graphics) { Graphics.setcolor (Color.White); Graphics.fillrect (0, 0, width, height);} /** * Set picture Border * */private void setbordor (graphics graphics) { Graphics.setcolor (Color.Blue); Graphics.drawrect (1, 1, width - 2, height - 2 );} /** * on the picture to draw the * */private void drawrandomline (Graphics graphics,color color) {graphics.setcolor (color);//Set the number of lines and draw a line for (int i = 0;i < 5;i++) { Int x1 = new random (). Nextint (WIDTH); Int x2 = new random (). nextInT (WIDTH); Int y1 = new random (). Nextint (HEIGHT); Int y2 = new random (). Nextint (HEIGHT); Graphics.drawline (X1, y1, x2, y2);}} /** * write random characters on a picture, combination of numbers and letters * @param length length of string * * @return Returns the generated string sequence * */private string drawrandomtext (graphics2d graphics) { Graphics.setcolor (color.red); Graphics.setfont (New font ("Arial", font.bold, 20));//combination of numbers and letters string baseNumLetter = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ"; Stringbuffer sbuffer = new stringbuffer (); Int x = 5; //rotation origin x coordinates string ch = ""; Random random = new random (); for (int i = 0;i < 4;i++) {// Set font rotation angle int degree = random.nextint () % 30; //angle is less than 30 degrees int dot = random.nextint (Basenumletter.length ()); Ch = basenumletteR.charat (dot) + ""; sbuffer.append (ch);//forward rotation graphics.rotate (degree * math.pi / &NBSP;180,&NBSP;X,&NBSP;20); graphics.drawstring (ch, x, 20);//Reverse Rotation graphics.rotate (-degree * &NBSP;MATH.PI&NBSP;/&NBSP;180,&NBSP;X,&NBSP;20); x += 30;} Return sbuffer.tostring ();} Public void doget (Httpservletrequest request,httpservletresponse response) throws servletexception,ioexception{dopost (Request, response);}}
Note:
Here, the interference line color and number can be set by itself, the color can use random color, while the display of each text can also use a random color, can increase the verification code identification difficulty, of course, here I will be more easily confused 0 and O and I have been removed. If you use encoded Chinese characters, it is also possible to generate a code
Four login.jsp page submits the form, the background servlet file Handlelogin.java verifies the verification code, and carries on the login verification
After the three steps above, Login.jsp should be able to correctly display the verification code, while clicking on the verification code picture will generate a new verification code, login.jsp submit the form after the Handlelogin.java file verification Verification code is mainly: the input verification code in the lowercase letters to uppercase, and the verification code generated when saved in the Sessi On the string comparison, if the same, it means that the input is correct, while removing the values set in the session, to prevent duplicate submissions, blasting passwords , Handlelogin.java related code is as follows:
package com.zifangsky.onlinefriend.servlet.member;import java.io.ioexception;import java.sql.connection;import java.sql.preparedstatement;import java.sql.resultset;import java.sql.sqlexception;import javax.servlet.requestdispatcher;import javax.servlet.servletconfig; import javax.servlet.servletexception;import javax.servlet.http.httpservlet;import javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;import javax.servlet.http.httpsession;import com.zifangsky.onlinefriend.model.member.login;import com.zifangsky.onlinefriend.util.dbconn;import com.zifangsky.onlinefriend.util.stringutil;public class handlelogin extends httpservlet{private string backnews = ""; //Login Status return information Public void init (servletconfig config) throws servletexception{ Super.init (config);} Public void dopost (httpservletrequest reQuest,httpservletresponse response) throws servletexception,ioexception{ Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); Httpsession session = request.getsession (TRUE);//Get the Verification code string validatecode = Stringutil.xssencode (Request.getparameter ("Validatecode"). Trim ());object checkcode = Session.getattribute ("Checkcode");//Convert the lowercase letters in the input verification code to uppercase, and then the string comparison if the code is saved in session when the CAPTCHA is generated (checkcode != null && checkcode.equals (stringutil.converttocapitalstring (Validatecode))) { Session.removeattribute ("Checkcode"); Continuedopost (request,response);} Else{response.sendredirect ("login.jsp"); return;}} Private void continuedopost (Httpservletrequest request, httpservletresponse response) throws servletexception,ioexception{//here the login follow-up operation omitted}public void doget (HttpServletRequest request,httpservletresponse response) throws servletexception,ioexception{doPost (request, response);}}
Note 1: The stringutil used above is a string-related method class that I wrote, the Method converttocapitalstring () is used to convert lowercase letters in a string to uppercase letters, with the following code:
/** * converts lowercase letters in a string to uppercase letters * * */public static String Converttocapitalstring (STRING&NBSP;SRC) { char[] array = src.tochararray (); int temp = 0; for ( int i = 0; i < array.length; i++) { temp = (int) array[i]; if (temp <= 122 && temp >= 97) { // Array[i] is a lowercase letter array[i] = (char) (TEMP&NBSP;-&NBSP;32); } } return string.valueof (Array); }
Note 2: Where the method Xssencode () is to encode the input string to avoid an XSS cross-site scripting attack, using the stringescapeutils in Commons-lang-2.4.jar, the code is as follows (PS: Of course there is no need here, can be omitted):
/** * String XSS filtering, JavaScript filtering, SQL filtering * * @param str Incoming String * * @return escaped String * */public static strings Xssencode (String St R) {String s = stringescapeutils.escapehtml (str);//s = Stringescapeutils.escapejavascript (s);//s = Stringescapeutils.escapesql (s); return s;}
This article is from the "Zifangsky" blog, make sure to keep this source http://983836259.blog.51cto.com/7311475/1706029
Dynamically generate random verification code in JSP, background check verification code at login, and how to avoid repeated submission of blasting password by the same verification code