技術:springboot+kaptcha+session
概述
場景介紹 驗證碼,用於web網站。用戶點擊驗證碼圖片后,生成驗證碼。提交后,用戶輸入驗證碼和Session驗證碼,進行校驗。
詳細
一、目錄結構

二、功能講解
(1)驗證碼配置文件
打開KaptchaConfig.java
@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", "black");
//邊框厚度
properties.setProperty("kaptcha.border.thickness", "1");
// 圖片寬
properties.setProperty("kaptcha.image.width", "200");
// 圖片高
properties.setProperty("kaptcha.image.height", "50");
//圖片實現類
properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");
//文本實現類
properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");
//文本集合,驗證碼值從此集合中獲取
properties.setProperty("kaptcha.textproducer.char.string", "01234567890");
//驗證碼長度
properties.setProperty("kaptcha.textproducer.char.length", "4");
//字體
properties.setProperty("kaptcha.textproducer.font.names", "宋體");
//字體顏色
properties.setProperty("kaptcha.textproducer.font.color", "black");
//文字間隔
properties.setProperty("kaptcha.textproducer.char.space", "5");
//干擾實現類
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");
//干擾顏色
properties.setProperty("kaptcha.noise.color", "blue");
//干擾圖片樣式
properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
//背景實現類
properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");
//背景顏色漸變,結束顏色
properties.setProperty("kaptcha.background.clear.to", "white");
//文字渲染器
properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
詳細配置說明:https://blog.csdn.net/elephantboy/article/details/52795309
(2)生成驗證碼方法
打開CommonUtil.java,這是一個公共方法
public class CommonUtil {
/**
* 生成驗證碼圖片
* @param request 設置session
* @param response 轉成圖片
* @param captchaProducer 生成圖片方法類
* @param validateSessionKey session名稱
* @throws Exception
*/
public static void validateCode(HttpServletRequest request, HttpServletResponse response, DefaultKaptcha captchaProducer, String validateSessionKey) throws Exception{
// Set to expire far in the past.
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
// create the text for the image
String capText = captchaProducer.createText();
// store the text in the session
request.getSession().setAttribute(validateSessionKey, capText);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}
(3)驗證碼控制類
打開MainController.java
@Controller
public class MainController {
@Resource
private DefaultKaptcha captchaProducer;
@RequestMapping(value = {"/"})
public String index() {
return "/index";
}
/**
* 登錄驗證碼SessionKey
*/
public static final String LOGIN_VALIDATE_CODE = "login_validate_code";
/**
* 登錄驗證碼圖片
*/
@RequestMapping(value = {"/loginValidateCode"})
public void loginValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
CommonUtil.validateCode(request,response,captchaProducer,LOGIN_VALIDATE_CODE);
}
/**
* 檢查驗證碼是否正確
*/
@RequestMapping("/checkLoginValidateCode")
@ResponseBody
public HashMap checkLoginValidateCode(HttpServletRequest request,@RequestParam("validateCode")String validateCode) {
String loginValidateCode = request.getSession().getAttribute(LOGIN_VALIDATE_CODE).toString();
HashMap<String,Object> map = new HashMap<String,Object>();
if(loginValidateCode == null){
map.put("status",null);//驗證碼過期
}else if(loginValidateCode.equals(validateCode)){
map.put("status",true);//驗證碼正確
}else if(!loginValidateCode.equals(validateCode)){
map.put("status",false);//驗證碼不正確
}
map.put("code",200);
return map;
}
}
(4)前端頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SpringBoot 生成驗證碼</title>
<script type="text/javascript" src="/js/jquery/jquery-3.3.1.min.js"></script>
<script type='text/javascript'>
$(function () {
$("#validateCode").keyup(function(){
checkLoginValidateCode($(this).val());
});
});
function uploadLoginValidateCode() {
$("#loginValidateCode").attr("src","/loginValidateCode?random="+new Date().getMilliseconds());
}
function checkLoginValidateCode(validateCode) {
var error = $("#validateCode").parent().next();
if(validateCode != null && validateCode != ""){
$.ajax({
type: "POST",
async:false,
url: "/checkLoginValidateCode?validateCode="+validateCode,
success : function(json) {
if(json != null && json.code == 200 && json.status != null) {
if (json.status == true) {
error.html("恭喜你驗證碼,正確!!!!!");
} else if(json.status == false){
error.html("驗證碼錯誤,請重新輸入");
}else{
error.html("驗證碼過期,請重新輸入");
uploadLoginValidateCode();
}
}
return false;
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("服務器錯誤!狀態碼:"+XMLHttpRequest.status);
// 狀態
console.log(XMLHttpRequest.readyState);
// 錯誤信息
console.log(textStatus);
return false;
}
});
}else{
error.html("請輸入驗證碼!");
}
}
</script>
</head>
<body>
驗證碼: <img id="loginValidateCode" height="40" width="150" style="cursor: pointer;" src="/loginValidateCode" onclick="uploadLoginValidateCode();">
<p>
你輸入的內容:<input type="text" id="validateCode" name="validateCode" />
</p>
<p style="color: red"></p>
</body>
</html>
三、運行




吐槽環節:百度的搜java 驗證碼,太坑爹了,各種各樣復雜,非常不通用,還有一些不能運行的。忍不了忍不了,自己整合一個,最后找到google kaptcha 工具 vary good !!!
謝謝大家觀看~
