Java之使用Hutool验证码

Servlet使用Hutool验证码

官网 https://hutool.cn/docs/#/captcha/%E6%A6%82%E8%BF%B0 


private void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //定义图形验证码的长和宽
    LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,40);
    //图形验证码写出,可以写出到文件,也可以写出到流
    //lineCaptcha.write("d:/6/line.png");

    lineCaptcha.write(response.getOutputStream());
    //输出code
    logger.info("这是验证码{}",lineCaptcha.getCode());

    Console.log(lineCaptcha.getCode());

    //存入session
    request.getSession().setAttribute("captchaCode",lineCaptcha.getCode());
}

session中的code与前端传过来的code值比较,如果一样。。。(== 对比是引用类型地址 ,字符串对比应该用equals)

String code = request.getParameter("code");
String captchaCode = request.getSession().getAttribute("captchaCode").toString();
if(code.equals(captchaCode)){
    ...
}

前端调验证码接口 映射/login,点击 将自己的src 添加一个& 重新发起请求 点击切换验证码

<img src="/login?action=getCode" onclick ="this.src = this.src+'&'" id="codeImg">

JS 自动刷新验证码 修改src 属性 改为当前src加一个&

$('#codeImg').attr('src',$('#codeImg').attr('src')+'&');

猜你喜欢

转载自blog.csdn.net/LvFengQi/article/details/114046533