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(); }