簡談Servlet(二)—ServletContext

ServletContext對象封裝這web應用的信息,一個web應用可以有多個servlet對象,但是只能有一個servletcontext對象。

ServletContext對象在web應用被服務器加載時創建,在服務器關閉時被銷燬

它的作用有:

1.通過ServletContext對象來獲得web應用全局的初始化參數

例如我們要獲得web.xml中的配置信息,web.xml部分代碼如下:

.......
  <context-param>
    <param-name>aaaa</param-name>
    <param-value>bbbb</param-value>
  </context-param>
.......

通過這個java代碼來獲得我們所需要的配置信息

public class ContextServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//獲得ServletContext對象
		ServletContext servletContext = this.getServletContext();
		
		//1.通過ServletContext對象獲得全局參數
		String initParameter = servletContext.getInitParameter("aaaa");
		System.out.println(initParameter);

	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

最終它的輸出爲 bbbb

在這裏我們要考慮到如何創建ServletContext對象:一是我們在init方法中,可以直接通過config(代表配置信息).getServletContext()來獲得這個對象。二是我們在doGet方法中直接this.getServletContext()來獲得這個對象

 

2.可以獲得web語言中任何資源的絕對路徑

現在我們創建一個a.txt文件,我們要獲得它的絕對路徑,這就用到ServletContext對象

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲得ServletContext對象
		ServletContext servletContext = this.getServletContext();
		
		//獲得web應用中任何資源的絕對路徑
		String path=servletContext.getRealPath("/WEB-INF/lib/a.txt");
		System.out.println(path);
	}

在這裏我們在getRealPath中設置的路徑爲相對路徑,是相對於WebContent(在ecslip項目中)  或 WebXX(在tomcat文件夾中,在發表時服務器將ecslip項目中的WebContent改名爲這個項目名)

方法:String path = context.getRealPath(相對於該web應用的相對地址);

3.用於域,它是一個域對象

ServletContext域對象的作用範圍:整個web應(所有的web資源都可以隨意向 servletcontext域中存取數據,數據可以共享)

通用方法:

set/get+Atrribute()

public class ContextServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲得ServletContext對象
		ServletContext servletContext = this.getServletContext();
		
		//3.ServletContext是一個域對象
		//向域中寫數據
		servletContext.setAttribute("aaa","hahaha");

        //讀數據
        Object attribute = servletContext.getAttribute("aaa");
		System.out.println(attribute.toString());
	}

這就是通過域寫數據及讀數據

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章