温馨提示×

温馨提示×

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

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

使用Session实现一个一次性的验证码登录功能

发布时间:2020-11-11 15:58:19 来源:亿速云 阅读:182 作者:Leah 栏目:编程语言

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

 验证码的实现原理:

在一个Servlet中生成验证,并把验证码上的数据保存在Session,用户提交验证码之后,会提交给另外一个Servlet程序。在获取用户提交数据的Servlet中的从Session中把验证码取出,在取出的同时从Session中把验证码删除。

1.注册页面:register.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>" rel="external nofollow" >
  <title>My JSP 'login.jsp' starting page</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">  
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <!--
  <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
  -->
  <script type="text/javascript">
    function _changImg(){
      document.getElementById("myimg").src = "/day11/checkImg&#63;" + new Date().getMilliseconds();
    }
  </script>
 </head>
 <body>
  <center>
    <form action="/day11/regist" method="post">
      <table>
        <tr>
          <td>用户名<font color="red">*</font></td>
          <td><input type="text" name="name"/></td>
        </tr>      
        <tr>
          <td>密码</td>
          <td><input type="password" name="password"/></td>
        </tr>                  
        <tr>
          <td>输入验证码</td>
          <td>
            <input type="text" name="form_checkcode" />
            <img  alt="" src="/day11/checkImg" id="myimg" onclick="_changImg();"/>
            <a href="javascript:void(0);" rel="external nofollow" onclick="_changImg();">看不清,换一张</a>
            <font color="red">${imgError }</font>
          </td>
        </tr>        
        <tr>
          <td><input type="submit" value="注册" /></td>
        </tr>
      </table>    
    </form>
  </center>
 </body>
</html>

2.生成验证码参考:cn.itcast.session.CheckImgServlet

public class CheckImgServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    int width = 120;
    int height = 40;
    // 先生成一张纸
    BufferedImage bufi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    // 画笔
    Graphics g = bufi.getGraphics();
    // 设置背景颜色
    // 修改画笔颜色
    g.setColor(Color.white);
    // 填充
    g.fillRect(0, 0, width, height);
    // 绘制边框
    // 设置边框颜色
    g.setColor(Color.red);
    // 画边框
    g.drawRect(0, 0, width - 1, height - 1);
    // 准备一些数据
    String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
    // 生成随机对象
    Random r = new Random();
    String checkcode = "";
    // 生成4个随机的数字
    for (int i = 0; i < 4; i++) {
      // 生成随机颜色
      g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
      // 设置字体
      g.setFont(new Font("宋体", Font.ITALIC, 25));
      String c = data.charAt(r.nextInt(data.length())) + "";
      g.drawString(c, 10 + (20 * i), 30);
      checkcode += c;
    }
    // 将生成的验证码放到 session中
    request.getSession().setAttribute("session_checkcode", checkcode);
    // 画干扰线
    for (int i = 0; i < 8; i++) {
      // 设置随机颜色
      g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
      // 画线 两点确定一线
      g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
    }
    // 将图片输出到浏览器
    ImageIO.write(bufi, "jpg", response.getOutputStream());
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  }
}

3.验证码的验证参考:cn.itcast.session.RegistServlet

public class RegistServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 校验验证码的有效性: 服务端生成的验证码 和 表单提交的验证码一致才算有效
    // 服务端生成的验证码 保存在 session容器中
    // 获得session中的验证码
    HttpSession session = request.getSession();
    String session_checkcode = (String) session.getAttribute("session_checkcode");
    // 使用完后,迅速清除session中验证码的属性
    session.removeAttribute("session_checkcode");
    // 获得表单提交的验证码
    String form_checkcode = request.getParameter("form_checkcode");
    // 判断什么是非法 如果非法,终止
    if (session_checkcode == null || !session_checkcode.equals(form_checkcode)) {
      // 说明验证码错误
      request.setAttribute("imgError", "验证码错误!");
      // 将request对象转发给 login.jsp
      request.getRequestDispatcher("/login.jsp").forward(request, response);
      // 结束当前方法
      return;
    }
    // 如果合法, 继续校验用户名和密码的有效
    String username = request.getParameter("username");
    String password = request.getParameter("password");
  }
}

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

向AI问一下细节

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

AI