首页 > 其他分享 >注册案例[session]

注册案例[session]

时间:2023-02-01 10:33:16浏览次数:37  
标签:String checkCode request 验证码 案例 session 注册

注册功能:保存用户信息到数据库
验证码功能:
展示验证码:展示验证码图片,并可以点击切换
校验验证码:验证码填写不正确,则注册失败

注册案例 -- 校验验证码
判断程序生成的验证码 和 用户输入的验证码 是否一样,如果不一样,则阻止注册
验证码图片访问和提交注册表单是两次请求,所以要将程序生成的验证码存入Session中

 

验证码存入session

  @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 生成验证码
        ServletOutputStream os = response.getOutputStream();
        String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);

        // 存入Session
        HttpSession session = request.getSession();
        session.setAttribute("checkCodeGen",checkCode);

    }

 保存表单获取session

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //1. 获取用户名和密码数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");

        // 程序生成的验证码,从Session获取
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");

        // 比对
        if(!checkCodeGen.equalsIgnoreCase(checkCode)){

            request.setAttribute("register_msg","验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request,response);

            // 不允许注册
            return;
        }

  

标签:String,checkCode,request,验证码,案例,session,注册
From: https://www.cnblogs.com/popopopopo/p/17081745.html

相关文章