ServletContext对象
- 概念:代表整个Web应用,可以和程序的容器(服务器)来通信
- 获取:
- 通过request对象获取:
request.getServletContext()
- 通过HttpServlet获取:
this.getServletContext()
- 通过request对象获取:
- 功能:
- 获取MIME类型
- MIME类型:在互联网通信过程中定义的一种文件数据类型
- 格式:大类型/小类型 text/html image/jpeg
- 获取:
String getMimeType(String file)
- 获取MIME类型
- 代码:
@WebServlet("/servletContextDemo2")
public class ServletContextDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.通过HttpServlet获取
ServletContext context = this.getServletContext();
//2.定义文件名称
String fileName = "a.jpg";
//3.获取MIME类型
String mimeType = context.getMimeType(fileName);
System.out.println(mimeType);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
- 访问:
- 域对象:共享数据
setAttribute(String name, Object value)
getAttribute(String name)
removeAttribute(String name)
- ServletContext对象的范围:所有用户所有请求的数据
- 域对象:共享数据
- 代码:
@WebServlet("/servletContextDemo3")
public class ServletContextDemo3 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.通过HttpServlet获取
ServletContext context = this.getServletContext();
//2.共享数据
context.setAttribute("msg","hello");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
@WebServlet("/servletContextDemo4")
public class ServletContextDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.通过HttpServlet获取
ServletContext context = this.getServletContext();
//2.获取数据
Object msg = context.getAttribute("msg");
System.out.println(msg);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
-
先访问Demo3再访问Demo4:
- 获取文件的真实(服务器)路径
- 方法:
String getRealPath(String path)
- 方法:
- 获取文件的真实(服务器)路径
-
资源位置:
-
代码:
@WebServlet("/servletContextDemo5")
public class ServletContextDemo5 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.通过HttpServlet获取
ServletContext context = this.getServletContext();
//2.获取文件的服务器路径
String bPath = context.getRealPath("/a.txt");//web目录下资源访问
System.out.println(bPath);
String cPath = context.getRealPath("/WEB_INF/b.txt");//WEB_INF目录下的资源访问
System.out.println(cPath);
String aPath = context.getRealPath("/WEB_INF/classes/c.txt");//src目录下的资源访问
System.out.println(aPath);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
- 访问输出结果: