ServletContext
目录
- 1.获取ServletContext对象
- 2.功能
- 2.1 获取MIME对象
- 2.2 域对象:共享数据
- 2.3 获取文件真实路径(服务器路径)
1.获取ServletContext对象
- 两种方式
1.通过request获取
ServletContext servletContext = request.getServletContext();
2.通过HttpServlet获取
ServletContext servletContext = this.getServletContext();
- 代码
@WebServlet("/servletContextDemo1")
public class ServletContextDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过request获取
ServletContext servletContext = request.getServletContext();
//通过HttpServlet获取
ServletContext servletContext1 = this.getServletContext();
}
}
2.功能
2.1 获取MIME对象
servletContext.getMimeType();
- 步骤
1.通过HttpServlet获取ServletContext对象
2.定义文件名称
3.获取MIME类型
@WebServlet("/servletContextDemo1")
public class ServletContextDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过HttpServlet获取
ServletContext servletContext = this.getServletContext();
//定义文件名称
String filename = "a.jpg";
//获取MIME类型
String mimeType = servletContext.getMimeType(filename);
System.out.println(mimeType);
}
}
- 结果:
image/jpeg
2.2 域对象:共享数据
- setAttribute(string name,object value)
- getAttribute( string hame)
- removeAttribute(string name)
- 作用范围
Servletcontext对象范围:所有用户所有请求的数据
2.3 获取文件真实路径(服务器路径)
- String getRealPath(String path)