Knowledge supplement:
toString()
method is used to return a Number object value represented by a string.
equalsIgnoreCase()
The method is used to compare a string with the specified object, regardless of case.
Verification method:
First, you need to obtain the verification code object entered by the user, and then determine whether the verification code is empty. If it is not empty, use the "toString()" method Obtain the "Number" object value represented by the verification code, and finally compare the verification code object value with the specified object to determine whether it is correct.
Sample code:
/** * Author: SamGroves * * Description: 获得前端输入验证码的验证 * * Date: 2017/8/26 */@Controller@RequestMapping("/api")public class VerifyController extends BaseController{ /** * @param checkCode 前端用户输入返回的验证码 * 参数若需要,自行添加 */ @RequestMapping(value = "/verify") @ResponseBody public String checkcode(HttpServletRequest request, HttpSession session, String checkCode) throws Exception { // 获得验证码对象 Object cko = session.getAttribute("simpleCaptcha"); if (cko == null) { request.setAttribute("errorMsg", "请输入验证码!"); return "请输入验证码!"; } String captcha = cko.toString(); // 判断验证码输入是否正确 if (StringUtils.isEmpty(checkCode) || captcha == null || !(checkCode.equalsIgnoreCase(captcha))) { request.setAttribute("errorMsg", "验证码错误!"); return "验证码错误,请重新输入!"; // 验证码有效时长为1分钟 Date now = new Date(); Long codeTime = Long.valueOf(session.getAttribute("codeTime") + ""); } else if ((now.getTime() - codeTime) / 1000 / 60 > 1) { request.setAttribute("errorMsg", "验证码已失效,请重新输入!"); return "验证码已失效,请重新输入!"; } else { // 在这里可以处理自己需要的事务,比如验证登陆等 return "验证通过!"; } }}
Recommended tutorial: Getting started with java development
The above is the detailed content of How to verify whether the image verification code is correct in JAVA. For more information, please follow other related articles on the PHP Chinese website!