1. 程式人生 > >ServletContext物件(域物件) (*****)

ServletContext物件(域物件) (*****)

1. ServletContext物件(域物件)    (*****)

1.1 定義:

WEB容器在啟動時,它會為每個WEB應用程式都建立一個對應的ServletContext物件,它代表當前web應用。

            一個WEB應用對應一個ServletContext物件
            一個WEB應用下有多個Servlet程式
            所有的servlet程式都共享同一個ServletContext物件

            demo1存入內容    ServletContext    demo2中取出來

2.作用:

2.1獲取WEB應用全域性初始化引數

                    * 在web.xml中配置
                        <context-param>
                            <param-name>encoding</param-name>
                            <param-value>UTF-8</param-value>
                        </context-param>
                    
                    String getInitParameter(String name)

                    getInitParameterNames()          

package cn.itcast.context;

import java.io.IOException;
import java.util.Enumeration;

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


/**
 * 獲取全域性初始化引數
 * @author Administrator
 *
 */
public class ContextDemo1 extends HttpServlet {

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//獲取servletcontext物件
		ServletContext context = getServletContext();
		//獲取初始化引數
		String encoding = context.getInitParameter("encoding");
		System.out.println("編碼:" + encoding);
		
		Enumeration<String> e = context.getInitParameterNames();
		while(e.hasMoreElements()){
			String name = e.nextElement();
			String value = context.getInitParameter(name);
			System.out.println(name + ": " + value);
		}
		
		
	}

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

		doGet(request, response);
	}

}

2.2實現資料的共享(*****)(統計網站被訪問了多少次)

                    void setAttribute(String name, Object object)   存入資料
                    void removeAttribute(String name)                  刪除資料

                    Object getAttribute(String name)                  獲取資料

兩個servlet實現:


CountServlet.java

package cn.itcast.context;

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;

/**
 * 統計網站的訪問次數
 * @author Administrator
 *
 */
public class CountServlet extends HttpServlet {

	/**
	 * 例項被建立,呼叫init方法初始化
	 * 在域物件中存入一個變數,賦值0
	 */
	public void init() throws ServletException {
		getServletContext().setAttribute("count", 0);
	}

	/**
	 * 每次訪問,都會執行該方法
	 * 拿出count值,然後自加,再存入域中
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletContext context = getServletContext();
		Integer count = (Integer) context.getAttribute("count");
		count++;
		//存入域物件中
		context.setAttribute("count", count);
		
		//向頁面輸出
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write("<h1> 歡迎再來哦!!! </h1>");
	}

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

		doGet(request, response);
	}

}


showServlet.java
package cn.itcast.context;

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;

/**
 * 顯示網站的訪問量
 * @author Administrator
 *
 */
public class ShowServlet extends HttpServlet {

	/**
	 * 獲取網站訪問次數
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletContext context = getServletContext();
		Integer count = (Integer) context.getAttribute("count");
		
		//向頁面輸出
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write("<h1>該網站一共被訪問了" + count + "次</h1>");
	}

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

		doGet(request, response);
	}

}


2.3讀取資原始檔(*****)

                    InputStream getResourceAsStream(String path)      通過檔案的地址獲取輸入流

                    String getRealPath(String path)          通過檔案的地址獲取檔案的絕對磁碟路徑

package cn.itcast.context;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

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

public class ReadServlet extends HttpServlet {

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

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

		doGet(request, response);
	}
	
	
	public void read5() throws IOException{
		String path = getServletContext().getRealPath("/WEB-INF/classes/db.properties");
		System.out.println(path);
		
		//servletContext來讀取檔案
		InputStream in = new FileInputStream(path);
		//列印方式
		print(in);
	}
	
	public void read2() throws IOException{
		//servletContext來讀取檔案
		InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		//列印方式
		print(in);
		
	}
	
	/**
	 * 傳統方式讀取資原始檔
	 * 交給伺服器處理,相對位置在tomcat/bin
	 * @throws IOException
	 */
	public void read1() throws IOException{
		//獲取輸入流
		InputStream in = new FileInputStream("/src/db.properties");
		Properties pro = new Properties();
		
		//載入
		pro.load(in);
		
		//獲取檔案中的內容
		String username = pro.getProperty("username");
		String password = pro.getProperty("password");
		String desc     = pro.getProperty("desc");
		
		System.out.println("使用者名稱:" + username);
		System.out.println("密碼:"  + password);
		System.out.println("描述:"  + desc);
	}
	
