final HttpSession httpSession=request.getSession(); final HttpSession httpSession=request.getSession(); httpSession.setAttribute(Constants.YXCODE1, code1); try { //TimerTask实现5分钟后从session中删除checkCode final Timer timer=new Timer(); timer.schedule(new TimerTask() { @Override public void run() { String yxcode1 = (String) httpSession.getAttribute(Constants.YXCODE1); if(StringUtils.isNotEmpty(yxcode1)){ //确保清除不出错 httpSession.removeAttribute(Constants.YXCODE1); } timer.cancel(); } },5*60*1000); } catch (Exception e) { e.printStackTrace(); }