需求, 前端获取后端验证码, 并且后端做判断处理是否相等
前端代码
<img id="codeImg" src="createCode">
src 的 createCode 指向后端 优化点击二维码再次发生改变
- $("#codeImg").click(function(){
- $("#codeImg").attr("src","createCode?r="+Math.random())
- })
后端做接收处理
- // 图片的宽度 图片的高度 验证码位数 干扰线的个数
- ValidateCode vs = new ValidateCode(100, 40, 4, 20);
- // 创建验证码
- vs.createCode();
- // 获取创建的验证码
- String code = vs.getCode();
- // 将验证码存储到 session 中
- request.getSession(false).setAttribute("validateCode", code);
- // 将验证码返回给前端页面
- vs.write(response.getOutputStream());
将验证码放到 session 做是否相等处理
- String vcode = request.getParameter("vlidateCode");
- if(!vcode.equalsIgnoreCase(code)) {
- JsonUtils.writeJsonUtils(0, "验证码错误", response);
- return false;
- }
来源: http://www.jianshu.com/p/b4f44616d1f9