1. 程式人生 > >ServletContext及相關案例

ServletContext及相關案例

light servlets ava set eas cep web容器 pack cast

ServletContext對象 (域對象)

定義:WEB容器在啟動時,它會為每個WEB運用程序都創建一個對應的ServletContext對象,它代表當前WEB運用。

一個WEB運用對應一個ServletContext對象

一個WEB運用下有多個Servlet程序

所有的Servlet程序都共享同一個ServletContext對象

作用

1、獲取WEB運用的全局初始化參數 案例和ServletConfig類似

String getInitParameter(String name)

Enumeration getInitParameters()

配置全局初始化參數 在<Servlet>外面

<Context-param>

<param-name>assasasa</param-name>

<param-value>fdsfdsfsd<param-value>

</Context-param>

2、實現數據共享

void setAttribute(String name,Object object) 存入數據

void removeAttribute(String name) 刪除數據

  • object getAttribute(String name) 獲取數據

3、讀取資源文件

InputStream getResourceAsStream(String path) 通過文件地址獲取輸入流

String getRealPath(String path) 通過文件地址獲取文件的絕對磁盤路徑

統計網站訪問量

package cn.idcast.Servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletCount extends HttpServlet {
	/**
	 * 實例被創建,調用init進行初始化 在域對象存入一個變量,初始化為0
	 */
	public void init() throws ServletException {
		getServletContext().setAttribute("count", 0);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 每一次訪問,都會執行該方法 獲得count的變量,每次訪問count都會自增,再存入到域對象中
		 */
		ServletContext sc = getServletContext();
		// 因為count 是數字,所以用integer
		Integer count = (Integer) sc.getAttribute("count");
		// ++i是先處理完加法,再做其它運算, i++是處理完相關運算(執行完一條語句後)後自加
		sc.setAttribute("count", ++count);
		// 向頁面輸出內容
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write("<h3>下次再來</h3>");
	}

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

}

  

package cn.idcast.Servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletShow extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Integer count = (Integer) getServletContext().getAttribute("count");
		// 向頁面輸出內容
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write("<h3>一共訪問了" + count + "次</h3>");
	}

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

}

  

ServletContext及相關案例