描述
1,首先验证码是一张图片,页面登录页面要以图片的形式来接受 即 <img> 标签
2,图片生成 是通过A-Z a-z 1-9 这些字母数字组成,以4位数的验证码来说,要先生成随机四位A-Z a-z 1-9编码,并且把编码放到session 里,主要是用于跟用户输入的验证码进行比较
3,根据随机编码,设置宽 高 ,指定图片输出流 来完成堆图片
4,点击图片 调用生成图片的clntroller 进行图片更新
代码:
<div class="form-group"> 验证码:<input type="text" class="validcode1" name="validcode" id="validcode"/> <img src="" alt="验证码" id="codeYZ" class="validimg" οnclick="changeCode();"/>
//点击图片生成验证码 function changeCode(){ var imgObj = document.getElementById("codeYZ"); imgObj.src = "/login/ajaxCode?ran=" + Math.random(); } //页面初始化生生验证码 $(function () { var imgObj = document.getElementById("codeYZ"); imgObj.src = "/login/ajaxCode?ran=" + Math.random(); })
// 生成验证码 controller
def ajaxCode(){ String code = VerifyCodeUtil.generateVerifyCode(4) //四位随机编码 session.setAttribute(session.getId(),code) //放到session VerifyCodeUtil.outputImage(100,40,response.getOutputStream(),code) // 生成图片流 }
随机编码,生成图片流 参考我的另一篇文章
https://blog.csdn.net/lijinlong1989/article/details/90512320
输入验证码,进行校验,一般项目都会使用 安全框架进行 注册登录,权限等校验
本项目使用的是spring security 进行登录(常用还有shiro)
spring security 项目在登录验证中想获得额外数据(验证码) 通过继承WebAuthenticationDetails 来实现
//获取额外数据 类
CustomWebAuthenticationDetails extends WebAuthenticationDetails
private final String validcode; private final Boolean flag ;
validcode = request.getParameter("validcode") //获取用户输入的验证码 if(StringUtils.isNotBlank(validcode)){ validcode = validcode.toLowerCase() } String value = request.getSession().getAttribute(request.getSession().getId())//获取session 验证码 if(StringUtils.isNotBlank(value)){ value = value.toLowerCase() } System.out.print("validcode"+validcode+":value="+value) if(validcode.equals(value)){ request.getSession().removeAttribute(request.getSession().getId()) 如果true 删除sessionid (key 可以使session_业务类型) flag = true }else{ flag=false }
// 校验用户名密码是否正确 类 spring security
public class CustomAuthenticationProvider extends DaoAuthenticationProvider { protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { // 登录失败返回 验证码不正确 def customWebAuthenticationDetails = details as CustomWebAuthenticationDetails def user = userDetails as CustomUserDetails if(!customWebAuthenticationDetails.getFlag()){ throw new CustomCodeException("对不起验证码 不正确") } }
// 最后上传一张图
到此 验证码登录 完成