1.概念
:代表整个web应用,可以和程序的容器(服务器)来通信
2.获取:
1.通过request对象获取
request.getServletContext();
2.通过HttpServlet获取
this.getServletContext(); 其实这两个获取的对象地址是相等的
3.功能:
1.获取MIME类型:
MIME类型:在互联网通信过程中定义的以重文件的数据类型
*格式:大数据类型/小数据类型 text/html image/jpeg
*获取:String getMimeType(String file)
package cn.itcast.web.servletcontext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/servletContextDemo2")
public class ServletContextDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取serveltContext对象
ServletContext servletContext = req.getServletContext();
//定义文件名称
String filename="a.jpg";//image/jpeg
//4.获取MIME数据类型
String mimeType = servletContext.getMimeType(filename);
System.out.println(mimeType);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
2.域对象:共享数据
1.setAttribute(String name,Object value)
2.getAttribute(String name)
3.removeAttribute(String name)
*ServletContext 对象范围:所有用户所有的请求数据
3.获取文件的真实(服务器)路径
1.方法:String getRealPath(" String path")
package cn.itcast.web.servletcontext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@WebServlet("/servletContextDemo5")
public class ServletContextDemo5 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取serveltContext对象
ServletContext servletContext = req.getServletContext();
String realPath = servletContext.getRealPath("/b.txt");//从web目录下资源访问
File file = new File(realPath);
String c = servletContext.getRealPath("WEB-INF/classes/c.txt");//从WEB-INF目录下的资源访问
System.out.println(c);
String a = servletContext.getRealPath("/WEB-INF/class/a.txt");//从src目录下的资源路径
System.out.println(a);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}