---
title: "servletContext 功能"
author: "jiang_xiaohan"
date: "2012-11-20T17:49:39Z"
tags: []
categories: ["编程语言"]
slug: "servletcontext"
draft: false
lastmod: "2012-11-20T17:49:38Z"
id: 1731232
url: "https://jiang-xiaohan.iteye.com/blog/1731232"
---

ServletContext是application 对象所对应的接口，它具有一些高级功能，其中最常见的就是获取绝对路径（文件读写的操作，文件上传等应用）。

ServletContext.getRealPath（“资源在项目中的路径”）；


例：

 public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
   ServletContext application = this.getServletContext();
   String realPath = application.getRealPath("/");
   //   String realPath = this.getServletContext().getRealPath("/");
  System.out.println("获得项目跟目录据对路径："+realPath);
}

//ServletContext对象的获取方法
1，通过session获得，  javax.servlet.http.HttpSession.getServletContext();
2,通过pageContext获得， javax.servlet.jsp.pageContext.getServletContext();
3, 通过ServletConfig获得， javax.servlet.ServletConfig.getServletContext();
4 通过servlet获得，  javax.servlet.http.HttpServlet.getServletContext();