使用 SpringBoot + kaptcha 生成、校对 验证码
2018年03月12日 00:28:23 larger5 阅读数:2966更多
所属专栏: SpringBoot
版权声明:有问题欢迎留言,转载请声明出处 https://blog.csdn.net/larger5/article/details/79522105
一、前言
验证码这么常见,想必不用多说了。最近做项目要用到验证码,也参考了网上很多方法,唯有下面方法感觉是最简单的,使用的是 Google 的 kaptcha 框架。
二、功能演示
1、git 图说明:
①点击验证码图片会切换验证码图片
②验证码输入错误会提示输入错误,重新输入新的验证码
③输入验证码正确跳转到成功界面
三、代码
2018.7.14 更新,代码已经放到github上了: https://github.com/larger5/Kaptcha.git
1、代码结构
2、pom
(SpringBoot+thymeleaf+web+kaptcha )
注意引入 kaptcha 的 Maven 依赖
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
3、KaptchaConfig
即 kaptcha 的配置文件
package com.cun.conf;
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", "red");
// 图片宽
properties.setProperty("kaptcha.image.width", "110");
// 图片高
properties.setProperty("kaptcha.image.height", "40");
// 字体大小
properties.setProperty("kaptcha.textproducer.font.size", "30");
// session key
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
4、KaptchaController
验证码控制层
package com.cun.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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.google.code.kaptcha.impl.DefaultKaptcha;
@Controller
public class KaptchaController {
/**
* 1、验证码工具
*/
@Autowired
DefaultKaptcha defaultKaptcha;
/**
* 2、生成验证码
* @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 = defaultKaptcha.createText();
httpServletRequest.getSession().setAttribute("rightCode", 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();
}
/**
* 3、校对验证码
* @param httpServletRequest
* @param httpServletResponse
* @return
*/
@RequestMapping("/imgvrifyControllerDefaultKaptcha")
public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
ModelAndView andView = new ModelAndView();
String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
String tryCode = httpServletRequest.getParameter("tryCode");
System.out.println("rightCode:"+rightCode+" ———— tryCode:"+tryCode);
if (!rightCode.equals(tryCode)) {
andView.addObject("info", "错误的验证码");
andView.setViewName("index");
} else {
andView.addObject("info", "登录成功");
andView.setViewName("success");
}
return andView;
}
@RequestMapping("/toIndex")
public String toIndex() {
return "index";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
5、application.yml SpringBoot 核心配置文件
server:
port: 80
context-path: /
- 1
- 2
- 3
6、主界面 index.html
<!DOCTYPE html>
<!-- thymeleaf 提示功能 -->
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8"></meta>
<title>hello</title>
<!-- 引入BootStrap -->
<link rel="stylesheet" href="../bootstrap3/css/bootstrap-theme.min.css" />
<link rel="stylesheet" href="../bootstrap3/css/bootstrap.min.css" />
<script type="text/javascript" src="../bootstrap3/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="../bootstrap3/js/bootstrap.min.js"></script>
</head>
<style type="text/css">
body {
padding: 10px
}
</style>
<body>
<!-- 提示 -->
<h3 th:text="${info}"></h3>
<div>
<!-- 后面添加参数起到清除缓存作用 -->
<img alt="验证码" onclick="this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha" />
</div>
<form action="imgvrifyControllerDefaultKaptcha" >
<input type="text" name="tryCode" />
<input type="submit" value="提交" class="btn btn-success"></input>
</form>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
7、验证成功界面 success.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"></meta>
<title>验证成功</title>
</head>
<body>
<h1>验证成功</h1>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
三、小结
1、参考文章
2、感受
验证码这种东西,一切都是固定套路,会用就行
四、其他(2018.5.11更新)
上面那个 Controller 在前后端分离时,应把验证码值+IP,存到 数据库中,以减少前端的业务逻辑,否则就等让前端带 cookie 等琐碎的操作(前端专注于视觉建设,不要参与业务逻辑)
package com.cun.controller;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cun.dao.CodeDao;
import com.cun.entity.Code;
import com.cun.entity.User;
import com.cun.util.Json;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@RestController
@RequestMapping("/Kaptcha")
@EnableSwagger2
public class KaptchaController {
@Autowired
private CodeDao codeDao;
/**
* 1、验证码工具
*/
@Autowired
DefaultKaptcha defaultKaptcha;
/**
* 2、生成验证码
* @param httpServletRequest
* @param httpServletResponse
* @return
* @throws Exception
*/
@ApiOperation(value = "生成验证码", notes = "")
@GetMapping("/defaultKaptcha")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws Exception {
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
String rightCode="";
try {
// 生产验证码字符串并保存到session中
rightCode = (String)defaultKaptcha.createText();
// httpServletRequest.getSession().setAttribute("rightCode", rightCode);
// 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge = defaultKaptcha.createImage(rightCode);
ImageIO.write(challenge, "jpg", jpegOutputStream);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return ;
}
// 将正确验证码值+IP,保存到数据库中
String remoteAddr = httpServletRequest.getRemoteAddr();
Code code = new Code();
code.setDate(new Date());
code.setRightCode(rightCode);
code.setAdressIp(remoteAddr);
codeDao.save(code);
System.out.println(code);
System.out.println(rightCode);
System.out.println(remoteAddr);
// 定义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();
}
/**
* 3、校对验证码
* @param httpServletRequest
* @param httpServletResponse
* @return
*/
@ApiOperation(value = "校对验证码")
@GetMapping("/imgvrifyControllerDefaultKaptcha")
public Map<String, Object> imgvrifyControllerDefaultKaptcha(String tryCode,HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
String remoteAddr = httpServletRequest.getRemoteAddr();
Code testCode = codeDao.testCode(remoteAddr);
if(testCode.getRightCode().equals(tryCode)) {
return Json.success(testCode);
}else {
return Json.fail();
}
/*
String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
System.out.println("rightCode:" + rightCode + " ———— tryCode:" + tryCode);
if (!rightCode.equals(tryCode)) {
return Json.fail();
} else {
return Json.success(rightCode);
}
*/
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
code 实体类
package com.cun.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import io.swagger.annotations.ApiModelProperty;
@Entity
@Table(name = "t_code")
public class Code {
@Id
@GeneratedValue
@ApiModelProperty(value = "验证码主键id")
private Integer id;
@Column(length = 100)
private String rightCode;
private String addressIp;
private Date date;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRightCode() {
return rightCode;
}
public void setRightCode(String rightCode) {
this.rightCode = rightCode;
}
public String getAdressIp() {
return addressIp;
}
public void setAdressIp(String addressIp) {
this.addressIp = addressIp;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}