验证码的作用
验证码设计的主要目的以及它最大的作用也就是防止不法分子在短时间内用机器批量的重复操作。
kaptcha验证码显示
添加依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
创建配置类KaptchaConfig
- 注意不要导错包
package com.rm.config;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha(){
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 图片边框
properties.put("kaptcha.border", "no");
// 字体颜色
properties.put("kaptcha.textproducer.font.color", "black");
// 图片宽
properties.put("kaptcha.image.width", "160");
// 图片高
properties.put("kaptcha.image.height", "40");
// 字体大小
properties.put("kaptcha.textproducer.font.size", "30");
// 验证码长度
properties.put("kaptcha.textproducer.char.length", "5");
// 字体
properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
创建Controller层 KaptchaController
KaptchaController
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
@Controller
public class KaptchaController {
@Autowired
private DefaultKaptcha captchaProducer;
@GetMapping("/kaptcha")
public void defaultKaptcha(
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws Exception {
byte[] captchaOutputStream;
ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
try {
//生产验证码字符串并保存到session中
String verifyCode = captchaProducer.createText();
httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
BufferedImage challenge = captchaProducer.createImage(verifyCode);
ImageIO.write(challenge, "jpg", imgOutputStream);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
captchaOutputStream = imgOutputStream.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(captchaOutputStream);
responseOutputStream.flush();
responseOutputStream.close();
}
@GetMapping("/click")
public String t(){
return "kaptcha";
}
}
kaptcha.html
- 点击一次更换一次图片
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>验证码显示</title>
</head>
<body>
<img src="/kaptcha" onclick="this.src='/kaptcha?d='+new Date()*1" />
</body>
</html>
- 每点击一次都会发送一个新的请求
验证码的输入和验证
验证码的显示完成后,我们接下来要做的就是对用户输入的验证码进行比对和验证,因为一般的做法就是后端生成后会对当前生成的验证码进行保存(可能是 session 中、或者缓存中、或者数据库中),之后显示到前端页面,用户在看到验证码之后在页面对应的输入框中填写验证码,之后才向后端发送请求,而后端再接到请求后会对用户输入的验证码进行验证,如果不对的话则不会进行后续操作,接下来我们来简单的实现一下这个流程。
Controller层
- 新添加一个方法
@GetMapping("/verify")
@ResponseBody
public String verify(@RequestParam("code") String code, HttpSession session) {
if (StringUtils.isEmpty(code)) {
return "验证码不能为空";
}
String kaptchaCode = session.getAttribute("verifyCode") + "";
if (StringUtils.isEmpty(kaptchaCode) || !code.equals(kaptchaCode)) {
return "验证码错误";
}
return "验证成功";
}
//映射路径
@GetMapping("/click")
public String t(){
return "verify";
}
前端
- 导入jquery
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
verify.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>验证码测试</title>
</head>
<body>
<img src="/kaptcha" onclick="this.src='/kaptcha?d='+new Date()*1" />
<input type="text" maxlength="5" id="code" placeholder="请输入验证码" />
<button id="verify">验证</button>
</body>
<script src="webjars/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#verify').click(function () {
var code = $('#code').val();
$.ajax({
type: 'GET', //方法类型
url: '/verify?code=' + code,
success: function (result) {
alert(result);
},
error: function () {
alert('请求失败');
},
});
});
});
</script>
</html>