ServletContext的作用
生活随笔
收集整理的這篇文章主要介紹了
ServletContext的作用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是 ServletContext?
上述的web工程應該是指:含有一個web文件夾(含有WEB-INF、web.xml的文件夾),如下圖所示。
獲取ServletContext對象
// 方法一 ServletContext context = getServletContext(); // 方法二 ServletContext context = getServletConfig().getServletContext();解釋方法二:
TODO:不明白???通過getServletConfig()可以返回一個config對象,
ServletContext 類的四個作用
測試 ServletContext 的作用
自定義的 Servlet 程序代碼
ServletContext context = getServletContext();// 獲取web.xml文件中的上下文信息,通過 param-name 獲取 param-value System.out.println("context-param 參數username的值是:" + context.getInitParameter("context")); System.out.println("context-param 參數username的值是:" + context.getInitParameter("username"));本文所有java代碼都寫在doGet()方法中
<!--context-param是上下文參數--> <context-param><param-name>context</param-name><param-value>123456</param-value> </context-param><context-param><param-name>username</param-name><param-value>hahah</param-value> </context-param>注意:以上<context-param>必須寫在web.xml文件的最上面(<web-app>標簽后)
輸出結果:
context-param 參數username的值是:123456 context-param 參數username的值是:hahah輸出:
獲取當前工程路徑:/webpro輸出:
獲取當前工程絕對路徑:F:\Code\webpro\out\artifacts\webpro_war_exploded\| Map | put() | get() | remove() |
| 域對象 | setAttribute() | getAttribute() | removeAttribute() |
輸出:
key1的值是:value1 key2的值是:value2 remove key1后 key1的值是:null remove key1后 key2的值是:value2參考文章:
總結
以上是生活随笔為你收集整理的ServletContext的作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么Servlet程序的init(Se
- 下一篇: 数据结构与算法基础--错题集