JSP Spring MVC Framework Integration Google Kaptcha Build Verification code example tutorial

Source: Internet
Author: User
Tags bind border color constructor flush generator

About Kaptcha Introduction, we do not say, online a bunch of information.

Use Kaptcha to facilitate configuration:
    captcha font
    captcha font size
     the font color of the code font
    The scope of the contents of the Verification code (numbers, letters, Chinese characters!)
    Verify code picture size, border, border thickness, border color
    validation code interference line ( You can inherit com.google.code.kaptcha.NoiseProducer to write a custom interference line
    verification code style (fish eye style, 3D, general Blur ...) Of course, you can inherit the Com.google.code.kaptcha.GimpyEngine custom style)


for the following:

1. First go to the website download jar: http://code.google.com/p/kaptcha/
2. Create a Web project and import Kaptcha-2.3.jar into environment variables.
Network disk download jar package: http://yunpan.cn/cdjzkrjkgq7ed  access password 754f

(1) configuring in Applicationcontext.xml

<bean id= "Captchaproducer"  class= "Com.google.code.kaptcha.impl.DefaultKaptcha" >      <property name= "config" >         <bean  class= "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.textproducer.font.size" >90</prop>                      <prop key= " Kaptcha.image.height ">90</prop>                      <prop key= "Kaptcha.session.key" >code</prop >                      <prop key= "Kaptcha.textproducer.char.length" >4</prop>          &nbsP;           <prop key= " Kaptcha.textproducer.font.names "> Arial, italics, Microsoft Ya-Black </prop>                  </props>         
    </constructor-arg>         </bean>     </property> </bean>


(2) Implementation of controller

package com.souvc.app.base.captcha;
import java.awt.image.bufferedimage;
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.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.servlet.modelandview;
import com.google.code.kaptcha.constants;
import com.google.code.kaptcha.producer; /**  *  prevent captcha robot landing  *  @author  liuwang  *  */@Controller @RequestMapping ("/ kaptcha/* ") public class captchacontroller {         @
Autowired     private Producer captchaProducer = null;      @ReqUestmapping     public modelandview getkaptchaimage (HttpServletRequest  Request, httpservletresponse response)  throws exception {    
    httpsession session = request.getsession ();         String code =  (String) Session.getattribute (
Constants.kaptcha_session_key); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("****************** Authentication 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 jpeg         response.setcontenttype ("Image/jpeg");                  // create  the text for the image   &Nbsp;     string captext = captchaproducer.createtext ();                  // store  the text in the session         
Session.setattribute (Constants.kaptcha_session_key, captext);                  // create  the image with the text         bufferedimage
 bi = captchaproducer.createimage (Captext);         ServletOutputStream out = 
Response.getoutputstream ();                  // write  the data out         imageio.write (bi,  "JPG",
 out);         try {         
   out.flush ();         } finally {      
      out.close ();         }         return 
Null &NBSP;&NBSP;&NBSP;&NBSP}}



(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 "> 


Warm tips:

Gets the key statement for the validation 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 is true we can set our own yes,no
Kaptcha.border.color border color defaults to Color.Black
kaptcha.border.thickness Border thickness defaults to 1
Kaptcha.producer.impl Authentication code generator defaults to Defaultkaptcha
Kaptcha.textproducer.impl Authenticode Text generator defaults to Defaulttextcreator
kaptcha.textproducer.char.string Authenticode text character content range defaults to ABCDE2345678GFYNMNPWX
Kaptcha.textproducer.char.length Authenticode text character length defaults to 5
Kaptcha.textproducer.font.names Authenticode text font style defaults to new font ("Arial", 1, fontsize), New Font ("Courier", 1, FontSize)
Kaptcha.textproducer.font.size Authenticode text character size defaults to 40
Kaptcha.textproducer.font.color Authenticode text character color defaults to Color.Black
Kaptcha.textproducer.char.space Authenticode text character spacing defaults to 2
Kaptcha.noise.impl Authentication Code Noise Generation object defaults to Defaultnoise
Kaptcha.noise.color Verify code noise color defaults to Color.Black
Kaptcha.obscurificator.impl authentication code style engine defaults to Waterripple
Kaptcha.word.impl Authenticode text character rendering defaults to Defaultwordrenderer
Kaptcha.background.impl Authentication Code Background generator defaults to Defaultbackground
Kaptcha.background.clear.from Authenticode background color progressively defaults to Color.light_gray
Kaptcha.background.clear.to Authenticode background color progressively defaults to Color.White
Kaptcha.image.width Verification Code picture width defaults to 200
Kaptcha.image.height Verification Code Picture height defaults to 50

(5) Verify that the verification code is correct:

@RequestMapping (value =  "/checkrandcode",  method = requestmethod.get) public void  checkrandcode (Httpservletrequest request,          Httpservletresponse response)  {    Map<String, Object> map 
= new hashmap<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);     }



(6) Default value





Another practical tutorial on the use of Kaptcha Verification code in spring MVC

Configuring Web.xml Files

