验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。今天给大家介绍一下kaptcha的和springboot一起使用的简单例子。

准备工作

1.首要要有一个可以运行的springboot的项目并可以正常运行

2.导入kaptcha依赖

<!--验证码-->
<dependency>
   <groupId>com.github.penggle</groupId>
   <artifactId>kaptcha</artifactId>
   <version>2.3.2</version>
</dependency>

开始试验

我们有两种方式在springboot中使用kaptcha

1.使用.xml的配置方式配置生成kaptcha的bean对象,在启动类上@ImportResource这个xml文件;在controller中注入其对象并使用

2.是把kaptcha作为工程的一个类,加上@component注解在返回kaptcha的方法中加上@Bean注解,再在controller中注入其对象。

第一种方法

在resources中创建一个kaptchaConfig.xml文件 如:

kaptchaConfig.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg type="java.util.Properties">
                    <props>
                        <!--是否使用边框-->
                        <prop key = "kaptcha.border ">yes</prop>
                        <!--边框颜色-->
                        <prop key="kaptcha.border.color">105,179,90</prop>
                        <!--验证码字体颜色-->
                        <prop key="kaptcha.textproducer.font.color">blue</prop>
                        <!--验证码图片的宽度-->
                        <prop key="kaptcha.image.width">100</prop>
                        <!--验证码图片的高度-->
                        <prop key="kaptcha.image.height">50</prop>
                        <!--验证码字体的大小-->
                        <prop key="kaptcha.textproducer.font.size">27</prop>
                        <!--验证码保存在session的key-->
                        <prop key="kaptcha.session.key">code</prop>
                        <!--验证码输出的字符长度-->
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <!--验证码的字体设置-->
                        <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
                        <!--验证码的取值范围-->
                        <prop key="kaptcha.textproducer.char.string">0123456789ABCEFGHIJKLMNOPQRSTUVWXYZ</prop>
                        <!--图片的样式-->
                        <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
                        <!--干扰颜色,合法值: r,g,b 或者 white,black,blue.-->
                        <prop key="kaptcha.noise.color">black</prop>
                        <!--干扰实现类-->
                        <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop>
                        <!--背景颜色渐变,开始颜色-->
                        <prop key="kaptcha.background.clear.from">185,56,213</prop>
                        <!--背景颜色渐变,结束颜色-->
                        <prop key="kaptcha.background.clear.to">white</prop>
                        <!--文字间隔-->
                        <prop key="kaptcha.textproducer.char.space">3</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>
</beans>

在springboot启动类上引入这个文件

@SpringBootApplication
@ImportResource(locations={"classpath:kaptchaConfig.xml"})
public class CodeDemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(CodeDemoApplication.class, args);
    }
}

在controller中注入DefaultKaptcha 

@Autowired
    DefaultKaptcha defaultKaptcha;

在controller中编写获取验证码图片的方法

//获取验证码
    @RequestMapping("/getCode")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

在controller中编写验证的方法

//验证码验证
    @RequestMapping("/checkCode")
    @ResponseBody
    public boolean imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
        String parameter = httpServletRequest.getParameter("code");
        log.info("Session  vrifyCode ---->"+captchaId+"---- form code --->"+parameter);
        if (!captchaId.equals(parameter)) {
            log.info("错误的验证码");
            return false;
        } else {
            return true;
        }
    }

模板页面register.html

......
<div class="form-group">
                <label class="col-md-2 col-md-offset-2 control-label">验证码</label>
                <div class="col-md-3">
                    <div class="row_bj" style="width:100%;">
                        <input type="text" class="form-control" id="code" name="code" required placeholder="请输入验证码">
                        <img alt="验证码" onclick = "this.src='/getCode?d='+new Date()*1" src="/getCode" style="margin-left:20px;"/>
                    </div>
                    <label class="control-label text-danger" id="code2">(验证码错误)</label>
                </div>
            </div>
......

启动访问

控制台日志结果:

第二种方法:这种方法把.xml文件换成使用代码来配置:

KaptchaConfig配置类:

@Component
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getDefaultKaptcha(){
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "red");
        properties.setProperty("kaptcha.image.width", "110");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "40");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

注意要去掉启动类中引入的.xml文件,不然会有两个相同的对象,而你没有指明要注入哪一个的话启动会失败。

补充:对于kaptcha的配置属性可以百度找一找。

 

posted on 2018-10-19 10:54  阿娇爱上了阿强  阅读(9295)  评论(0编辑  收藏  举报