ServletContext物件的使用

2021-10-19 07:23:01 字數 2569 閱讀 3066

web容器啟動的時候,它會為每個web程式都建立乙個對應的servletcontext物件,它代表了當前的web應用。

1. 共享資料

我在這個servlet當中的資料可以在另乙個servlet當中拿到

當前servlet放的資料

上下文

servletcontext context =

this

.getservletcontext()

; string username =

"胡某人"

; context.

setattribute

("username"

,username)

;

需要拿資料的另乙個servlet

servletcontext context =

this

.getservletcontext()

; string username =

(string) context.

getattribute

("username");

resp.

setcontenttype

("text/html");

resp.

setcharacterencoding

("utf-8");

resp.

getwriter()

.print

("名字:"

+username)

;

2. 獲取初始化引數配置的web應用的初始化引數

>

>

urlparam-name

>

>

jdbc:mysql://localhost:3306/mybatisparam-value

>

context-param

>

在servlet中拿到web應用中的初始化引數

servletcontext context =

this

.getservletcontext()

; string url = context.

getinitparameter

("url");

resp.

getwriter()

.print

(url)

;

結果為

3. 請求**

servlet將請求**給另乙個servlet

需要請求**的servlet

servletcontext context =

this

.getservletcontext()

;//requestdispatcher requestdispatcher = context.getrequestdispatcher("/serv");//引數為要**到的servlet路徑

呼叫forward實現請求**

context.

getrequestdispatcher

("/serv").

forward

(req,resp)

;

4. 讀取資源檔案properties

發現都被打包到了同一路徑下:classes,俗稱類路徑classpath

需要乙個檔案流

//在target的web應用的classes裡找到配置檔案

inputstream asstream =

this

.getservletcontext()

.getresourceasstream

("/web-inf/classes/da.properties");

properties prop =

newproperties()

;prop.

load

(asstream)

;string user = prop.

getproperty

("username");

string pwd = prop.

getproperty

("password");

resp.

getwriter()

.print

(user+

":"+pwd)

;

配置檔案

username=root

password=123456

結果

ServletContext介面功能

使用getinitparameternames 和getinitparameter string name 來獲得web應用中的初始化引數 setattribute string name,string value 來設定共享的資料 getattribute string name 來獲得共享得資料...

ServletContext物件學習

問題 不同的使用者使用相同的資料 解決 servletcontext物件 特點 伺服器建立 使用者共享 作用域 整個專案內 生命週期 伺服器啟動到伺服器關閉 使用 獲取servletcontext物件 第一種方式 servletcontext sc this.getservletcontext 第二...

ServletContext物件的應用

servletcontext物件 user root pass 1234 1.獲取指定名稱的context配置資訊 servletcontex context this.getservletcontext string user context.getinitparameter user syste...