在Spring中使用jcaptcha实现图片验证

我这里用的SPring4

Maven配置:

  com.octo.captcha
    jcaptcha
  1.0-all

还要添加commons-collections-*.*.jar 版本自己控制

首先是ApplicationContext.xml的配置,这里主要是对验证码生成器服务的注入,控制类就是Spring Web中的Controller,没有什么特别的

 

spring-jcaptcha.xml 代码如下:



	  
          
              
             
             
          
              
             
             
            180     
             
             
            100000     
             
             
            75000     
            
      
         
         
    

 

WEB.XML 部分代码

  
    contextConfigLocation
    
    	classpath:applicationContext.xml
    	classpath:spring-jcaptcha.xml
    
  
  
    org.springframework.web.util.IntrospectorCleanupListener
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
    Dispatcher
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:applicationContext-mvc.xml
    
  

 

 

下面是验证码生成器CaptchaEngineEx,网上找的:

import java.awt.Color;
import java.awt.Font;
import java.awt.image.ImageFilter;

import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
import com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator;
import com.octo.captcha.component.image.color.RandomListColorGenerator;
import com.octo.captcha.component.image.deformation.ImageDeformation;
import com.octo.captcha.component.image.deformation.ImageDeformationByFilters;
import com.octo.captcha.component.image.fontgenerator.FontGenerator;
import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.image.textpaster.DecoratedRandomTextPaster;
import com.octo.captcha.component.image.textpaster.TextPaster;
import com.octo.captcha.component.image.textpaster.textdecorator.TextDecorator;
import com.octo.captcha.component.image.wordtoimage.DeformedComposedWordToImage;
import com.octo.captcha.component.image.wordtoimage.WordToImage;
import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;
import com.octo.captcha.component.word.wordgenerator.WordGenerator;
import com.octo.captcha.engine.image.ListImageCaptchaEngine;
import com.octo.captcha.image.gimpy.GimpyFactory;

public class CaptchaEngineEx extends ListImageCaptchaEngine {

	protected void buildInitialFactories() {
		int minWordLength = 4;  //最小个数
		int maxWordLength = 6;	//最大个数
		int fontSize = 50;
		int imageWidth = 250;
		int imageHeight = 100;

		WordGenerator wordGenerator = new RandomWordGenerator(
				"0123456789abcdefghijklmnopqrstuvwxyz");

		TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength,
				maxWordLength, new RandomListColorGenerator(new Color[] {
						new Color(23, 170, 27), new Color(220, 34, 11),
						new Color(23, 67, 172) }), new TextDecorator[] {});
		BackgroundGenerator background = new UniColorBackgroundGenerator(
				imageWidth, imageHeight, Color.white);
		FontGenerator font = new RandomFontGenerator(fontSize, fontSize,
				new Font[] { new Font("nyala", Font.BOLD, fontSize),
						new Font("Bell MT", Font.PLAIN, fontSize),
						new Font("Credit valley", Font.BOLD, fontSize) });

		ImageDeformation postDef = new ImageDeformationByFilters(
				new ImageFilter[] {});
		ImageDeformation backDef = new ImageDeformationByFilters(
				new ImageFilter[] {});
		ImageDeformation textDef = new ImageDeformationByFilters(
				new ImageFilter[] {});

		WordToImage word2image = new DeformedComposedWordToImage(font,
				background, randomPaster, backDef, textDef, postDef);
		addFactory(new GimpyFactory(wordGenerator, word2image));

	}

}

 

验证码图片的显示是一个向服务器请求的过程 所以必须有serlvet来处理这个请求,下面是显示验证码的控制器类

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 验证码生成
 * @author shuxuefu
 *
 */
@Controller
@RequestMapping("/img")
public class GenerateImageController{

	@Resource(name = "imageCaptchaService")
	private ImageCaptchaService imageCaptchaService;

	@RequestMapping
	public void ImageCaptcha(HttpServletRequest request , HttpServletResponse response , Model model) 
	 throws ServletException, IOException{

		byte[] captchaChallengeAsJpeg = null;
		// the output stream to render the captcha image as jpeg into
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			// get the session id that will identify the generated captcha.
			// the same id must be used to validate the response, the session id
			// is a good candidate!
			String captchaId = request.getSession().getId();
			// call the ImageCaptchaService getChallenge method
			BufferedImage challenge = imageCaptchaService
					.getImageChallengeForID(captchaId, request
							.getLocale());

			// a jpeg encoder
			JPEGImageEncoder jpegEncoder = JPEGCodec
					.createJPEGEncoder(jpegOutputStream);
			jpegEncoder.encode(challenge);
		} catch (IllegalArgumentException e) {
		} catch (CaptchaServiceException e) {
		} catch (ImageFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();  
        // flush it in the response  
        response.setHeader("Cache-Control", "no-store");  
        response.setHeader("Pragma", "no-cache");  
        response.setDateHeader("Expires", 0);  
        response.setContentType("image/jpeg");  
        ServletOutputStream responseOutputStream = response  
                .getOutputStream();  
        responseOutputStream.write(captchaChallengeAsJpeg);  
        responseOutputStream.flush();  
        responseOutputStream.close();
	}

}

 

test.jsp 

这里只需要像图片一样写就可以了

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<form action="你要请求的地址">
   <input id="verify1"  type="text" name="verify1"placeholder="验证码"  style="float: left;width:130px;" />

   <img title="点击更换" alt="验证图片" src="<%=path%>/img.htm" style=" margin-top: 25px;float: right;
onclick="this.src='<%=path%>/img.htm?d='+new Date().getTime()"  >
   <input value="提&ensp;&ensp;交" type="submit">
<from>
 

 

 

 

验证工具类:

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
/**
 * 判断验证码是否正确
 * @author shuxuefu
 *
 */
public class YanZhengMa {
	
	public  boolean ValidateCaptchaImage(HttpServletRequest request,     
           ImageCaptchaService imageCaptchaService)throws ServletException , IOException {
		Boolean isResponseCorrect = Boolean.FALSE;     
        //获取Session ID   
        String captchaId = request.getSession().getId();     
        //获取输入框输入的值   
        String captcha_value = request.getParameter("verify"); 
        captcha_value = captcha_value == null ? request.getParameter("verify1") : captcha_value;
        // 调用框架判断是否正确    
        try {     
            isResponseCorrect = imageCaptchaService.validateResponseForID(captchaId, captcha_value.toLowerCase());  
        } catch (CaptchaServiceException e) {     
        	e.printStackTrace();
        }     
        System.out.println("验证结果:"+ isResponseCorrect);   
       
        if(isResponseCorrect.booleanValue()){  
        	return true;
        }  
        else {  
        	return false;  
        }  
    }     
}

 

前台提交表单 -->后台验证代码调用:

YanZhengMa yanzhen = new  YanZhengMa();
		boolean com = false; //是否成功
		try {
			com = yanzhen.ValidateCaptchaImage(request ,imageCaptchaService);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 

转载请注明原文链接:在Spring中使用jcaptcha实现图片验证

发表评论:

共有 0 条评论

 Top