文章目录
一、Sercletcontext对象获取
/* Sercletcontext对象获取 1. 通过request对象获取 request.getServletContext(); 2. 通过HttpServlet获取 this.getServletContext(); */ ServletContext sc1 = request.getServletContext(); ServletContext sc2 = this.getServletContext(); System.out.println(sc1); System.out.println(sc2); System.out.println(sc1==sc1);
二、Sercletcontext对象功能
1. 获取MIME类型:
/* Sercletcontext对象功能 1. 获取MIME类型: * MIME类型:在互联网通信过程中定义的一种文件数据类型 * 格式: 大类型/小类型 text/html image/jpeg * 获取:String getMimeType(String file) */ //2.通过httpservlet获取 ServletContext sc2 = this.getServletContext(); //3.定义文件名称 String filename = "a.jpg";//image/jpeg //4获取MIME类型: String mimeType = getServletContext().getMimeType(filename); System.out.println(mimeType);
2、域对象:共享数据
/* Sercletcontext对象功能 2. 域对象:共享数据 1. setAttribute(String name,Object value) 2. getAttribute(String name) 3. removeAttribute(String name) * ServletContext对象范围:所有用户所有请求的数据 */ //2.通过httpservlet获取 ServletContext bc = this.getServletContext(); //设置数据 bc.setAttribute("msg","haha");
//2.通过httpservlet获取 ServletContext cd = this.getServletContext(); //获取数据 Object msg = cd.getAttribute("msg"); System.out.println(msg);
3、获取文件的真实(服务器)路径
//1. 方法: String getRealPath(String path) //2.通过httpservlet获取 ServletContext ct = this.getServletContext(); //ServletContext cd = this.getServletContext(); String s = ct.getRealPath("/WEB-INF/classes/a.txt"); System.out.println(s);