	public void print(InputStream in) throws IOException{
		
		Properties pro = new Properties();
		//載入
		pro.load(in);
		
		//獲取檔案中的內容
		String username = pro.getProperty("username");
		String password = pro.getProperty("password");
		String desc     = pro.getProperty("desc");
		
		System.out.println("使用者名稱:" + username);
		System.out.println("密碼:"  + password);
		System.out.println("描述:"  + desc);
	}

}

相關推薦

WEB專案-Servlet簡介、生命週期、訪問路徑、ServletContext物件物件

Servlet簡介 什麼是Servlet: - Servlet是一個介面,下面有5個方法 - Servlet有兩個實現類,GenericServlet和HttpServlet Servlet的作用: - Servlet是一個小型的Java程式,執行在伺服器端 - Servle

ServletContext物件物件 *****

1. ServletContext物件(域物件)    (*****) 1.1 定義: WEB容器在啟動時,它會為每個WEB應用程式都建立一個對應的ServletContext物件,它代表當前web應用。             一個WEB應用對應一個Servlet

ServletContext物件--三大物件

Servlet三大域物件的應用 request、session、application(ServletContext) ServletContext是一個全域性的儲存資訊的空間,伺服器開始就存在,伺服器關閉才釋放。 request,一個使用者可有多個;sessi

JSP內建物件物件

什麼是內建物件? 在使用jsp頁面時,有某些物件使用頻率非常高。如果我們每次都去建立這些物件再使用,就會變得麻煩。所以在載入完jsp頁面時,就把這些物件建立好了,我們只需要直接使用這些物件即可!!!!這些物件就叫內建物件。 JSP的9大內建物件 JSP的4大域物

Java四大物件詳解ServletContext、Session、Request、pageContext物件

一、ServletContext 1、生命週期:當Web應用被載入進容器時建立代表整個web應用的ServletContext物件,當伺服器關閉或Web應用被移除時,ServletContext物件跟著銷燬。 2、作用範圍:整個Web應用。 3、作用:

ServletContext物件2ServletContext物件

ServletContext物件: 一、ServletContext物件的核心API(作用) 4、域物件有關的方法 1)域物件:作用是用於儲存資料,獲取資料。可以在不同的動態資源之間共享資料。 2)案例:想要從Servlet1向Servlet2傳送資料

JSP JSP語法 JSP註釋 JSP指令 JSP九大內建物件 pageContext物件 JSP動作標籤

(1)jsp概述1.1 什麼是jspjsp(java Server Pages)是JavaWeb服務端的動態資源,它與html作用是相同的 顯示資料和獲取資料1.2 jsp的組成JSP=html+Java指令碼(程式碼片段)+JSP動態資源(2)JSP語法2.1 jsp指令碼

JavaWeb監聽器實現監聽器步驟,物件的建立和銷燬,物件的屬性變更

在WEB中監聽器的監聽物件也就是針對域物件【application/session/request/pageContext(不用)】的建立、銷燬以及域物件屬性物件的新增、移除。 監聽三個域物件的建立和銷燬的監聽器        ( 型別名Listene

ServletServletContext物件和ServletConfig物件

ServletContext 物件:問題:  Request 解決了一次請求內的資料共享問題,session 解決了使用者不同請求的資料共享問題,那麼不同的使用者的資料共享該怎麼辦呢?解決:  使用 ServletContext 物件作用:  解決了不同使用者的資料共享問題原理:  ServletContex

JSP:JSP九大內建物件、四個作用物件

jsp的九大內建物件:        內建物件:            jsp檔案在轉譯成其對應的Servlet檔案的時候自動生成

CRM分頁查詢客戶資訊涉及到物件知識

前端程式碼:<TD class=menuSmall> <A class=style2 href="${pageContext.request.contextPath}/customer/searchClistForPage.action?pageNum=1&pag

Java 7:類和物件、引數、初始化

面向物件程式設計:每個物件包含對使用者公開的特定功能部分和隱藏的實現部分,在OOP中不必關心物件的具體實現,OOP更看重資料(結構),而不是具體演算法。 封裝(資料隱藏):將資料和行為組合在一個包裡,並對物件的使用者隱藏資料的實現方式,封裝的關鍵是絕不能讓其他類直接訪問例項

ServletContext物件獲取當前工程資源webapps或者webroot下資源

//讀取工程工程下面images資料夾的圖片向瀏覽器輸出 public class ImageServlet_02 extends HttpServlet { public void do

jsp九大內建物件與四大物件轉載

一,什麼是內建物件? 在jsp開發中會頻繁使用到一些物件,如ServletContext HttpSession PageContext等.如果每次我們在jsp頁面中需要使用這些物件都要自己親自動手建立就會特別的繁瑣.SUN公司因此在設計jsp時,在jsp頁面載入完畢之後自

Web開發中的四個物件範圍由小到大

簡介: page(jsp有效)  request(一次請求) session(一次會話)application(當前web應用) page域指的是pageContext. request域指的是requestHttpServletRequest session 域指的是 s

Servlet知識詳解ServletContext物件 和 ServletConfig物件學習筆記

學習小結 (一)Servlet的對映URL中使用*萬用字元的方法:兩種固定格式           b:另一種格式是以正斜槓(/)開頭並以/*結尾           備註:/####/*形式的優先順序要高於*.副檔名的優先順序 (二)Servlet例項物件的預裝載配置<load-on-sta

【小家java】POP面向過程程式設計、OOP面向物件程式設計、AOP面向切面程式設計三種程式設計思想的區別和聯絡

相關閱讀 【小家java】java5新特性(簡述十大新特性) 重要一躍 【小家java】java6新特性(簡述十大新特性) 雞肋升級 【小家java】java7新特性(簡述八大新特性) 不溫不火 【小家java】java8新特性(簡述十大新特性) 飽受讚譽 【小家java】java9

js物件屬性駝峰式命名帶數字轉下劃線命名

將類似於 info 格式轉化為 info2  var info = { id: 1, id1: 2, userName1: '劉玄德', userName2: '劉玄德', userName3: '大哥',

python 學習第二十四天同步物件、資訊量、queue庫

同步物件 import threading,time class Boss(threading.Thread): def run(self): print("BOSS:今晚大家都要加班到22:00。") print(event.i

從零開始的全棧工程師——js篇2.12面向物件

面向物件 Js一開始就是寫網頁特效,面向過程的,作者發現這樣寫不好,程式碼重複利用率太高,計算機記憶體消耗太大,網頁效能很差。 所以作者就收到java和c的影響,往面向物件靠齊。Js天生有一個Object,但他沒有面向物件的特徵(封裝,繼承,多型)。 最後研究出了建構函式。 建構函式最終目的是生成物件