关于getContextPath,getRealPath和getAbsolutePath的区别

关于getContextPath,getRealPath和getAbsolutePath的区别

  1. getContextPath()从Context这个单词就知道获取的是上下文路径,也就是项目路径。
  2. getRealPath()获得是真实路径,也就是绝对路径,带盘符名
  3. getAbosolutePath()和getRealPath()一样,不过调用方法的对象不一样

例子测试getContextPath和getRealPath

package cn.edou.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestPath extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String requestContextPath = req.getContextPath();
		String servletContextPath = req.getServletContext().getContextPath();
		String sessionContextPath = req.getSession().getServletContext().getContextPath();
		String realPath = req.getServletContext().getRealPath("/c3p0-config.xml");
		String realPath1 = req.getServletContext().getRealPath("/");
		String sessionRealPath = req.getSession().getServletContext().getRealPath("/test.txt");
		String sessionRealPath1 = req.getSession().getServletContext().getRealPath("/");
		PrintWriter out = resp.getWriter();
		out.println("requestContextPath:"+requestContextPath);
		out.println("<br/>");
		out.println("servletContextPath:"+requestContextPath);
		out.println("<br/>");
		out.println("sessionContextPath:"+requestContextPath);
		out.println("<br/>");
		out.println("---------------------------------");
		out.println("<br/>");
		out.println("realPath:"+realPath);
		out.println("<br/>");
		out.println("realPath1:"+realPath1);
		out.println("<br/>");
		out.println("sessionRealPath:"+sessionRealPath);
		out.println("<br/>");
		out.println("sessionRealPath1:"+sessionRealPath1);
		
	}
}

结果
关于getContextPath,getRealPath和getAbsolutePath的区别
c3p0-config.xml和test.txt在项目中的存放路径,不管把文件放在src还是webRoot,文件都是相当于根目录
关于getContextPath,getRealPath和getAbsolutePath的区别