"Spring" based on SPRINGMVC's image verification code function implementation

Source: Internet
Author: User
Tags tojson

Background implementation code:

Imgcontroller.java file

 PackageCn.shop.controller;ImportJava.awt.Color;ImportJava.awt.Font;ImportJava.awt.Graphics;ImportJava.awt.image.BufferedImage;Importjava.io.IOException;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Random;ImportJavax.imageio.ImageIO;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.ResponseBody;ImportCom.google.gson.Gson; @Controller Public classImgcontroller {@RequestMapping ({"Authcode.htgo"})     Public voidGetauthcode (httpservletrequest request, HttpServletResponse response,httpsession session)throwsIOException {intwidth = 63; intHeight = 37; Random Random=NewRandom (); //Set Response header information//Disable CachingResponse.setheader ("Pragma", "No-cache"); Response.setheader ("Cache-control", "No-cache"); Response.setdateheader ("Expires", 0); //Generate buffer Image classBufferedImage image =NewBufferedImage (width, height, 1); //the graphics that produce the image class are used for drawing operationsGraphics g =Image.getgraphics (); //style of the graphics classG.setcolor ( This. Getrandcolor (200, 250)); G.setfont (NewFont ("Times New Roman", 0,28)); G.fillrect (0, 0, width, height); //Draw Interference Lines         for(inti=0;i<40;i++) {G.setcolor ( This. Getrandcolor (130, 200)); intx =random.nextint (width); inty =random.nextint (height); intX1 = Random.nextint (12); intY1 = Random.nextint (12); G.drawline (x, y, x+ x1, y +y1); }        //Drawing charactersString Strcode = "";  for(inti=0;i<4;i++) {String rand= String.valueof (Random.nextint (10)); Strcode= Strcode +Rand; G.setcolor (NewColor (20+random.nextint, 20+random.nextint), 20+random.nextint (110))); g.DrawString (Rand,13*i+6, 28); }        //saving characters to the session for verification of the front endSession.setattribute ("Strcode", Strcode);        G.dispose (); Imageio.write (Image,"JPEG", Response.getoutputstream ());    Response.getoutputstream (). Flush (); }        //Create colorColor Getrandcolor (intFcintBC) {Random random=NewRandom (); if(fc>255) FC= 255; if(bc>255) BC= 255; intr = FC + random.nextint (BC-FC); intg = FC + random.nextint (BC-FC); intB = fc + random.nextint (BC-FC); return NewColor (R,G,B); }    /*** Verify that the user's verification code is correct *@paramvalue user-entered verification code *@paramRequest HttpServletRequest Object *@returna string of type strings. The format is:<br/> * {"res",boolean},<br/> * If {"res", true}, indicating successful validation <br/&     Gt * If {"res", false} indicates that the validation failed*/@RequestMapping ("Validate.htgo") @ResponseBody Publicstring Validate (string Value,httpservletrequest request) {string Valuecode= (String) request.getsession (). getattribute ("Strcode"); Map Map=NewHashMap (); if(valuecode!=NULL){            if(Valuecode.equals (value)) {Map.put ("Res",true); return NewGson (). ToJson (map); }} map.put ("Res",false); return NewGson (). ToJson (map); }}
Imgcontroller.java

Front-End Part code:

    <Divclass= "Form-group">Verification Code:<inputID= "Authcode"name= "Authcode"type= "text"/>        <!--here the value of the SRC attribute of the IMG tag is the request address of the background implementation picture Captcha method -        <label><imgtype= "image"src= "Authcode.do"ID= "Codeimage"onclick= "Chagecode ()"title= "The picture is not clear?" Click to re-get verification Code "style= "Cursor:pointer;"/></label>        <label><aonclick= "Chagecode ()">Another one.</a></label>    </Div>

To achieve the click image Update JS Method:

    function Chagecode () {        $ (' #codeImage '). attr (' src ', ' authcode.do?abc= ' +math.random ());   Add math.random after linking to ensure that a new verification code is generated each time to avoid caching problems.     }

When the form is submitted, it can be verified by Ajax and the user's input is correct:

$.post (  "validate.do",  {"value": $ ("#code_input"). Val ()},  function  (res) {      if(res.res) {          alert ("validation succeeded");       } Else {          alert ("validation failed");
Refresh Verification Code Picture
$ ("#codeImage"). Trigger ("click"); } }, "JSON");

"Spring" based on SPRINGMVC's image verification code function implementation

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.