ServletContext的使用
web容器在啟動的時候,他會為每個web程式都創建一個對應的ServletContext對象,他代表了當前的web應用
獲取ServletContext的對象的三種方法
// 第一種方式 ServletContext con1 = this.getServletConfig().getServletContext(); // 第二種方式 ServletContext con2 = req.getSession().getServletContext(); // 第三種方式 ServletContext con3= this.getServletContext();
共享數據 使用ServletContext 對象完成數據的共享
數據存儲:context.setAttribute(String name,Object value);
數據獲取:context.getAttribute(String name);
程式碼A:
程式碼B:(加了一步強轉的操作)
添加映射:
<servlet> <servlet-name>setc</servlet-name> <servlet-class>com.guangtao.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>setc</servlet-name> <url-pattern>/setc</url-pattern> </servlet-mapping> <servlet> <servlet-name>getc</servlet-name> <servlet-class>com.guangtao.servlet.getValue</servlet-class> </servlet> <servlet-mapping> <servlet-name>getc</servlet-name> <url-pattern>/gets</url-pattern> </servlet-mapping>
注意:
- 在輸入程式碼B的映射前得先運行程式碼A的映射路徑,否則會出現null的情況
- 如果在web.xml中配置多個servlet標籤,web-app出現報錯(一個標籤並不會報錯)
- 原因:引入的版本與默認的版本不匹配。
- 解決辦法:在web.xml 的web-app頭部加入一下配置即可
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="//www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee //xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">