在我们用户登录的时候,为了安全性考虑,会增加验证码的功能,这里采用的是google的kaptcha;spirngboot是轻便,独立,使得基于spring的应用开发变得特别简单。网上有很多介绍springboot的有点,这里不多说。言归正抓,讲下登陆时验证码结合springboot的用法
引入kaptcha所需要的jar包,我这里用的是maven
<dependency>
<groupId></groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
<exclusions>
<exclusion>
<artifactId>-api</artifactId>
<groupId></groupId>
</exclusion>
</exclusions>
</dependency>
去除包中自带的servlet包。在我个人的理解中springboot就是javaconfig和注解搭建起来的轻型的微架构。
下面是kapcha的javaconfig
@Configuration
public class CaptchaConfig {
@Bean(name="captchaProducer")
public DefaultKaptcha getKaptchaBean(){
DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
Properties properties=new Properties();
("", "yes");
("", "105,179,90");
("", "blue");
("", "125");
("", "45");
("", "code");
("", "4");
("", "宋体,楷体,微软雅黑");
Config config=new Config(properties);
(config);
return defaultKaptcha;
}
}
这里的的katcha的javaconfig相当于springmvc中的bean配置,下面给是一个针对上面javaconfig的springmvc的bean示例,供参考
<bean class="">
<property name="config">
<bean class="">
<constructor-arg>
<props>
<prop key="">yes</prop>
<prop key="">105,179,90</prop>
<prop key="">blue</prop>
<prop key="">125</prop>
<prop key="">45</prop>
<prop key="">45</prop>
<prop key="">code</prop>
<prop key="">4</prop>
<prop key="">宋体,楷体,微软雅黑</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
其中构造方法中的属性参数可以根据自己的需求来设置。
配置文件已经配好,那么如何获取自己的二维码呢,我的理解是画布的概念,然后将生成的四位的验证码生成对应的画布,然后让结果write出去。代码如下:
@RequestMapping(value = "/captcha-image")
public ModelAndView getKaptchaImage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
("Expires", 0);
("Cache-Control",
"no-store, no-cache, must-revalidate");
("Cache-Control", "post-check=0, pre-check=0");
("Pragma", "no-cache");
("image/jpeg");
String capText = ();
("capText: " + capText);
try {
String uuid=UUIDUtils.getUUID32().trim().toString();
().set(uuid, capText,60*5,);
Cookie cookie = new Cookie("captchaCode",uuid);
(cookie);
} catch (Exception e) {
();
}
BufferedImage bi = (capText);
ServletOutputStream out = ();
(bi, "jpg", out);
try {
();
} finally {
();
}
return null;
}
如上面的代码,在用户登录的时候使用验证码以及cooike中的captchacode来实现唯一性验证,开始的时候我考虑到放到session中,当时想了下,感觉这不科学啊,比如讲captchacode放到session中,这时候验证码是一个,后来另一个用户再登陆,前一个用户还在登陆中,这时候会出现一系列的问题。这里使用cookie和redis,来应对用户的并发登陆验证。
页面使用也比较简单如下:
<div style="float: left;">
<i><img style="height:22px;" alt="点击更换"
title="点击更换" src="code/captcha-image" /></i>
</div>
更换的话加一个click事件,然后清空以前在redis中对应的缓存数据;或者在获取验证码的时候,设置生存周期。
大概方法,如上,不对之处,敬请指正