天天看點

示範 ServletContext | 學習筆記

開發者學堂課程【Servlet 入門:示範 ServletContext】學習筆記,與課程緊密聯系,讓使用者快速學習知識。

課程位址:

https://developer.aliyun.com/learning/course/34/detail/753

示範 ServletContext

 内容介紹

一.域對象的功能

ServletContext 是 JavaWeb 四大域對象之一:

PageContext;

ServletReguest;

HttpSession;

SenvletContext;

所有域對象都有存取資料的功能,因為域對象内部有-個Map,用來存儲資料,

下面是 ServletContext. 對象用來操作資料的方法: 

1.void SetAttribute(String name.object value):

用來存儲一一個對象,也可以稱之為存儲一-個域屬性,例如: serletCotetstitrtl(xx","“XX*),在 ServletContext 中儲存了一個域屬性,域屬性名稱為xox ,域屬性的值為)XX.請注意,如果多次調用該方法,并且使用相同的 name ,那麼會覆寫上-次的值,這一特性與 Map 相同;

2.Object getAttribute(String name):

用來擷取 ServletContext 中的資料,目前在擷取之前需要先去存儲才行,例如: String value=(rtingestrclCntetote('";"擷取名為 xx 的域屬性;

3.void removettribute(tring name):

用來移除 ServletContext 中的域屬性,如果參數 name 指定的域屬性不存在,那麼本方法什麼都不做;

4.Enumeration gettributeNames():

擷取所有域屬性的名稱;

package cn. itcast.servlet;

import java.io.IOException;

​​

示範從 servletContext 中擷取資料public class BServlet extends HttpServlet { publia void doGet (HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException [

1.擷取 servletContext 對象

2.調用其 getAttribute (方法完成荻取資料 Servletcontext application-​​

this .getServletcontext();

string name = (string) application.getAttribute ("name") 

system. out.println (name);