作爲jsp的九大內置對象的三種,servletContext屬於一個web應用的全局範圍,session則用於保存客戶端和服務器端交互的。一個web應用只有一個servletContext,存放的是全局信息,所有的servlet共享同一個servletContext對象。下面是它同session和cookie的比較
1.servletContext
//獲取servletContext對象
ServletContext sc = this.getServletContext();
//添加屬性,也就是存放共享數據
sc.setAttribute("uname","張三");//寫法爲sc.setAttribute(String name,Object obj)
//獲取屬性,也就是獲取共享的數據
sc.getAttribute("uname");//返回的是Object,寫法爲getAttribute(String)
//刪除屬性
removeAttribute("uname");//爲removeAttribute(String name),注意,刪除的是屬性,而不是對象
2.session
request//客戶端向服務端發送的信息
response//服務器端向客戶端相應的信息
HttpSession hs = request.getSession(true);//獲取與req相關聯的session,如果沒有就創建新的
hs.setAttribute("name","李四");//向session中添加屬性
hs.removeAttribute("name");//刪除session相應的屬性
3.cookie
Cookie ck = new Cookie("uname","王五");//在服務器端創建cookie,但cookie信息在客戶端保留
response.addCookie(ck);//將該cookie傳遞到客戶端
若想獲取request,可用類似下邊的方法
SamrtUpload su = new SmartLoad();
Request req = su.getRequest();