public class ServletContextDemo extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取context对象 ServletContext context = getServletContext(); // 1、获取全局配置参数,根据key获取value String parameter = context.getInitParameter("globaEncoding"); System.out.println(parameter); // 2、获取应用的虚拟目录 String contextPath = context.getContextPath(); System.out.println(contextPath); // 3、根据虚拟目录获取绝对路径 // src目录下的文件 String realPath1 = context.getRealPath("/WEB-INF/classes/a.txt"); System.out.println(realPath1); // web目录下的文件 String realPath2 = context.getRealPath("/b.txt"); System.out.println(realPath2); // WEB-INF目录下的文件 String realPath3 = context.getRealPath("/WEB-INF/web.xml"); System.out.println(realPath3); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
标签:常用,String,resp,ServletContext,System,context,println,方法,out From: https://www.cnblogs.com/weiduaini/p/17241838.html