jcaptcha codes using (a)

jcaptcha default style using the generated identification codes more difficult, it is necessary to custom style codes, including, background color, background size, font, font size, number of characters generated. As opposed to kaptcha complex.

JavaWeb create a project, the introduction of the relevant dependent jar package

 

Jcaptcha Service class to create a single embodiment, there is provided a key part of the style codes

package cn.util;

import java.awt.Font;

import com.octo.captcha.CaptchaFactory;
import com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator;
import com.octo.captcha.component.image.color.RandomRangeColorGenerator;
import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.image.textpaster.RandomTextPaster;
import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;
import com.octo.captcha.component.word.FileDictionary;
import com.octo.captcha.component.word.wordgenerator.ComposeDictionaryWordGenerator;
import com.octo.captcha.engine.GenericCaptchaEngine;
import com.octo.captcha.image.gimpy.GimpyFactory;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.octo.captcha.service.multitype.GenericManageableCaptchaService;
 
public class CaptchaServiceSingleton {
    private static ImageCaptchaService service = null;
 
    public static ImageCaptchaService getService(){
        if(service == null)
            service = generatorCaptchaService();
        return service;
    }
    / ** 
     * The code written SpringBean profile implement 
     * * / 
    public  static ImageCaptchaService generatorCaptchaService () {
         // generate random color parameter ranges represent the RGBA 
        RandomRangeColorGenerator textColor = new new RandomRangeColorGenerator ( new new  int [] {0,255} , new new  int [] {0,180}, new new  int [] {0,210}, new new  int [] {255,255 });
         // number of the random number and color of text, parameters 1 and 2 show a minimum of number and character generation to generate up 
        RandomTextPaster = randomTextPaster new new RandomTextPaster (. 4,. 5, textColor, to true );
         //Generating a background image of the aspect where the size is 8540, the background color may be provided and random background color, as used herein, the default white 
        UniColorBackgroundGenerator colorbgGen = new new UniColorBackgroundGenerator (85,40 );
         // randomly generated font size and font type, parameters 1 and 2 show the minimum and maximum font size, the font of the third represents a random 
        randomFontGenerator randomFontGenerator = new new randomFontGenerator (20 is, 25, new new the Font [] { new new the Font ( "Arial", 0, 10), new new the Font ( " tahoma ", 0,10 )});
         // bind a target image generated from the text above objects member 
        ComposedWordToImage cwti = new new ComposedWordToImage (randomFontGenerator, colorbgGen, randomTextPaster);
         //Random text dictionary, here using jcaptcha-1.0-all.jar text dictionary, the dictionary name toddlist.properties 
        ComposeDictionaryWordGenerator cdwg = new new ComposeDictionaryWordGenerator ( new new FileDictionary ( "toddlist" )); 
 
        GimpyFactory GF = new new GimpyFactory (cdwg, cwti ); 
 
        GenericCaptchaEngine GCE = new new GenericCaptchaEngine ( new new CaptchaFactory [] {} GF);
         // returns a Service object, where the time code 180 is to verify the presence, in seconds, the maximum memory size is 200,000 
        return  new new GenericManageableCaptchaService (GCE, 180, 200000,75000 ); 
    } 
}

Creating a Servlet generated verification code

package cn.servlet;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import cn.util.CaptchaServiceSingleton;
 
public class CustomServlet extends HttpServlet {
 
    private static final long serialVersionUID = 169310818225761427L;
     
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        byte[] captChallengeAsJpeg = null;
         
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
         
        String captchaId = req.getSession().getId();
        BufferedImage challenge = CaptchaServiceSingleton.getService().getImageChallengeForID(captchaId,req.getLocale());
         
        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
        jpegEncoder.encode(challenge);
         
        captChallengeAsJpeg = jpegOutputStream.toByteArray();
         
         resp.setHeader("Cache-Control", "no-store");
         resp.setHeader("Pragma", "no-cache");
         resp.setDateHeader("Expires", 0);
         resp.setContentType("image/jpeg");
          
         ServletOutputStream respOutputStream = resp.getOutputStream();
         respOutputStream.write(captChallengeAsJpeg);
         respOutputStream.flush();
         respOutputStream.close();
    }
}

Register the Servlet in web.xml

<servlet>
    <servlet-name>generateValidateCode</servlet-name>
    <servlet-class>cn.servlet.CustomServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>generateValidateCode</servlet-name>
    <url-pattern>/cgvc</url-pattern>
</servlet-mapping>

Create a html page, the introduction of jquery.js file

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="statics/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
    //Math.floor (); rounded down//refreshCaptcha () {
        functionthis code refresh//
    
        jQuery effect, fadeIn () method uses the fade-in effect to display the selected element, if the element is hidden. 
        $ ( ' #Vcode ' ) .hide () attr (.
             ' The src ' ,
             ' cgvc? ' + Math.floor (Math.random () *  100 )) fadeIn ();. 
    } 
</ Script > 
< body > 
    < form Action = "valiServlet" Method = "POST" > 
        < INPUT type = "text" name = "customgvc" > 
        < id="vcode" title="点击更换" alt="验证图片" style="vertical-align: middle;" src="cgvc" height="30" width="80">
        <input type="submit" value="提交">
    </form>
</body>
</html>

Verify and register to write a Servlet in web.xml. (Success.html and fail.html not created)

package cn.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.util.CaptchaServiceSingleton;
 
public class ValidateServlet extends HttpServlet {
 
    private static final long serialVersionUID = -7173743572400866269L;
     
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String captchaId = req.getSession().getId();
         
        String validateCode = req.getParameter("customgvc");
         
        boolean validateResult = CaptchaServiceSingleton.getService().validateResponseForID(captchaId, validateCode);
        if(validateResult)
            resp.sendRedirect("success.html");
        else
            resp.sendRedirect("fail.html");
    }
}
<servlet>
    <servlet-name>validatServlet</servlet-name>
    <servlet-class>cn.servlet.ValidateServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>validatServlet</servlet-name>
    <url-pattern>/valiServlet</url-pattern>
</servlet-mapping>

Enter the code click submit to see if can verify, if all goes well and submission of the Session is consistent

Guess you like

Origin www.cnblogs.com/chuanqi1995/p/11583407.html