一、什麼是ServletContext?web
二、原理
ServletContext對象由服務器建立,一個項目只有一個ServletContext對象。在項目任何位置獲取到的都是同一個對象,那麼不一樣用戶發起的請求獲取到的也就是同一個ServletContext對象了,該對象由用戶共同擁有。
三、做用
解決不一樣用戶之間數據共享問題
四、特色服務器
五、 用法
web.xml文件部分屬性app
<context-param> <param-name>country</param-name> <param-value>China</param-value> </context-param> <context-param> <param-name>city</param-name> <param-value>BeiJing</param-value> </context-param> <servlet> <servlet-name>ContextServlet</servlet-name> <servlet-class>com.syf.ContextServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ContextServlet</servlet-name> <url-pattern>/cs</url-pattern> </servlet-mapping> <servlet> <servlet-name>ConfigServlet</servlet-name> <servlet-class>com.syf.ConfigServlet</servlet-class> <init-param> <param-name>Job</param-name> <param-value>Program</param-value> </init-param> <init-param> <param-name>Location</param-name> <param-value>East</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ConfigServlet</servlet-name> <url-pattern>/config</url-pattern> </servlet-mapping>
public class ContextServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //3種方式獲取ServletContext對象 ServletContext sc1 = this.getServletContext();//經常使用 ServletContext sc2 = this.getServletConfig().getServletContext(); ServletContext sc3 = request.getSession().getServletContext(); //設置屬性 sc1.setAttribute("name","zhangsan"); //獲取web.xml中設置的參數值 String city = sc2.getInitParameter("city"); System.out.println(city);//BeiJing String country = sc3.getInitParameter("country"); System.out.println(country);//China //獲取某個文件的絕對路徑 String realPath = sc1.getRealPath("web.xml"); System.out.println(realPath); //獲取web項目的上下文路徑(Tomcat的虛擬目錄路徑) String contextPath = sc1.getContextPath(); System.out.println(contextPath); } }
public class ContextServlet2 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取ServletContext對象 ServletContext sc = this.getServletContext(); //獲取在contextServlet類中設置的屬性 String name = (String) sc.getAttribute("name"); System.out.println(name);//zhangsan } }
一、做用
ServletConfig對象是Servlet的專屬配置對象,每一個Servlet都單獨擁有一個ServletConfig對象 ,用來獲取web.xml中的配置信息
二、用法this
public class ConfigServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); ServletConfig sc = this.getServletConfig(); //獲取web.xml中設置的ConfigServlet的配置屬性key Enumeration<String> keys = sc.getInitParameterNames(); while (keys.hasMoreElements()){ String key = keys.nextElement(); //根據key獲取value值 String value = sc.getInitParameter(key); System.out.println(key+"="+value);//Job=Program,Location=East } } }