天天看点

J2EE中获得web路径和类路径总结

以工程名为test为例

一、取得web中的路径

①包含工程名的当前页面全路径request.getrequesturi() 

/test/test.jsp

②工程名:request.getcontextpath() 

/test

③当前页面所在目录下全名称request.getservletpath() 

若页面在jsp目录下/test/jsp/test.jsp

④页面所在服务器的全路径request.getsession().getservletcontext().getrealpath("a.jsp"); 

d:\resin\webapps\test\test.jsp

若想定位到某个文件夹则getservletcontext().getrealpath("web-inf");

getservletcontext()其实取得的是application

⑤页面所在服务器的绝对路径:request.getsession().getservletcontext().(request.getrequesturi()).getparent(); 

d:\resin\webapps\test 

二、取得类路径

①类的绝对路径:class.class.getclass().getresource("/").getpath() 

/d:/test/webroot/web-inf/classes/pack/ 

②工程的路径:system.getproperty("user.dir") 

d:\test 

原帖地址:http://deific.iteye.com/blog/1172107