Servlet-servletContext
/**
* ServletContext物件學習
* 問題:
* 不同的使用者使用相同的資料
* 解決:
* ServletContext物件
* 特點:
* 伺服器建立
* 使用者共享
* 作用域:
* 整個專案內
* 生命週期:
* 伺服器啟動到伺服器關閉
* 使用:
* 獲取ServletContext物件
* //第一種方式:
ServletContext sc=this.getServletContext();
//第二種方式:
ServletContext sc2=this.getServletConfig().getServletContext();
//第三種方式:
ServletContext sc3=req.getSession().getServletContext();
* 使用ServletCOntext物件完成資料共享
* sc.setAttribute(String,Object);
* sc.getAttribute(String) 返回的是Object
*注意:
* ` 不同的使用者可以給ServletContext物件進行資料的存取
* 獲取的資料不存在返回Null
* @author Administrator
*
*/
public class ServletContextServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//獲取ServletContext物件
//第一種方式:
ServletContext sc=this.getServletContext();
//第二種方式:
ServletContext sc2=this.getServletConfig().getServletContext();
//第三種方式:
ServletContext sc3=req.getSession().getServletContext();
System.out.println(sc==sc2);
System.out.println(sc2==sc3);
//使用ServletContext物件完成資料共享
//資料儲存
sc.setAttribute("str","ServletContext物件學習");
}
}