以工程名为test为例:
(1)得到包含工程名的当前页面全路径:request.getRequestURI()
结果:/test/index.jsp
(2)得到工程名:request.getContextPath()
结果:/test
(3)得到当前页面所在目录下全名称:request.getServletPath()
结果:如果页面在jsp目录下 /test/index.jsp
(4)得到页面所在服务器的全路径:application.getRealPath("页面.jsp")
结果:D:\resin\webapps\test\index.jsp
(5)得到页面所在服务器的绝对路径:absPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
结果:D:\resin\webapps\test
(6)在页面中加入${ pageContext.request.contextPath }也可以得到绝对路径
2.在类中取得路径:
(1)类的绝对路径:Class.class.getClass().getResource("/").getPath()
结果:/D:/test/WebRoot/WEB-INF/classes/pack/
(2)得到工程的路径:System.getProperty("user.dir")
结果:D:\test
3.在Servlet中取得路径:
(1)得到工程目录:request.getSession().getServletContext().getRealPath("") 参数可具体到包名。
结果:E:\Tomcat\webapps\test
(2)得到IE地址栏地址:request.getRequestURL()
结果:http://localhost:8080/test/test
(3)得到相对地址:request.getRequestURI()
结果:/test/test
3.在js中取得路径:
//js获取项目根路径,如:http://localhost:8083/uimcardprj
function getRootPath(){
//获取当前网址,如:http://localhost:8083/uimcardprj/share/meun.jsp
var curWwwPath=window.document.location.href;
//获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
var pathName=window.document.location.pathname;
var pos=curWwwPath.indexOf(pathName);
//获取主机地址,如:http://localhost:8083
var localhostPaht=curWwwPath.substring(0,pos);
//获取带"/"的项目名,如:/uimcardprj
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
return(localhostPaht+projectName);
}
1.如何获得当前文件路径
常用:
(1).Test.class.getResource("")
得到的是当前类FileTest.class文件的URI目录。不包括自己!
(2).Test.class.getResource("/")
得到的是当前的classpath的绝对URI。
(3).Thread.currentThread().getContextClassLoader().getResource("")
得到的也是当前ClassPath的绝对URI。
(4).Test.class.getClassLoader().getResource("")
得到的也是当前ClassPath的绝对URI。
(5).ClassLoader.getSystemResource("")
得到的也是当前ClassPath的绝对URI。
尽量不要使用相对于System.getProperty("user.dir")当前用户目录的相对路径,后面可以看出得出结果五花八门。
(6) new File("").getAbsolutePath()也可用。
2.Web服务器
(1).Tomcat
在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin
(2).Resin
不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成Servlet的路径为根.比如用新建文件法测试File f = new File("a.htm");
这个a.htm在resin的安装目录下
(3).如何读文件
使用ServletContext.getResourceAsStream()就可以
(4).获得文件真实路径
String
不建议使用request.getRealPath("/");
本人水平有限,欢迎大家指出错误,进行技术交流。