Servlet共享數據的五種方式

Servlet共享數據的五種方式

一:Cookie(小甜餅)技術web

說明:
1.服務器在客戶端保存用戶的信息
2.此表的數據類型都是String
瀏覽器

a)建立一個Cookie表
Cookie coo = new Cooke(String name,String value);
服務器

b)發送一個Cookie添加至客戶端
HttpServletResponse res;
res.addCookie(coo);
說明:在C盤的Documents and Settings內一個以用戶名命名的文件夾下,Cookies文件夾內
session

c)從客戶端獲得全部的Cookie至服務器
HttpServletRequest req;
Cookie[] allCookies = req.getCookies();
for(Cookie temp:allCookies)
{
 if(temp.getName().equals("***")){
  String value = temp.getVelue();
 }
}
this

d)Cookie存在時間的設置(以秒爲單位)
coo.setMaxAge(60*1);
說明:不設置則此Cookie將不會保存
spa

e)刪除這一個Cookie
temp.setMaxAge(0);
orm

二:sendRedirect()轉向xml

a)發送數據
 HttpServletResponse res;
 res.sendRedirect("ServletName?name1="+value_1+"&name2="+value_2);
 說明:這行數據將會全然暴露於瀏覽器地址欄中!
 
b)接收數據
 HttpServletRequest req;
 String name_1 = req.getParameter("name1");
 String name_2 = req.getParameter("name2");
生命週期

三:隱藏表單內存

a)發送數據
<form action=login>
 <input type=hidden name=a value=b>
</form>

b)接收數據

四:Session技術

說明:
1.存儲至服務器端內存中
2.在Tomcat\conf\web.xml中,發呆時間的默認值(以分鐘爲時間單位)
  <session-config>
   <session-timeout>30</session-timeout>
  </session-config>
  
a)建立一個session表
HttpServletResponse res;
HttpSession hs = request.getSession(true);

b)向session添加屬性
hs.setAttribute(String name,Object val);

c)從session獲得某個屬性的值(Object類型)
String name_value = (String) hs.getAttribute(String name);

d)從session除去某個屬性
hs.removeAttribute(String name);
說明:一個屬性的除去不影響其它屬性的存在

e)獲得session的id
String sessionID = ht.getId();

f)設置session的發呆時間(以秒爲單位)
ht.setMaxInactiveInterval(60*1);

g)撤去session所有信息,至session無效
ht.setMaxInactiveInterval(0);

五:ServletContext技術

說明:
1.此技術用於多個客戶端共享服務器中的一個數據
2.ServletContext中的屬性的生命週期從建立開始,到服務器關閉而結束
3.多配合File技術使用

a)如何獲得一個ServletContext實例
ServletContext sc = this.getServletContext();

b)添加一個屬性
sc.setAttribute(String name,Object ob);

c)獲得這個屬性的值(類型爲Object)
String info = (String)sc.getAttribute(String name)

d)除去一個屬性 removeAttribute(String name)

相關文章
相關標籤/搜索