jsp中session的使用

來源:互聯網
上載者:User

標籤:etl   config   使用者登入   XML   cal   obj   ini   file   .net   

Session的典型應用:

  1. 防止使用者非法登入到某個頁面。
  2. 網上商城的購物車
  3. 儲存使用者登入資訊

註:多個請求要用的東西放在session中,多個會話之間要用的東西放在上下文中。

如何建立session?

Servelt API 中有HttpSession介面,來封裝session對象。用HttpServletRequest來擷取會話對象。

 

HttpSession  session=request.getSession();

 

 

主要方法:
1. getAttribute( String name )
擷取指定名字name相聯絡的資訊.

 

2.getAttributeNames()
返回Session對象中儲存的每一個屬性對象,其結果為一個類舉的執行個體.

 

3. getCreationTime()
返回Session被建立的時間.最小單位為千分之一秒.

 

4.getId()
此方法返回惟一的標識,這些標識為每個Session而產生.當只有一個單一的值與一個Session聯合時,或當日誌資訊與先前的Session有關時,它被當做鍵名用.

 

5.GetLastAccessedTime()
返回當前Session對象最後被客戶發送的時間,最單位為千分之一秒.

 

6. GetMaxInactiveInterval()
返回總時間(秒),負值表示Session永遠不會逾時.該時間為該Session對象的存留時間.

 

7. removeAttribute( String name )
刪除與提定名字name的相聯絡的資訊.

 

8. setAttribute( String name , Java.lang.Object value )
設定指定名字name的屬性值value,並將之儲存在Session對象中.

9.session.invalidate()                                                                                                    是將session設定為失效,一般在退出時使用

 

問:會話的有效時間到底會有多長時間?

答:1.會話是由容器來建立的,長時間不用,容器會在30分鐘後將它銷毀,它是不能一直存放在伺服器中的。

Tomcat中可以修改會話的時間

C:\Program File\Tomcat\cof\web.xml 

第483行-485行

<session-config> 

 <session-timeout>30</session-timeout>

</session-config>

2.在項目中web.xml中可以設定會話的時間長度

<session-config> 

 <session-timeout>30</session-timeout>

</session-config>

1、2中session的有效時間應用於所有會話對象有效時間長。

3,對於某一個會話設定有效時間,在Servlet中用session.setMaxAge(秒)來設定

 

內容相關的作用

利用內容物件可以實現多個使用者之間的資料共用。

內容物件如何建立的?

Servelt中ServletContext  sc=this.getServletContext()

             sc. setAttribute(String key,Object value)

             sc. getAttribute(String key)

             sc. getInitParameter(String path)

ServletContext和ServletConfig本來沒有直接關係,但容器起動後,把得到上下文方法封裝在servletConfig中,因為servlet繼承了。

所以,在Servlet 中就可以直接使用ServletContext  sc=this.getServletContext()方法得到ServletContext

JSP中 application.getAttribute(String key);

 

 問:ServletContext 什麼時使用?

 

答:  如果在一個應用中有多個Servlet和JSP都使用的變數,以後還可能被修改,就可以考慮用上下文參數

 

在web.xml中配置:

 

<context-param>

 

 <param-name>level</param-name>

 

 <param-value>1</param-value>

 

 </context-param> 

 

jsp中session的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.