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和錯誤歡迎各位在評論區留言指正。
(工具類代碼和部分代碼來源於網絡,如有侵權,請聯繫我刪除)