Springmvc+java Verification Code Perfect registration function

Source: Internet
Author: User

This article simply wrote a Java verification code, for the previously written SPRINGMVC registration function plus Verification code, the role of the verification code is not much to say, to prevent the bot malicious registration of something ...

See the previous article for the implementation of the Basic registration function maven build springmvc+spring+hibernate for user registration

Where I modified part of the Code of the Registration program, where User.java, with the password and Code properties, while persisting password to the database, the code attribute uses @transient annotations so that it is not 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.

private string password; @Column (name= "password", nullable=false,length=20) public string GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} private string code; @Transient   //properties that do not need to be persisted to db use the annotation public string GetCode () {return code;} public void Setcode (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

Package Com.sgl.controller;import Java.awt.color;import Java.awt.font;import java.awt.graphics;import Java.awt.image.bufferedimage;import Java.io.ioexception;import Java.util.random;import Javax.imageio.ImageIO; Import Javax.servlet.servletoutputstream;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.servlet.http.httpsession;import Org.springframework.stereotype.controller;import org.springframework.web.bind.annotation.requestmapping;@  Controllerpublic class Codecontroller {private int width = 90;//defines widthprivate int height = 20;//definition picture heightprivate int  Codecount = 4;//Defines the number of verification codes displayed on the image private int xx = 15;private int fontheight = 18;private int codey = 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 void GetCode (httpservletrequest Req, HttpservletreSponse resp) throws IOException {//definition image bufferbufferedimage buffimg = new BufferedImage (width, height,bufferedimage.type _INT_RGB);//graphics2d gd = Buffimg.creategraphics ();//graphics2d gd = (graphics2d) buffimg.getgraphics (); Graphics GD = Buffimg.getgraphics ();//create a random number generator class random random = new random ();//fill the image with white Gd.setcolor (color.white); Gd.fillrect (0, 0, width, height);//Create a font, the size of the font should be based on the height of the picture. Font font = new Font ("Fixedsys", Font.Bold, fontheight);//Set fonts. Gd.setfont (font);//Draw border. Gd.setcolor (Color.Black); gd.drawrect (0, 0, width-1, height-1);//randomly generate 40 interference lines, so that the authentication code in the image is not easily detected by other programs.  Gd.setcolor (Color.Black); for (int i = 0; i <; i++) {int x = random.nextint (width); int y = random.nextint (height); int XL = Random.nextint (n), int yl = Random.nextint (n), 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 = new StringBuffer (); int red = 0, green = 0, blue = 0;//randomly generates a verification code for the Codecount number. for (int i = 0; i < Codecount; i++) {//Get a randomly generated captcha number. String codE = string.valueof (Codesequence[random.nextint (36)]);//Generate 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);//Use a randomly generated color to draw the verification code into the image. Gd.setcolor (New Color (red, green, blue)), Gd.drawstring (code, (i + 1) * xx, Codey);//combine the resulting four random numbers. 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 ());//disable 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") public modelandview addUser (user user,httpsession session) {Modelandview mav=new Modelandview (); if (! ( User.getcode (). Equalsignorecase (Session.getattribute ("code"). ToString ()))) {  //Ignore Authenticode case Mav.setviewname (" Error "), Mav.addobject (" msg "," Incorrect verification Code "); return MAV;} else {User.setid (Uuid.randomuuid (). toString ()); User.setregtime (new Date ()); try {userservice.adduser (user);// Request.setattribute ("user", user), Mav.setviewname ("Success"), Mav.addobject ("user", user), Mav.addobject ("MSG", " Registered successfully, you can go to the landing "); return MAV; catch (Exception e) {mav.setviewname ("menu"), Mav.addobject ("user", null), Mav.addobject ("MSG", "Registration Failed"); return MAV;}}

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> &LT;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&gt Verification Code </td><td><input id= "Index_code" name= "code" type= "text"/></td> <td> <a href=" # "onclick=" changeimg () "> Change a </a></td></tr> & Lt;tr> <tD colspan= "2" align= "center" nowrap= "nowrap" ><label> <input type= "Submit" value= "register"/> <input type= "reset" value= "refill"/> </label></td> </tr> </table></for M>

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));} Timestamp   //In order to make every generation picture inconsistent, that is, do not let the browser read the cache, so you need to add a timestamp   function Chgurl (URL) {var timestamp = (new Date ()). ValueOf (); URL = Url.substring (0, +), if ((Url.indexof ("&") >= 0)) {url = url + "xtamp=" + timestamp;} else {url = url + "? Timestamp = "+ timestamp;} return URL;} </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.
Finally, you need this demo project source code Child, please contact email [email protected]

Or go to csdn code up for download, address: Https://code.csdn.net/Sgl731524380/verificationcode/tree/master

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Springmvc+java Verification Code Perfect registration function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.