This article simply wrote a Java verification code, for the previously written SPRINGMVC registration function plus Verification code, the role of verification code is not much to say, to prevent the bot malicious registration and so on.
Where User.java, with the password and Code properties, password persisted to the database, the Code property uses @transient annotations to keep it from being persisted to the database.
Adding these two attributes to the User.java, the user's construction method is modified to public user (string ID, Date regtime, string username,string password) without code.
PrivateString password; @Column (Name= "Password", nullable=false, length=20) PublicString GetPassword () {returnpassword; } Public voidSetPassword (String password) { This. Password =password; } PrivateString Code; @Transient//attributes that do not need to be persisted to db use this annotation PublicString GetCode () {returnCode; } Public voidSetcode (String code) { This. Code =Code; }
The following is the controller generated by the CAPTCHA, and most of the code is written in comments.
Codecontroller.java
PackageCom.sgl.controller;ImportJava.awt.Color;ImportJava.awt.Font;ImportJava.awt.Graphics;ImportJava.awt.image.BufferedImage;Importjava.io.IOException;ImportJava.util.Random;ImportJavax.imageio.ImageIO;ImportJavax.servlet.ServletOutputStream;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping; @Controller Public classCodecontroller {Private intwidth = 90;//define the width of the picture Private intheight = 20;//defines the height of a picture Private intCodecount = 4;//define the number of verification codes displayed on the image Private intxx = 15; Private intFontheight = 18; Private intCodey = 16; Char[] codesequence = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ' }; @RequestMapping ("/code") Public voidGetCode (httpservletrequest req, HttpServletResponse resp)throwsIOException {//defining the image bufferBufferedImage buffimg =Newbufferedimage (width, height, bufferedimage.type_int_rgb);//graphics2d gd = Buffimg.creategraphics (); //graphics2d gd = (graphics2d) buffimg.getgraphics ();Graphics GD =Buffimg.getgraphics (); //Create a random number generator classRandom random =NewRandom (); //fill the image with whiteGd.setcolor (Color.White); Gd.fillrect (0, 0, width, height); //To create a font, the size of the font should depend on the height of the image. Font font =NewFont ("Fixedsys", Font.Bold, fontheight); //sets the font. Gd.setfont (font); //draw a border. Gd.setcolor (Color.Black); Gd.drawrect (0, 0, width-1, height-1); //randomly generates 40 lines of interference so that the authentication code in the image is not easily detected by other programs. Gd.setcolor (Color.Black); for(inti = 0; I < 40; i++) { intx =random.nextint (width); inty =random.nextint (height); intXL = Random.nextint (12); intYL = Random.nextint (12); Gd.drawline (x, y, x+ XL, Y +yl); } //The Randomcode is used to save randomly generated verification codes so that users can log in and authenticate. StringBuffer Randomcode =NewStringBuffer (); intRed = 0, green = 0, blue = 0; //random generation of Codecount number verification code. for(inti = 0; i < Codecount; i++) { //get a randomly generated captcha number. String code = string.valueof (Codesequence[random.nextint (36)]); //generates a random color component to construct a color value so that the output will have a different color value for each digit. Red = Random.nextint (255); Green= Random.nextint (255); Blue= Random.nextint (255); //draws the verification code into the image with a randomly generated color. Gd.setcolor (NewColor (red, green, blue)); Gd.drawstring (Code, (I+ 1) *xx, Codey); //The resulting four random numbers are grouped together. randomcode.append (code); } //Save the four-digit verification code to the session. HttpSession session =req.getsession (); System.out.print (Randomcode); Session.setattribute ("Code", randomcode.tostring ()); //suppresses image caching. Resp.setheader ("Pragma", "No-cache"); Resp.setheader ("Cache-control", "No-cache"); Resp.setdateheader ("Expires", 0); Resp.setcontenttype ("Image/jpeg"); //output the image to the servlet output stream. Servletoutputstream SOS =Resp.getoutputstream (); Imageio.write (buffimg,"JPEG", SOS); Sos.close (); }}
Overwrite the registration code in Usercontroller.java
Modify the Add method in Usercontroller.java to the following.
@RequestMapping ("/user") PublicModelandview AddUser (User user,httpsession session) {Modelandview Mav=NewModelandview (); if(! (User.getcode (). Equalsignorecase (Session.getattribute ("code"). ToString ()))) {//Ignore verification code casingMav.setviewname ("Error"); Mav.addobject ("MSG", "Incorrect Captcha"); returnMav; }Else{User.setid (Uuid.randomuuid (). toString ()); User.setregtime (NewDate ()); Try{userservice.adduser (user); //request.setattribute ("user", user);Mav.setviewname ("Success"); Mav.addobject ("User", user); Mav.addobject ("MSG", "registered successfully, can go to the landing"); returnMav; } Catch(Exception e) {mav.setviewname ("Menu"); Mav.addobject ("User",NULL); Mav.addobject ("MSG", "Registration failed"); returnMav; } } }
And then you modify the foreground page.
Modify the form of the registered index.jsp
<form action= "user.html" method= "POST" > <table width= "207" border= "0" align= "center" > <tr> <TD colspan= "2" align= "center" nowrap= "nowrap" > User registration </td> </tr> <tr> < TD width= "nowrap=" nowrap "> User name </td> <td width=" 127 "nowrap=" nowrap "><label> &L T;input name= "username" type= "text" id= "username" size= "/>" </label></td> </tr> <tr> <td nowrap= "nowrap" > Password </td> <td nowrap= "nowrap" ><input name= "PASSW Ord "type=" password "id=" password "size=" maxlength= "ten"/></td> </tr> <tr><td> Verification Code </td><td><input id= "Index_code" name= "code" type= "text"/></td> <td> <a href=" # "onclick=" changeimg () "> Change </a></td></tr> <tr> <TD colspan= "2" align= "center" nowrap= "nowrap" ><label> <input type= "Submit" value= "register"/> <input type= "reset" value= "refill"/> </label></td> </tr> </table> </form>
Note the label SRC, written in code.html.
Where JavaScript is used to implement the "Change one" function
<script type= "Text/javascript" >function changeimg () {var imgsrc= $ ("#imgObj"); var src= Imgsrc.attr ("src"); Imgsrc.attr ("SRC", Chgurl (SRC)); } //time Stamp//in order to make the picture inconsistent each time, that is, do not let the browser read cache, so you need to add a timestampfunction Chgurl (URL) {var timestamp= (NewDate ()). ValueOf (); URL= url.substring (0, 17); if((Url.indexof ("&") >= 0) ) {URL= URL + "xtamp=" +timestamp; } Else{URL= URL + "? timestamp=" +timestamp; } returnURL; }</script>
Among them, this paragraph JS used to jquery, do not forget in the head of the jquery JS to introduce.
<script type= "Text/javascript" src= "Js/jquery-easyui-1.3.1/jquery-1.8.0.min.js" ></script>
At this end, a complete registration process is complete. deployment, testing,
The registration was successful as follows
Verification code input error, as follows
And then it's an error.
This registration function is basically perfect, of course, in fact, the hint of error should be in the original registration page, you can use Ajax to achieve, I just write a sample program, I did not do that. The pursuit of the perfect can reconstruct the controller's code, return JSON to the browser, and then use AJAX implementation does not refresh the page, you can realize the real registration function.
Https://code.csdn.net/Sgl731524380/verificationcode/tree/master
Springmvc+java Verification Code Perfect registration function