1.获得Web应用全局的初始化参数
1.1 配置Web.xm文件
<context-param>
<param-name>name</param-name>
<param-value>xiaodingdang</param-value>
</context-param>
1.2 获取Web应用全局的初始化参数
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = this.getServletContext().getInitParameter("name");
System.out.println(name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
2.获得Web应用所有资源的真实路径
分别获取a b c d 文本的真实路径
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String realPath1 = servletContext.getRealPath("a.txt");
System.out.println(realPath1);
String realPath2 = servletContext.getRealPath("WEB-INF/b.txt");
System.out.println(realPath2);
//获取不到Java的Src的路径 但是可以从classes中获取
String realPath3 = servletContext.getRealPath("WEB-INF/classes/c.txt");
System.out.println(realPath3);
//d获取不到 因为是相对于整个Web应用来获取 相对于wtpwebapps来获取的相对位置
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3.ServletContext是一个域对象
可以设置域属性
常用的方法有getAttribute(String name)获取域属性
setAtrribute(String name,Object object) 设置域属性
removeAtrribute(String name) 移除域属性
一个案例就是实现登录人数的功能