spring整合Google Kaptcha验证码的使用

Kaptcha是什么?

kaptcha 是谷歌开源的非常实用的验证码生成工具,基于SimpleCaptcha的开源项目。使用Kaptcha 生成验证码十分简单并且参数可以进行自定义。只需添加jar包配置下就可以使用,通过配置,可以自己定义验证码大小、颜色、显示的字符等等。下面就来讲一下如何使用kaptcha生成验证码以及在服务器端取出验证码进行校验。

怎么使用Kaptcha?

1.首先要项目使用Kaptcha肯定要依赖kaptcha的jar,maven项目的话直接加入如下依赖,非maven项目就自己下载jar包吧

<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>

官方下载链接:https://code.google.com/archive/p/kaptcha/downloads,当然你得翻墙哈

2.配置kaptcha

以项目使用spring为例,配置一个默认的Kaptcha的bean,如下

<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha" scope="singleton">
	    <property name="config">
	        <bean class="com.google.code.kaptcha.util.Config">
	            <constructor-arg>
	                <props>
	                	<prop key="kaptcha.session.key">kaptcha.code</prop>  
	                	<!-- 无边框 -->
	                    <prop key="kaptcha.border">no</prop>
	                    <prop key="kaptcha.textproducer.font.color">black</prop>
	                    <!-- 渲染效果:水纹:WaterRipple;鱼眼:FishEyeGimpy;阴影:ShadowGimpy -->
	                    <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
	                    <!-- 不要噪点 -->
	                    <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
	                    <prop key="kaptcha.image.width">90</prop>
	                    <prop key="kaptcha.image.height">33</prop>
	                    <prop key="kaptcha.textproducer.font.size">25</prop>
	                    <prop key="kaptcha.textproducer.char.length">4</prop>
	                    <prop key="kaptcha.textproducer.char.space">5</prop>
	                    <!-- 和登录框背景颜色一致 -->
	                    <prop key="kaptcha.background.clear.from">247,247,247</prop>
	                    <prop key="kaptcha.background.clear.to">247,247,247</prop>
	                </props>
	            </constructor-arg>
	        </bean>
	    </property>
	</bean>

3.将生成的验证码保存进session中,并输出由验证码生成的图片流到页面

        @Autowired
	private Producer captchaProducer;
	@RequestMapping(value = "/kaptchaImage", method = RequestMethod.GET)
    public void kaptcha(HttpServletRequest req, HttpServletResponse rsp) {
		ServletOutputStream out = null;
		try {
	        HttpSession session = req.getSession();
	        rsp.setDateHeader("Expires", 0);
	        rsp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	        rsp.addHeader("Cache-Control", "post-check=0, pre-check=0");
	        rsp.setHeader("Pragma", "no-cache");
	        rsp.setContentType("image/jpeg");
	        String capText = captchaProducer.createText();
	        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
	        BufferedImage image = captchaProducer.createImage(capText);
	        out = rsp.getOutputStream();
	        ImageIO.write(image, "jpg", out);
	        out.flush();
        }catch(IOException e)
		{
			throw new SystemException(e);
		} finally {
            try {
				out.close();
			} catch (IOException e) {
				throw new SystemException(e);
			}
        }
    }

4.校验用户输入的验证码和保存进session的是否一直,达到验证目的

@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
	public String userLogin(String accountName, String password, String captcha, Boolean rememberMe, HttpServletRequest request) {
		 //从session中取出kaptcha生成的验证码text值
	        String expected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
	        //获取用户页面输入的验证码
	        if(!captcha.equalsIgnoreCase(expected))
	        {
	        	request.setAttribute("error", "验证码错误!");
				return "/login";
	        }else
	        {
                    xxxx验证码后的后续逻辑
                 }
}

 更详细的Kaptcha验证码配置?

  • kaptcha.border  是否有边框  默认为true  我们可以自己设置yes,no  

  • kaptcha.border.color   边框颜色   默认为Color.BLACK  

  • kaptcha.border.thickness  边框粗细度  默认为1  

  • kaptcha.producer.impl   验证码生成器  默认为DefaultKaptcha  

  • kaptcha.textproducer.impl   验证码文本生成器  默认为DefaultTextCreator  

  • kaptcha.textproducer.char.string   验证码文本字符内容范围  默认为abcde2345678gfynmnpwx  

  • kaptcha.textproducer.char.length   验证码文本字符长度  默认为5  

  • kaptcha.textproducer.font.names    验证码文本字体样式  默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)  

  • kaptcha.textproducer.font.size   验证码文本字符大小  默认为40  

  • kaptcha.textproducer.font.color  验证码文本字符颜色  默认为Color.BLACK  

  • kaptcha.textproducer.char.space  验证码文本字符间距  默认为2  

  • kaptcha.noise.impl    验证码噪点生成对象  默认为DefaultNoise  

  • kaptcha.noise.color   验证码噪点颜色   默认为Color.BLACK  

  • kaptcha.obscurificator.impl   验证码样式引擎  默认为WaterRipple  

  • kaptcha.word.impl   验证码文本字符渲染   默认为DefaultWordRenderer  

  • kaptcha.background.impl   验证码背景生成器   默认为DefaultBackground  

  • kaptcha.background.clear.from   验证码背景颜色渐进   默认为Color.LIGHT_GRAY  

  • kaptcha.background.clear.to   验证码背景颜色渐进   默认为Color.WHITE  

  • kaptcha.image.width   验证码图片宽度  默认为200  

  • kaptcha.image.height  验证码图片高度  默认为50

效果图如下

本文链接地址: http://www.kailing.pub/article/index/arcid/92.html

转载于:https://my.oschina.net/klblog/blog/668400

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC中生成验证码可以使用KaptchaGoogle的ReCaptcha。这里提供一种使用Kaptcha的方法: 1. 添加kaptcha依赖 在项目的pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> ``` 2. 在Spring MVC配置文件中添加Kaptcha配置 ``` <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg> <props> <prop key="kaptcha.border">no</prop> <prop key="kaptcha.textproducer.font.color">black</prop> <prop key="kaptcha.image.width">100</prop> <prop key="kaptcha.image.height">40</prop> <prop key="kaptcha.textproducer.char.string">0123456789abcdefghijklmnopqrstuvwxyz</prop> <prop key="kaptcha.textproducer.char.length">4</prop> </props> </constructor-arg> </bean> </property> </bean> ``` 3. 在Controller中使用Kaptcha 在Controller的方法中添加以下代码: ``` @RequestMapping("/captcha.jpg") @ResponseBody public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); ServletOutputStream out = response.getOutputStream(); try { String captchaText = captchaProducer.createText(); request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, captchaText); BufferedImage bi = captchaProducer.createImage(captchaText); ImageIO.write(bi, "jpg", out); out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(out); } } ``` 4. 在JSP页面中显示验证码 在JSP页面中添加以下代码: ``` <img src="${ctx}/captcha.jpg" onclick="this.src='${ctx}/captcha.jpg?'+Math.random();" /> <input type="text" name="captcha" /> ``` 以上代码中,`${ctx}`代表的是项目的context path,可以根据具体情况进行修改。点击验证码图片时,会重新请求验证码接口,刷新验证码。 这样就可以在Spring MVC中生成验证码了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值