JSP實現資料儲存(web基礎學習筆記四)

來源:互聯網
上載者:User

標籤:

session對象:

 

//服務端設定Session屬性session.setAttribute("user", username);//用戶端接收SessionObject obj = session.getAttribute("user");    //判斷是否為空白,不是空就輸出    if(obj==null){        //如果為空白就提示使用者登入        %>                   <%}else{            //不為空白就輸出使用者名稱,和歡迎資訊            out.println("歡迎您"+obj.toString());    }    %>

 

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("訪問:&nbsp;"+iCount+"次");%>
Request、Session和Application的區別

Request:中儲存的資料僅在一個請求中可用

Session:中儲存的資料在一個會話有效期間內可用

Application:中儲存的資料在整個WEB項目中可用,直到WEB伺服器停止運行

 

JSP實現資料儲存(web基礎學習筆記四)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.