前言:小程序發送短信驗證碼須要在後臺儲存生成的code,一次會話應放入session中,請求頭部發送sessionId驗證爲同一sessionjson
後臺:小程序
/** * 得到sessionId */ @RequestMapping("/getSessionId") @ResponseBody public Object getSessionId(HttpServletRequest request) { try { HttpSession session = request.getSession(); return session.getId(); } catch (Exception e) { e.printStackTrace(); } return null; }
/** * 發送短信驗證碼 * @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; }
前臺發送請求驗證時一樣須要攜帶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相比較session
這裏設置的失效時間爲5分鐘app