//服務端設置Session屬性session.setAttribute("user", username);//客戶端接收SessionObject obj = session.getAttribute("user"); //判斷是否為空,不是空就輸出 if(obj==null){ //如果為空就提示用戶登錄 %> <%}else{ //不為空就輸出用戶名,和歡迎信息 out.Session清理機制
在服務端設置過期時間
//設置服務器端session過期日期(單位為:秒),如設置為10秒 session.setMaxInactiveInterval(10);在客戶端中設置<% //在客戶端設置session,如點擊注銷之后,直接設置session過期 //第一種刪除session中的數據session.removeAttribute("user");//第二種 或者直接使用session過期 session.invalidate();//以2選一 //重定向主頁 response.sendRedirect("index.jsp");%>在tomcat中直接設置,在tomact中設置時間為分鐘conf/web.xml中<!--在最下方的</webapp>之前添加,并設置為10分種--><session-config> <session-timeout>10</session-timeout> </session-config></web-app>Session過程cookie
在服務端設置Cookie
//聲明cookie變量,并添加要保存的參數和值如:用戶名 Cookie cookie = new Cookie("user",username); //設置cookie的有效時間以秒為單位60秒*60秒int類型的值 cookie.setMaxAge(60*60); //將cookies對象發回客戶端 response.addCookie(cookie);在客戶端接收cookie,
//接收cookies返回值為cookies的數組 Cookie [] cookies = request.getCookies(); //聲明字符串變量用來接收cookies的值 String user=""; for(int i=0;i<cookies.length;i++){ //獲取cookies的名字,并判斷如果是服務端的名稱 if(cookies[i].getName().equals("user")){ //將cookes的值賦為字符串變量 user=cookies[i].getValue(); } }application對象計數器的實現原理
<% //計數器//取出application屬性中的count值為object值 Object count = application.getAttribute("count");//判斷是否為空if(count==null){ //如果是空,表示第一次訪問將值設置為1 application.setAttribute("count", new Integer(1));}else{ //不是空,則將結果+1 Integer i=(Integer)count; application.setAttribute("count", i.intValue()+1);}Integer iCount=(Integer)application.getAttribute("count");out.println("訪問: "+iCount+"次");%><%//獲取application對象的count屬性值 Object count = application.getAttribute("count");//判斷是否為空if(count==null){ //為空就設置為1 application.setAttribute("count", new Integer(1)); }else{ //不空就取值+1 application.setAttribute("count", (Integer)count+1);} Integer icount = (Integer)application.getAttribute("count"); out.println("訪問了: "+icount+"次");%>Request、Session和Application的區別Request:中存儲的數據僅在一個請求中可用
Session:中存儲的數據在一個會話有效期內可用
Application:中存儲的數據在整個WEB項目中可用,直到WEB服務器停止運行
新聞熱點
疑難解答