关于getContextPath,getRealPath和getAbsolutePath的区别

本文详细介绍了在JavaWeb中,getContextPath(), getRealPath()和getAbsolutePath()的区别。getContextPath()返回的是项目的上下文路径,getRealPath()和getAbsolutePath()则提供真实的、绝对的文件系统路径。通过示例展示了它们在不同场景下的应用和输出结果。" 85630375,8061909,Flask项目实践:个人中心与点赞功能,"['Flask框架', 'web开发', '个人中心管理', '点赞功能', '数据库交互']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于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);
		
	}
}

结果
在这里插入图片描述
c3p0-config.xml和test.txt在项目中的存放路径,不管把文件放在src还是webRoot,文件都是相当于根目录
在这里插入图片描述

06-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值