<!--kaptcha  Verification code   --><!--       <servlet>            <servlet-name>kaptcha</servlet-name>            <servlet-class> com.google.code.kaptcha.servlet.kaptchaservlet</servlet-class>            <init-param>                <param-name>kaptcha.border</param-name>                <param-value>no</param-value>            </init-param>            <init-param>                <param-name>kaptcha.border.color</param-name>               <param-value> 105,179,90</param-value>           </init-param>                 <init-param>                <param-name> kaptcha.textproducer.font.color</param-name>                <param-value>red</param-value>            </init-param>           < init-param>               < param-name>kaptcha.image.width</param-name>                <param-value>250</param-value>           </init-param>            <init-param>                <param-name>kaptcha.image.height</param-name >               <param-value>90 </param-value>           </init-param>            <init-param>                <param-name>kaptcha.textproducer.font.size</ param-name>               < param-value>70</param-value>           </ init-param>           <init-param>                <param-name>kaptcha.session.key</param-name>                <param-value>code</param-value>            </init-param>            <init-param>                <param-name>kaptcha.textproducer.char.length</param-name>                <param-value>4</param-value>            </init-param>            <init-param>                <param-name>kaptcha.textproducer.font.names</param-name>       
        <param-value> Arial, italics, Microsoft Ya-Black </param-value>  
        </init-param>            </servlet>


XML code

<servlet-mapping>
<servlet-name>kaptcha</servlet-name>
<url-pattern>/cliniccou Ntmanager/kaptcha.jpg</url-pattern>
</servlet-mapping>



JSP page Usage

<table>           <tr>                <td></td>              
 <td valign= "Top" >                              <form  Method= "POST" >                        <br>sec code:<input type= "text"  name= " Kaptchafield "><br />                        <input type= "Submit"  name= "Submit" >                   </form>               </td>            </tr>       </table>             <br /><br /><br /><br  />              <%            String c =  (String) Session.getattribute ( Com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);            String parm =  (String)  request.getparameter ("Kaptchafield");                       out.println (" parameter:  " + parm +  " ? Session Key: "  + c +  " : ");                      if   (c != null && parm != null)  {                if  (C.equals (parm))  {                    out.println ("<b>true </b> ");               } else  {                    out.println ("<b>false</b>");                }                   %> 


&NBSP
The configuration above is valid under the normal JSP environment, if the session value is not taken in the spring MVC environment, the sping MVC Environment Verification Code is configured as follows:

Instead of configuring in Web.xml, configure

in Applicationcontext.xml

<bean id= "Captchaproducer"  class= "Com.google.code.kaptcha.impl.DefaultKaptcha" >           <property name= "config" >                <bean class= " 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.textproducer.font.size" >90</prop>                             <prop key= "Kaptcha.image.height" >90</prop>                            <prop key= "Kaptcha.session.key" >code</prop>                            <prop key= " Kaptcha.textproducer.char.length ">4</prop>                            <prop  key= "Kaptcha.textproducer.font.names" > Arial, italics, Microsoft Ya-Black </prop>                        </props>                     </constructor-arg>                </bean> &nBsp         </property>       </bean >



New build Picture control class

import java.awt.image.bufferedimage;   import javax.imageio.imageio;   Import  javax.servlet.ServletOutputStream;   import javax.servlet.http.httpservletrequest;    import javax.servlet.http.httpservletresponse;   import  org.springframework.beans.factory.annotation.autowired;   import  org.springframework.stereotype.controller;   import  org.springframework.web.bind.annotation.requestmapping;   import  org.springframework.web.servlet.modelandview;   import com.google.code.kaptcha.constants;    import com.google.code.kaptcha.producer;      @Controller    @ Requestmapping ("/")    public class captchaimagecreatecontroller {               private Producer captchaProducer =  null;           @Autowired        public void setcaptchaproducer (Producer  captchaproducer)  {           this.captchaproducer  = captchaProducer;       }            @RequestMapping ("/captcha-image")        public ModelAndView  HandleRequest (Httpservletrequest request, httpservletresponse response)  throws  exception {              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 jpeg            Response.setcontenttype ("Image/jpeg");           //  create the text for the image            string captext = captchaproducer.createtext ();            // store the text in the session            Request.getsession (). setattribute (constants.kaptcha_session_key, captext);      
     // create the image with the text           bufferedimage bi = captchaproducer.createimage ( Captext);           ServletOutputStream out =  Response.getoutputstream ();           // write the  data out           imageio.write (bi,  "JPG",  out);           try {                out.flush ();            } finally {                Out.close ();           }            return null;       }     }

&NBSP

Foreground call mode

<div class= "Chknumber" >          <label> Verification Code:                   < Input name= "Kaptcha"  type= "text"  id= "Kaptcha"  maxlength= "4"  class= "Chknumber_input"  />                        </label>                        <script type= "Text/javascript" >                $ (function () {                         $ (' #kaptchaImage '). Click (function  ()  {//Generate verification Code                 $ (This). Hide (). attr (' src ',  '/cliniccountmanager/captcha-image.do? '  + math.floor (Math.random () *100)  ). FadeIn ();  })                           });                      </script>         </div>


How to take the verification code

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


Related Article

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.