1.ServletContext概述
a.Tomcat服务器启动时 , 会为每个项目创建一个ServletContext对象.
b.一个项目只有一个ServletContext对象(保证了存取都是同一个)
2.ServletContext的获取
因为每次ServletContext对象都是自动创建,所以我们无需创建 , 只需获取它.
ServletContext sc = this.getServletContext(); / / 每次使用都要获取
3.ServletContext的作用
1.实现多个servlet的共享数据.
- setAttribute(String name,Object object): 存数据.
- getAttributegetAttribute(String name): 取数据.
- removeAttribute(name): 移除数据.
2.获取项目的一些资源.
- String getRealPath("/项目下的资源"); 获取资源在服务器上的绝对路径.
- InputStream getResourceAsStream(path): 获取资源的输入流 , 不存在返回null
3.获取其他辅助信息.
- getMimeType(“文件名”) : 返回该文件的数据类型.
4.获取初始化数据(框架Spring使用)
- getInitparameter(“参数名”): 通过参数获取参数值.
全局初始化参数: context-param -> param-name(参数名)
param-value(参数值)
登录次数案例:
Count1Servlet.java
@WebServlet("/count01")
public class Count1Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置编码格式 - 解决中文乱码问题.
response.setContentType("text/html; charset=utf-8");
// 1.先获取servletContext对象.
ServletContext sc = this.getServletContext();
Integer count = (Integer) sc.getAttribute("count");
// 2.先获取 , 看是否访问过.
if(count==null){
count =1 ;
}else{
count++;
}
response.getWriter().print("<h1 color = red>此页面已经被你访问了"+count+"次");
sc.setAttribute("count" , count);
}
}
Count2Servlet.java(一样)
@WebServlet("/count02") //访问路径不一样.
public class Count2Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置编码格式 - 解决中文乱码问题.
response.setContentType("text/html; charset=utf-8");
// 1.先获取servletContext对象.
ServletContext sc = this.getServletContext();
Integer count = (Integer) sc.getAttribute("count");
// 2.先获取 , 看是否访问过.
if(count==null){
count =1 ;
}else{
count++;
}
response.getWriter().print("<h1 color = red>此页面已经被你访问了"+count+"次");
sc.setAttribute("count" , count);
}
}
当访问了count1之后 , 再访问count2时 , 他会是已经访问了2次,
因为只有一个ServletContext对象 , 多个Servlet之间数据共享 .