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

##百度网盘demo提取地址:
https://pan.baidu.com/s/1dF81khN

GitHub

https://github.com/rundreamstop/graphic-validate-code

##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<FilterFactory> factories;
	
	static {
		factories = new ArrayList<FilterFactory>();
		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;
    }
}
  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rundreamsFly

达者不再兼济天下,却怪穷者独善

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值