温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

利用java实现验证码生成并完成验证

发布时间:2020-11-17 16:33:40 来源:亿速云 阅读:154 作者:Leah 栏目:编程语言

利用java实现验证码生成并完成验证?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

java 制作验证码并进行验证实例详解

在注册、登录的页面上经常会出现验证码,为了防止频繁的注册或登录行为。下面是我用java制作的一个验证码,供初学者参考,做完验证码之后,我们可以用ajax进行验证码验证。

功能一:验证码制作的代码,点击图片,验证码进行更换

/**
 * 显示验证码图片
 */
public void showCheckCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  // 调用业务逻辑
  String checkCode = getCheckCode();
  //将验证码字符放入session域对象中
  req.getSession().setAttribute("checkCode", checkCode);

  //图片宽
  int width = 80;
  //图片高
  int height = 30;
  //在内存中创建一个图片
  BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
  //获取一个画笔
  Graphics g = image.getGraphics();
  //设置画笔颜色,用灰色做背景
  g.setColor(Color.GRAY);
  //向Image中填充灰色
  g.fillRect(0,0,width,height);

  Random r = new Random();

  //设置3条干扰线
  for (int i = 0; i < 3; i++) {
    g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
    g.drawLine(r.nextInt(80), r.nextInt(30), r.nextInt(80), r.nextInt(80));
  }

  //设置验证码字符串的颜色
  g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
  //设置字符的大小
  g.setFont(new Font("黑体",Font.BOLD,24));
  //在图片中写入验证码字符串
  g.drawString(checkCode,15,20);
  //将Image对象以PNG格式输出给所有的客户端
  ImageIO.write(image,"PNG",resp.getOutputStream());
}

/**
 * 获取4位验证码中的4位随机字符串
 */
public static String getCheckCode(){
  //验证码中的字符由数字和大小写字母组成
  String code = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
  Random r = new Random();
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < 4; i++) {
    sb.append(code.charAt(r.nextInt(code.length())));
  }

  return sb.toString();
}

jsp页面

<script type="text/javascript">
  function changeCodeImage(img){
    img.src = "${pageContext.request.contextPath}/UserServlet&#63;method=showCheckCode&time="+new Date().getTime();
  }

</script>

 <div class="form-group">
  <label for="date" class="col-sm-2 control-label">验证码</label>
  <div class="col-sm-3">
   <input type="text" class="form-control" id="writeCode" onkeyup="checkCodeMethod(this.value)" >

  </div>
  <div class="col-sm-2">
  <img src="${pageContext.request.contextPath}/UserServlet&#63;method=showCheckCode" id="checkCodeImage" title="点击换一张" onclick="changeCodeImage(this)" />
  </div>
  <span id="checkCodeSpan"></span>
 </div>

功能二:ajax动态验证验证码

/**
 * 验证验证码
 */
public void checkCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

  //获取从页面中接收到的验证码参数
  String checkCode = req.getParameter("checkCode");
  //从session域对象中获取验证码
  String sessionCode = (String) req.getSession().getAttribute("checkCode");
  //判断验证码是否相同
  if (checkCode.equalsIgnoreCase(sessionCode)) {
    resp.getWriter().print(true);
  }else {
    resp.getWriter().print(false);
  }

jsp页面

<script type="text/javascript">
  function changeCodeImage(img){
    img.src = "${pageContext.request.contextPath}/UserServlet&#63;method=showCheckCode&time="+new Date().getTime();
  }

  function checkCodeMethod(code){
    $.get("${pageContext.request.contextPath}/UserServlet&#63;method=checkCode", 
        { checkCode: code}, 
        function(data){
          if (data == 'true') {
            document.getElementById("checkCodeSpan").innerHTML = "<font>验证码正确!</font>";
          }else {
            document.getElementById("checkCodeSpan").innerHTML = "<font>验证码错误!</font>";
          }
        }
      );
  }

</script>

 <div class="form-group">
  <label for="date" class="col-sm-2 control-label">验证码</label>
  <div class="col-sm-3">
   <input type="text" class="form-control" id="writeCode" onkeyup="checkCodeMethod(this.value)" >

  </div>
  <div class="col-sm-2">
  <img src="${pageContext.request.contextPath}/UserServlet&#63;method=showCheckCode" id="checkCodeImage" title="点击换一张" onclick="changeCodeImage(this)" />
  </div>
  <span id="checkCodeSpan"></span>
 </div>

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI