Using Kaptcha to generate verification codes in sping MVC environment

Source: Internet
Author: User
Tags border color

Kaptcha is a very useful verification code generation tool. With it, you can generate various styles of verification codes, as it is configurable. Kaptcha works by calling Com.google.code.kaptcha.servlet.KaptchaServlet and generating a picture. The resulting Authenticode string is also placed in the httpsession.

The Kaptcha can be conveniently configured with:

    • The font of the verification code
    • Size of Captcha Font
    • The font color of the Captcha font
    • Verification Code content range (numbers, letters, Chinese characters!) )
    • Verify the size of the code picture, border, border thickness, border color
    • The interference line of the verification code (you can inherit com.google.code.kaptcha.NoiseProducer to write a custom interference line)
    • The style of the Verification code (fish-eye style, 3D, general Blur ...) Of course, you can also inherit com.google.code.kaptcha.GimpyEngine custom styles)

Here's how to use:

1. First go to the official website to download jar:http://code.google.com/p/kaptcha/

2. Create a Web project and import Kaptcha-2.3.jar into the environment variable.

Network disk download Jar package: Http://yunpan.cn/cdjzkrjKgQ7eD access password 754f

(1) Configure in Applicationcontext.xml

<bean id= "Captchaproducer"class= "Com.google.code.kaptcha.impl.DefaultKaptcha" > <property name= "config" > <beanclass= "Com.google.code.kaptcha.util.Config" > <constructor-arg> <props> <prop key= "Kaptcha.border" >no</prop> <prop key= "Kaptcha.border.color                        ">105,179,90</prop> <prop key=" Kaptcha.textproducer.font.color ">red</prop> <prop key= "Kaptcha.image.width" >250</prop> <prop key= "Kaptcha.te                        Xtproducer.font.size ">90</prop> <prop key=" Kaptcha.image.height ">90</prop> <prop key= "Kaptcha.session.key" >code</prop> <prop key= "kaptcha.t Extproducer.char.length ">4</prop> <prop key=" Kaptcha.textproducer.font.names "> Arial, Italic,        Microsoft Ya-Black </prop> </props> </constructor-arg> </bean> </property> &Lt;/bean> 

(2) Controller implementation

 PackageCom.souvc.app.base.captcha;ImportJava.awt.image.BufferedImage;ImportJavax.imageio.ImageIO;ImportJavax.servlet.ServletOutputStream;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.servlet.ModelAndView;Importcom.google.code.kaptcha.Constants;ImportCom.google.code.kaptcha.Producer;/*** Prevent CAPTCHA robot from landing *@authorLiuwang **/@Controller @requestmapping ("/kaptcha/*") Public classCaptchacontroller {@AutowiredPrivateProducer Captchaproducer =NULL; @RequestMapping PublicModelandview Getkaptchaimage (httpservletrequest request, httpservletresponse response)throwsException {HttpSession session=request.getsession (); String Code=(String) Session.getattribute (Constants.kaptcha_session_key); System.out.println ("****************** Verification Code is:" + code + "******************"); Response.setdateheader ("Expires", 0); //Set Standard http/1.1 no-cache headers.Response.setheader ("Cache-control", "No-store, No-cache, Must-revalidate"); //Set IE Extended http/1.1 no-cache headers (use AddHeader).Response.AddHeader ("Cache-control", "Post-check=0, pre-check=0"); //Set Standard http/1.0 no-cache header.Response.setheader ("Pragma", "No-cache"); //return a JPEGResponse.setcontenttype ("Image/jpeg"); //Create the text for the imageString Captext =Captchaproducer.createtext (); //Store the text in the sessionSession.setattribute (Constants.kaptcha_session_key, Captext); //Create the image with the textBufferedImage bi =captchaproducer.createimage (Captext); Servletoutputstream out=Response.getoutputstream (); //write the data outImageio.write (BI, "JPG", out); Try{Out.flush (); } finally{out.close (); }        return NULL; }}

(3) JSP code

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >$ (function () {$ (' #kaptchaImage '). Click (function () {//Generate verification Code$( This). Hide (). attr (' src ', './kaptcha/getkaptchaimage.do? ' + Math.floor (math.random () *100) . FadeIn (); Event.cancelbubble=true; });}); Window.onbeforeunload=function () {//automatically exits when the window is closed    if(event.clientx>360&&event.clienty<0| |Event.altkey)    {alert (parent.document.location); }};function ChangeCode () {$ (' #kaptchaImage '). Hide (). attr (' src ', './kaptcha/getkaptchaimage.do? ' + Math.floor (math.random () *100) . FadeIn (); Event.cancelbubble=true;}</script>class= "Chknumber" > <label>Verification Code:<input name= "Kaptcha" type= "text" id= "Kaptcha" maxlength= "4"class= "Chknumber_input"/> </label> <br/>  <a href=" # "onclick=" ChangeCode () "> Can't you see? change a piece of </a></ Div></body>

Warm tips:

Get the key statement for the verification code, as follows:

String code =(String) session.getattribute (Com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);            

(4) Kaptcha configurable items

Kaptcha.border Whether there is a border default to True we can set the Yes,nokaptcha.border.color border color by default to Color.BLACKkaptcha.border.thickness border Thickness default to 1kaptcha.producer.impl Authenticode generator default to DefaultKaptchakaptcha.textproducer.impl captcha text generator default to DEFAULTTEXTCREATORKAPTC Ha.textproducer.Charthe. String code text character content range defaults to abcde2345678gfynmnpwxkaptcha.textproducer.Char. length captcha text character length default to 5kaptcha.textproducer.font.names captcha text font style default to new font ("Arial", 1, FontSize),NewFont ("Courier", 1, FontSize) kaptcha.textproducer.font.size Authenticode text character size default to 40kaptcha.textproducer.font.color captcha text character color The default is Color.BLACKkaptcha.textproducer.Char. Space captcha text character spacing default to 2kaptcha.noise.impl Authenticode Noise generation object default to DefaultNoisekaptcha.noise.color captcha noise color default to Color.blackk Aptcha.obscurificator.impl Verification Code style engine defaults to WaterRipplekaptcha.word.impl captcha text character rendering defaults to Defaultwordrendererkaptcha.backgro Und.impl Verification Code Background generator defaults to DefaultBackgroundkaptcha.background.clear.from captcha background color progressive default to Color.LIGHT_GRAYkaptcha.backgroun D.clear.to Verification Code Background color Progressive default to Color.WHITEkaptcha.image.width captcha picture width default to 200kaptcha.image.height captcha picture height default is

(6) method to verify the correctness of the Verification code:

@RequestMapping (value = "/checkrandcode", method =requestmethod.get) Public voidCheckrandcode (httpservletrequest request, httpservletresponse response) {Map<string, object> map =NewHashmap<string, object>(); Try{String Randcode= Request.getparameter ("Randcode"); Logger.info ("Randcode:" +Randcode); String Status= "0"; String Code=(String) request.getsession (). getattribute (Com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if(Randcode.tolowercase (). Equals (Code.tolowercase ())) status= "1"; Map.put ("Status", status); Map.put ("description", "" "); String Data=jsonobject.fromobject (map). ToString (); Logger.info ("The data returned to the page is:" +data);            Response.getwriter (). print (data);            Response.getwriter (). Flush ();        Response.getwriter (). Close (); } Catch(Exception ex) {Logger.error (Ex.getmessage (), ex); }

(7) Default value

Using Kaptcha to generate verification codes in sping MVC environment

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.