jcaptcha使用

jcaptcha使用

jcaptcha是做图片验证码的,主要说下在springboot 里面的使用方法.

pom.xml里面的配置

xml

<dependency>

<groupId>com.octo.captcha</groupId>

<artifactId>jcaptcha</artifactId>

<version>1.0</version>

</dependency>

 

两个java类

CaptchaService 处理图片

import com.octo.captcha.component.image.backgroundgenerator.GradientBackgroundGenerator;
import com.octo.captcha.component.image.color.SingleColorGenerator;
import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.image.textpaster.NonLinearTextPaster;
import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;
import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;
import com.octo.captcha.engine.GenericCaptchaEngine;
import com.octo.captcha.image.gimpy.GimpyFactory;
import com.octo.captcha.service.captchastore.FastHashMapCaptchaStore;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import com.octo.captcha.service.image.ImageCaptchaService;

import java.awt.*;


public class CaptchaService {
    private static class SingletonHolder {
        private static ImageCaptchaService imageCaptchaService = new DefaultManageableImageCaptchaService(
                new FastHashMapCaptchaStore(),
                new GenericCaptchaEngine(
                        new GimpyFactory[]{new GimpyFactory(
                                new RandomWordGenerator("123456789ABCE"),
                                new ComposedWordToImage(
                                        new RandomFontGenerator(20, 20, new Font[]{new Font("Arial", 20, 20)}),
                                        new GradientBackgroundGenerator(90, 30, new SingleColorGenerator(new Color(235, 255, 255)), new SingleColorGenerator(new Color(255, 195, 230))),
                                        new NonLinearTextPaster(4, 4, new Color(11, 11, 11))
                                )
                        )}
                ),
                180,
                180000,
                20000
        );
    }

    private CaptchaService() {
    }

    public static ImageCaptchaService getInstance() {
        return SingletonHolder.imageCaptchaService;
  }
}

CaptchaController 处理页面请求

import com.octo.captcha.service.CaptchaServiceException;
import com.smspai.sms.website.config.CaptchaService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;


@Controller
@RequestMapping("/component")
public class CaptchaController {
	// slf4j logger
	private final static Logger logger = LoggerFactory.getLogger(CaptchaController.class);

	@ResponseBody
	@RequestMapping(value = "/captcha") //captcha captchaImage
	public void getJCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		BufferedImage bi = CaptchaService.getInstance().getImageChallengeForID(request.getSession(true)
				.getId());
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
		return;
	}

	//    经验:@Param("code") String code 这两个名字必须相同,都要叫code,这是绑定的
	@ResponseBody
	@RequestMapping(value = "/check", method = RequestMethod.POST) // check validate
	@ResponseStatus(HttpStatus.OK)
	public Object validate(@Param("code") String code, HttpServletRequest request) {
		ModelMap modelMap = new ModelMap();
		boolean isCaptchaCorrect = false;
		try {
			isCaptchaCorrect = CaptchaService.getInstance().validateResponseForID(request.getSession().getId(), code.toUpperCase());
//        if (isCaptchaCorrect) {
//
//        }
		} catch (CaptchaServiceException exception) {
			logger.debug(">>>>>>>[CaptchaController.validate]:\n "  + exception.getMessage());
			modelMap.addAttribute("refresh", true);
		}
		modelMap.addAttribute("success", isCaptchaCorrect);

		logger.debug(">>>>>>>[CaptchaController.validate]: \n" + code + ":" + isCaptchaCorrect);

		return modelMap;
	}
}

页面设置 及 js

<div class="field-container">
	<input  name="checkcode" type="text"  data-placeholder="验证码" placeholder="验证码"/>
	<img style="float:left;cursor: pointer;border: 1px solid #ddd;margin-left: 10px;" src="/component/captcha" id="J_captcha" title="点击刷新验证码" border="0" height="30"/>
</div>

检查验证码

$(".field[name=checkcode]").keyup(function (event) {

	var _this = $(this);
	var val = $.trim(_this.val());
	if (val.length == 4) {
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url: '/component/check',
			data: {
				code: val
			},
			success: function (result) {
				if (result.success) {

					$(".ccstatus").show();
				} else if (result.refresh) {
					$("#J_captcha").click();
				} else {
					$(".ccstatus").hide();
				}
			},
			error: function () {
				$(".ccstatus").hide();
			}

		});

	} else {
		$(".ccstatus").hide();
	}

});

验证码刷新

$("#J_captcha").click(function () {
	var _this = $(this);
	var ts = new Date().getTime();
	_this.attr('src', '/component/captcha?ts=' + ts);
	$(".field[name=checkcode]").val('');
	$(".field[name=checkcode]").focus();
});
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/100412.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java map 缓存_缓存用于

    java map 缓存_缓存用于缓存什么是缓存?平常的开发项目中,多多少少都会使用到缓存,因为一些数据我们没有必要每次查询的时候都去查询到数据库。缓存的使用场景:在Java应用中,对于访问频率高,更新少的数据,通常的方案是将这类数据加入缓存中,相对从数据库中读取,读缓存效率会有很大提升。在集群环境下,常用的分布式缓存有Redis等。但在某些业务场景上,可能不需要去搭建一套复杂的分布式缓存系统,在单机环境下,通常是会希望使用内部的缓存(LocalCache)。使用map缓存方案:基于ConcurrentHashMap实现数

    2022年9月27日
    2
  • MATLAB中神经网络工具箱的使用「建议收藏」

    MATLAB中神经网络工具箱的使用「建议收藏」今夕何夕兮,前些天把玩了一下MATLAB中神经网络工具箱的使用,忽有“扪参历井仰胁息”之感。别的倒是没什么,只是神经网络的数据组织结构有些“怪异”,要是不小心就会导致工具箱报错。以下便是神经网络工具箱的正确打开姿势,谨供诸君参考:1.打开MATLAB,在命令行输入nntool,将出现如下界面:图1神经网络工具箱主界面其中最主要的分为6个部分:第1部分中显示的是系统的输…

    2022年6月20日
    124
  • mybatis map foreach_while的三个用法

    mybatis map foreach_while的三个用法MyBatis循环Map今天遇到一个比较特殊的业务,需要对传入的Map数据在映射文件中进行遍历,在之前的学习中,我们也知道MyBatis有默认对集合的操作list和array,但是没有默认的map,所有不能直接写collection=“map”,如果这么处理,它会当成是根据map.get(“map”)获取传递value只,大部分情况下是一个map中是不会有“map”这个key的,于是就是报错。如果你想用map标识来获取参数map,就需要保证传入的Map参数有@Param(“map”

    2022年8月30日
    4
  • html attrs属性,在Vue中详细介绍$attrs属性

    html attrs属性,在Vue中详细介绍$attrs属性这篇文章主要给大家介绍了关于Vuev2.4中新增的$attrs及$listeners属性的使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着我来一起学习学习吧。前言多级组件嵌套需要传递数据时,通常使用的方法是通过vuex。如果仅仅是传递数据,而不做中间处理,使用vuex处理,未免有点杀鸡用牛刀。Vue2.4版本提供了另一种方法,使用…

    2022年10月17日
    1
  • JavaScript执行顺序分析建议收藏

    之前从JavaScript引擎的解析机制来探索JavaScript的工作原理,下面我们以更形象的示例来说明JavaScript代码在页面中的执行顺序。如果说,JavaScript引擎的工作机制比较深奥

    2021年12月20日
    53

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号