2015-09-24 21 views
1

如果我在我的ServletContext對象中設置屬性,視圖是否自動訪問它?我試圖弄清楚這個JSP頁面是如何訪問在ServletContextListener中設置的變量以及其他任何地方的,因此我唯一可以得出的結論是它必須直接來自上下文對象。如果這是真的,那麼在ServletContext中設置一個值和在請求中設置一個值有什麼區別。這有點像會話和請求之間的區別嗎?在java servlets中,ServletContext屬性是否可以自動查看視圖?

+1

食品讀:http://stackoverflow.com/q/3106452和http://stackoverflow.com/tags/el /信息 – BalusC

回答

3

是的。您將可以在JSP中訪問它。

Tomcat將爲所有JSP轉換/生成servlet。

因此,您對JSP中的Java Servlet具有幾乎相同的訪問權限。 這意味着他們都將有權訪問servletConfig

所有jsp生成的servlet將擴展爲HttpJspBase,其中的實現擴展了GenericServlet,GenericServlet具有ServletConfig屬性。檢查doc


ServletContext的屬性是在容器[tomcat的]級別的屬性,按照該文檔

/** 
* 
* Defines a set of methods that a servlet uses to communicate with its 
* servlet container, for example, to get the MIME type of a file, dispatch 
* requests, or write to a log file. 
* 
* <p>There is one context per "web application" per Java Virtual Machine. (A 
* "web application" is a collection of servlets and content installed under a 
* specific subset of the server's URL namespace such as <code>/catalog</code> 
* and possibly installed via a <code>.war</code> file.) 
* 

所以會有每個應用程序只有一個背景和什麼都的屬性設置會所有servlet都可以訪問,而不管任何特定的會話或請求。

凡爲會話屬性設置在會話級別的屬性,可以有很多的會議在容器回事,它是由兩個客戶端[通常瀏覽器],並使用session-id機制容器維護。您將有權訪問會話中設置的屬性,直到會話結束。

終於請求屬性終身是直到你服務該請求。一旦你的容器發回結果,你設置的屬性將被銷燬。

檢查下面的Javadoc ServletRequest.removeAttribute的(...)

/** 
* Removes an attribute from this request. This method is not generally 
* needed as attributes only persist as long as the request is being 
* handled. 
*/ 
public void removeAttribute(String name); 
相關問題