> 文档中心 > java实现图片验证码全套实现方式

java实现图片验证码全套实现方式


百度网盘demo提取地址:

https://pan.baidu.com/s/1dF81khN

java引用的包

import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Random;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.shiro.SecurityUtils;import org.apache.shiro.session.Session;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;import com.github.bingoohuang.patchca.filter.FilterFactory;import com.github.bingoohuang.patchca.filter.predefined.CurvesRippleFilterFactory;import com.github.bingoohuang.patchca.filter.predefined.DiffuseRippleFilterFactory;import com.github.bingoohuang.patchca.filter.predefined.DoubleRippleFilterFactory;import com.github.bingoohuang.patchca.filter.predefined.MarbleRippleFilterFactory;import com.github.bingoohuang.patchca.filter.predefined.WobbleRippleFilterFactory;import com.github.bingoohuang.patchca.utils.encoder.EncoderHelper;import com.yjf.easylife.web.security.util.CaptchaFactory;

控制器代码

@Controller@RequestMapping("/security")public class ValidateController {    /**     * 日志对象     */    protected final Logger logger = LoggerFactory.getLogger(getClass());    private static final long serialVersionUID = 1L;    private static ConfigurableCaptchaService cs = CaptchaFactory.getInstance();    private static List factories;    static { factories = new ArrayList(); factories.add(new CurvesRippleFilterFactory(cs.getColorFactory())); factories.add(new MarbleRippleFilterFactory()); factories.add(new DoubleRippleFilterFactory()); factories.add(new WobbleRippleFilterFactory()); factories.add(new DiffuseRippleFilterFactory());    }    @RequestMapping("/getImage.htm")    public void getImage(HttpServletRequest request, HttpServletResponse response) { try {     cs.setFilterFactory(factories.get(new Random().nextInt(5)));     setResponseHeaders(response);     Session session = SecurityUtils.getSubject().getSession();;     String token = EncoderHelper.getChallangeAndWriteImage(cs, "png",  response.getOutputStream());     session.setAttribute("EASYLIFE_CAPCHA", token);     logger.info("当前的SessionID = " + session.getId() + ",  验证码 = " + token); } catch (IOException e) {     e.printStackTrace(); }    }    private void setResponseHeaders(HttpServletResponse response) { response.setContentType("image/png"); response.setHeader("Cache-Control", "no-cache, no-store"); response.setHeader("Pragma", "no-cache"); long time = System.currentTimeMillis(); response.setDateHeader("Last-Modified", time); response.setDateHeader("Date", time); response.setDateHeader("Expires", time);    }}

CaptchaFactory实现代码

import com.github.bingoohuang.patchca.color.RandomColorFactory;import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;import com.github.bingoohuang.patchca.word.RandomWordFactory;public class CaptchaFactory {    private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();    static { cs.setColorFactory(new RandomColorFactory()); RandomWordFactory wf = new RandomWordFactory(); wf.setCharacters("1234567890"); wf.setMaxLength(4); wf.setMinLength(4); cs.setWordFactory(wf);    }    public static ConfigurableCaptchaService getInstance() { return cs;    }}

html代码

<html> <head></head> <body>  <div class="p-new-in">    <span class="p-new-inname">验证码</span>   <input type="text" name="customCaptcha" class="p-new-input p-new-w177" placeholder="请输入图片验证码" />    <span class="p-new-code l-mar-r15"> <img src="/security/getImage.htm" class="reloadImage" id="reloadImage" width="121" height="40" /> </span>    <a href="javaScript:;" class="l-color9 reloadImage">看不清楚,换一张</a>   </div> </body></html>

js代码

$(".reloadImage").click(function () {    //获取当前的时间作为参数,无具体意义    var timenow = new Date().getTime();    $('#reloadImage').attr("src", "/security/getImage.htm?date=" + timenow);});

判断验证码是否正确

/** * * Created by cike-zihao on 2015/11/25 */package com.yjf.easylife.common.util;import org.apache.commons.lang3.StringUtils;import javax.servlet.http.HttpServletRequest;
/** * Created by cike-zihao on 2015/11/25. */public class SecurityCodeUtil {    public static boolean whetherImgCaptchaMatch(String customCaptcha, HttpServletRequest request) { boolean captchaMatch = true; String requestCaptcha = (String) request.getSession()      .getAttribute("EASYLIFE_CAPCHA"); if (!StringUtils.equals(customCaptcha, requestCaptcha)) {     captchaMatch = false; } return captchaMatch;    }}