您的位置:首页 > 编程语言 > Java开发

kaptcha的和springboot一起使用的简单例子

2018-02-09 10:36 309 查看

kaptcha介绍

验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。这个问题可以由计算机生成并评判,但是必须只有人类才能解答。由于计算机无法解答CAPTCHA的问题,所以回答出问题的用户就可以被认为是人类。(百度百科)

在我们的网站中验证码是常用的手段之一今天给大家介绍一下kaptcha的和springboot一起使用的简单例子。

Kaptcha是谷歌放在github上的一个验证码jar包,我们可以简单配置属性实现验证码的验证功能。

kaptcha参数设置如下所示:

Constant 描述 默认值

kaptcha.border 图片边框,合法值:yes , no yes

kaptcha.border.color 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. black

kaptcha.border.thickness 边框厚度,合法值:>0 1

kaptcha.image.width 图片宽 200

kaptcha.image.height 图片高 50

kaptcha.producer.impl 图片实现类 com.google.code.kaptcha.impl.DefaultKaptcha

kaptcha.textproducer.impl 文本实现类 com.google.code.kaptcha.text.impl.DefaultTextCreator

kaptcha.textproducer.char.string 文本集合,验证码值从此集合中获取 abcde2345678gfynmnpwx

kaptcha.textproducer.char.length 验证码长度 5

kaptcha.textproducer.font.names 字体 Arial, Courier

kaptcha.textproducer.font.size 字体大小 40px.

kaptcha.textproducer.font.color 字体颜色,合法值: r,g,b 或者 white,black,blue. black

kaptcha.textproducer.char.space 文字间隔 2

kaptcha.noise.impl 干扰实现类 com.google.code.kaptcha.impl.DefaultNoise

kaptcha.noise.color 干扰颜色,合法值: r,g,b 或者 white,black,blue. black

kaptcha.obscurificator.impl 图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy com.google.code.kaptcha.impl.WaterRipple

kaptcha.background.impl 背景实现类 com.google.code.kaptcha.impl.DefaultBackground

kaptcha.background.clear.from 背景颜色渐变,开始颜色 light grey

kaptcha.background.clear.to 背景颜色渐变,结束颜色 white

kaptcha.word.impl 文字渲染器 com.google.code.kaptcha.text.impl.DefaultWordRenderer

kaptcha.session.key session key KAPTCHA_SESSION_KEY

kaptcha.session.date session date KAPTCHA_SESSION_DATE

首先springboot简单项目

然后添加 kaptcha 的maven依赖

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


总体思路:

1. 创建bean 并注册(springboot有两种注册,xml 和java)

2. Controller 中注入bean

3. 添加请求方法 调用bean 返回图片

4. 前段显示

实现代码

1.创建简单的springboot项目

2.添加maven依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>

<groupId>com.lushunde.springboot</groupId>
<artifactId>springboot-kaptcha</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent> <!-- 默认的父pom -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
</parent>
<name>springboot-kaptcha</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf模板jar,是很不错的html数据传递取值,类似jsp的jstl  -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- 验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

<!--maven的打包插件 -->
<build>
<!-- 配置java版本 不配置的话默认父类配置的是1.6 -->
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>


2.添加 kaptcha 的 图片配置 生成图片的bean。两种方法(都会提供,选择一种既可)

xml 配置

java配置bean

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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:gfe="http://www.springframework.org/schema/gemfire"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd" default-lazy-init="true">

<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">yes</prop>
<prop key="kaptcha.border.color">105,179,90</prop>
<prop key="kaptcha.textproducer.font.color">blue</prop>
<prop key="kaptcha.image.width">150</prop>
<prop key="kaptcha.image.height">50</prop>
<prop key="kaptcha.textproducer.font.size">40</prop>
<prop key="kaptcha.session.key">code</prop>
<prop key="kaptcha.textproducer.char.length">4</prop>
<prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>

</beans>


java代码

package com.lushunde.springboot.kaptcha.common;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

@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", "yes");
properties.setProperty("kaptcha.border.color", "105,179,90");
properties.setProperty("kaptcha.textproducer.font.color", "blue");
properties.setProperty("kaptcha.image.width", "110");
properties.setProperty("kaptcha.image.height", "40");
properties.setProperty("kaptcha.textproducer.font.size", "30");
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;
}
}


3.添加html文件

<form action="imgvrifyControllerDefaultKaptcha">
<input type="text" name="vrifyCode" />  <img alt="验证码" onclick = "this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha" />
</br>  <input type="submit" value="提交"></input>
</form>


4.编辑login处理逻辑

package com.lushunde.springboot.kaptcha.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.RespectBinding;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.impl.DefaultKaptcha;
@Controller
public class LoginController {
@Autowired
private DefaultKaptcha captchaProducer;

/**
* 获取验证码 的 请求路径
* @param httpServletRequest
* @param httpServletResponse
* @throws Exception
*/
@RequestMapping("/defaultKaptcha")
public void defaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception{
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
//生产验证码字符串并保存到session中
String createText = captchaProducer.createText();
httpServletRequest.getSession().setAttribute("vrifyCode", createText);
//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge = captchaProducer.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();
}

/**
* 验证的方法
* @param httpServletRequest
* @param httpServletResponse
* @return
*/
@RequestMapping("/imgvrifyControllerDefaultKaptcha")
public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
ModelAndView andView = new ModelAndView();
String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
String parameter = httpServletRequest.getParameter("vrifyCode");
System.out.println("Session  vrifyCode "+captchaId+" form vrifyCode "+parameter);

if (!captchaId.equals(parameter)) {
andView.addObject("info", "错误的验证码");
andView.setViewName("index");
} else {
andView.addObject("info", "登录成功");
andView.setViewName("succeed");
}
return andView;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: