sessionId在小程序中的妙用

前言:小程序发送短信验证码需要在后台储存生成的code,一次会话应放入session中,请求头部发送sessionId验证为同一session

1.页面一加载就从后台获取sessionId,储存在本地缓存中

 

 后台:

    /**
     * 获得sessionId
     */
    @RequestMapping("/getSessionId")
    @ResponseBody
    public Object getSessionId(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            return session.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

2.发送验证码时在头部携带 "Cookie": sessionId,然后将电话号码传给后台

    /**
     * 发送短信验证码
     * @param phoneNum 接收手机号码
     */
    @RequestMapping(value = "/sendMsg",method = RequestMethod.POST)
    public Object sendSms(HttpServletRequest request, String phoneNum) {
        try {
            JSONObject json = null;
            //生成6位验证码
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            AliyunMessage.sendMessage(phoneNum,verifyCode);
            //将验证码存到session中,同时存入创建时间
            //以json存放,这里使用的是阿里的fastjson
            HttpSession session = request.getSession();
            json = new JSONObject();
            json.put("verifyCode", verifyCode);
            json.put("createTime", System.currentTimeMillis());
            // 将认证码存入SESSION
            request.getSession().setAttribute("verifyCode", json);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

3.验证验证码

前台发送请求验证时同样需要携带sessionId的头部

    /**
     * 验证
     */
    @RequestMapping(value = "/verification",method = RequestMethod.POST)
    @ResponseBody
    public Object addinfo(
            HttpServletRequest request,
            String phoneNum,
            String code) {
        JSONObject json = (JSONObject)request.getSession().getAttribute("verifyCode");
        if(!json.getString("verifyCode").equals(code)){
            return "验证码错误";
        }
        if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
            return "验证码过期";
        }
        return "success";
    }

从session中获取code,然后与传过来的code相比较

这里设置的失效时间为5分钟

posted @ 2019-10-12 14:31  梧桐树master  阅读(1668)  评论(0编辑  收藏  举报