servlet
servlet 聲明周期
實(shí)例化 -> 初始化 -> 服務(wù) -> 銷毀
出生: (實(shí)例化 -> 初始化) 第一次訪問Servlet就出生
活著:(服務(wù)) 應(yīng)用活著,Servlet 就活著
死亡: (銷毀)應(yīng)用卸載了Servlet 就銷毀
實(shí)例 init service destroy
如何讓Servlet 在服務(wù)器啟動(dòng)時(shí)就創(chuàng)建
在web.xml servlet 中設(shè)置
<load-on-startup>2</load-on-startup>
Servlet 的線程安全
單例:每次訪問多線程
解決縣城安全問題的最佳方法:不要寫全局變量奈嘿,而寫局部變量
Servlet 獲取配置信息
ServletConfig 使用
可以獲取servlet配置信息
this.getServletConfig().getInitParameter(key)
可以獲得Servlet對象
ServletContext
SerletContext 代表的是整個(gè)應(yīng)用肛著,一個(gè)應(yīng)用只有一個(gè)ServletContext對象浆熔。單例
作用
1,域?qū)ο螅涸谝欢ǚ秶鷥?nèi)(當(dāng)前應(yīng)用)杭攻,使多個(gè)Servlet共享數(shù)據(jù)
常用方法:
this.getServletContext.setAtrribute(String name,Object value)
this.getServletContext.getAttribute(String name)
this.getServletContext.moveAttribute(String name)
2坏晦,獲取全局配置信息
web.xml
<contxt-param>
<param-name>encoding</contxt-param>
<param-value>utf-8</param-value>
</contxt-param>>
this.getServletContext.getInitParameter("encoding")
3,獲取資源路徑
this.getServletContext.getRealPath(String path)
private void getPropertie(HttpServletResponse resp) {
ServletContext sc = this.getServletContext();
String path = sc.getRealPath("WEB-INF/a.properties");
Properties ps = new Properties();
try {
ps.load(new FileInputStream(path));
PrintWriter out = resp.getWriter();
out.println(ps.get("name"));
out.println(ps.get("age"));
out.println(ps.get("sex"));
out.println(sc.getClass().getName());
} catch (Exception e) {
e.printStackTrace();
}
}