---
title: "java(JSP)中几种获取项目路径方式"
author: "cuker919"
date: "2014-07-17T10:27:00Z"
tags: []
slug: "java-jsp"
draft: false
lastmod: "2015-04-11T22:46:06Z"
id: 2201407
url: "https://cuker919.iteye.com/blog/2201407"
---

01. 在jsp和class文件中调用的相对路径不同。在jsp里，根目录是WebRoot在class文件中，根目录是WebRoot/WEB-INF/classes当然你也可以用System.getProperty("user.dir")获取你工程的绝对路径。
02. 另:在Jsp,Servlet,Java中详细获得路径的方法!
03. 1.jsp中取得路径：
04. 以工程名为TEST为例：
05. (1)得到包含工程名的当前页面全路径：request.getRequestURI()
06. 结果：/TEST/test.jsp
07. (2)得到工程名：request.getContextPath()
08. 结果：/TEST
09. (3)得到当前页面所在目录下全名称：request.getServletPath()
10. 结果：如果页面在jsp目录下/TEST/jsp/test.jsp
11. (4)得到页面所在服务器的全路径：application.getRealPath("页面.jsp")
12. 结果：D:\\resin\\webapps\\TEST\\test.jsp
13. (5)得到页面所在服务器的绝对路径：absPath=newjava.io.File(application.getRealPath(request.getRequestURI())).getParent();
14. 结果：D:\\resin\\webapps\\TEST
15. 2.在类中取得路径：
16. (1)类的绝对路径：Class.class.getClass().getResource("/").getPath()
17. 结果：/D:/TEST/WebRoot/WEB-INF/classes/pack/
18. (2)得到工程的路径：System.getProperty("user.dir")
19. 结果：D:\\TEST
20. 3.在Servlet中取得路径：
21. (1)得到工程目录：request.getSession().getServletContext().getRealPath("")参数可具体到包名。
22. 结果：E:\\Tomcat\\webapps\\TEST
23. (2)得到IE地址栏地址：request.getRequestURL()
24. 结果：http://localhost:8080/TEST/test
25. (3)得到相对地址：request.getRequestURI()
26. 结果：/TEST/test

struts2设置了struts.multipart.saveDir后会在根目录建立文件夹，这样会涉及linux下的权限问题，

最好不要设置，使用struts默认

需要使用路径时，用下面的方法取得项目根目录的绝对路径(Tools为方法类)

public static String getRootPath() {  
String classPath = Tools.class.getClassLoader().getResource("/").getPath();  
String rootPath = "";  
//windows下  
if("[\\\\".equals(File.separator]())){  
rootPath = classPath.substring(1,classPath.indexOf("/WEB-INF/classes"));  
rootPath = rootPath.replace("/", "\\\\");  
}  
//linux下  
if("/".equals(File.separator)){  
rootPath = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));  
rootPath = rootPath.replace("\\\\", "/");  
}  
return rootPath;  
}