request.getSession().getServletContext().getRealPath("/");

request.getSession().getServletContext()是获取的servlet容器对象,
相当于tomcat容器了。getRealPath("/") 获取实际路径,项目发布时,
在容器中的实际路径。

D:\apache-tomcat-8.5.23\apache-tomcat-8.0.52\wtpwebapps\Springmvc_day01\(Springmvc_day01是项目名)

获取文件的真实(服务器)路径 方法: String getRealPath(String path)

文件放置路径图

1.web目录下的资源访问   也就是WebContent下 把a.txt放到WebContent下

        ServletContext context = request.getServletContext();
		String path1 = context.getRealPath("/a.txt");//web目录下的资源访问   也就是WebContent下
		System.out.println(path1 );

输出为D:\eclipsework\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Demo4\a.txt

2.WEB-INF目录下的资源访问  文件放到WEB-INF下    b.txt

ServletContext context = request.getServletContext();
String path2 = context.getRealPath("/WEB-INF/b.txt");
		System.out.println(path2);

输出为D:\eclipsework\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Demo4\WEB-INF\b.txt

3.src目录下的资源访问 ---- src下的文件都
   src下的文件编译后,会放到WEB-INF下的classes文件夹,相应的c.txt就放到了classes下了

ServletContext context = request.getServletContext();
//src下的文件编译后,会放到WEB-INF下的classes文件夹,相应的c.txt就放到了classes下了
		String path3 = context.getRealPath("/WEB-INF/classes/c.txt");
		System.out.println(path3);
		

输出为D:\eclipsework\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Demo4\WEB-INF\classes\c.txt

注意:类加载器只能获取src下的真实目录,不能获取web下的真实目录

扫描二维码关注公众号,回复: 10484817 查看本文章

类加载器的例子

public class JdbcUtil {
	      static DataSource ds = null;
	static {
		 Properties pro = new Properties();
		try {
			pro.load(JdbcUtil.class.getClassLoader().getResourceAsStream("Druid.properties"));
			ds = DruidDataSourceFactory.createDataSource(pro);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
发布了52 篇原创文章 · 获赞 69 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/lbqlzch/article/details/101076712
今日推荐