securityCodeUtils.rar是java生成图像验证码的工具类代码,该工具类可以生成gif气泡验证码和jpg气泡验证码两种验证码,开发者不需要关注具体实现过程,只需要创建GifCaptcha、SpecCaptcha对象的,即可轻松生成。
示例1:动态验证码
示例2:图片验证码
1.将securityCodeUtils.rar压缩包解压到公共的项目公共目录下;
2.创建一个controller为前端提供接口,调用接口时生成验证码值securityCode将存入session,验证码gif/jpg将直接传给前端。
@RestController
@RequestMapping("common/securityCodeService")
@Api(description = "生成图像验证码",tags = {"公共模块-生成图像验证码"})
public class SecurityCodeController {
/**
* 获取验证码(Gif版本)
* @Auothor qishuai
* @param response
*/
@RequestMapping(value="getGifCode",method= RequestMethod.GET)
@ApiOperation(value = "获取Gif验证码", notes = "获取Gif验证码")
public void getGifCode(HttpServletResponse response, HttpServletRequest request){
try {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/gif");
/**
* gif格式动画验证码
* 宽,高,位数。
*/
Captcha captcha = new GifCaptcha(146,33,4);
//输出
captcha.out(response.getOutputStream());
HttpSession session = request.getSession(true);
//存入Session
session.setAttribute("securityCode",captcha.text().toLowerCase());
} catch (Exception e) {
e.printStackTrace();
// LoggerUtils.fmtError(getClass(),e, "获取验证码异常:%s",e.getMessage());
}
}
/**
* 获取验证码(jpg版本)
* @Auothor qishuai
* @param response
*/
@RequestMapping(value="getJPGCode",method=RequestMethod.GET)
@ApiOperation(value = "获取jpg验证码", notes = "获取jpg验证码")
public void getJPGCode(HttpServletResponse response,HttpServletRequest request) {
try {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpg");
/**
* jgp格式验证码
* 宽,高,位数。
*/
Captcha captcha = new SpecCaptcha(146, 33, 4);
//输出
captcha.out(response.getOutputStream());
HttpSession session = request.getSession(true);
//存入Session
session.setAttribute("securityCode", captcha.text().toLowerCase());
} catch (Exception e) {
e.printStackTrace();
// LoggerUtils.fmtError(getClass(),e, "获取验证码异常:%s",e.getMessage());
}
}
}
3.前端将用户填写的验证码传到后端,后端只需要从session中取出验证码,与前端传来的验证码值进行比较即可。比较结束无论是否通过都要从session中删除已存在的验证码值,让前端重新生成新的验证码。
//验证码校验
JSONObject jsonObject = rawRequest.getJOject();
String securityCode = jsonObject.getString("securityCode"); //用户输入的验证码
HttpSession session = httpServletRequest.getSession();
String code = (String) session.getAttribute("securityCode");
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(securityCode) || !code.equalsIgnoreCase(securityCode)) {
session.removeAttribute("securityCode");
return new RawResponse("403", "验证码错误,请重新输入!");
} else {
session.removeAttribute("securityCode");
}
4.工具类下载地址:https://download.csdn.net/download/qisoft1213/12092495
5.以上均为个人开发过程中的经验总结,如有bug和错误欢迎各位在评论区留言指正。
(工具类代码和部分代码来源于网络,如有侵权,请联系我删除)