1.servlet中获取路径
System.out.println("服务器中的路径:"+request.getContextPath());
//服务器中的路径:/proj_valuation
System.out.println("路径:"+request.getServletPath());
//路径:/FileUploadServlet
System.out.println("绝对路径:"+request.getSession().getServletContext().getRealPath("/"));
//绝对路径:E:\apache-tomcat-6.0.26\webapps\proj_valuation\
String pathStr=request.getSession().getServletContext().getRealPath("/");
if(!pathStr.isEmpty())
{
pathStr = pathStr.replace('\\', '/');
}
2.java中获取路径
String path1 =getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
//路径1/E:/apache-tomcat-6.0.26/webapps/proj_valuation/WEB-INF/lib/cglib-2.1.3.jar
String path2 =this.getClass().getClassLoader().getResource("/").getPath();
//classes路径1/E:/apache-tomcat-6.0.26/webapps/proj_valuation/WEB-INF/classes/
String path3 = FlexContext.getHttpRequest().getContextPath();
//blazeDS获取到的ContextPath路径/proj_valuation
String path4 = FlexContext.getHttpRequest().getSession().getServletContext().getRealPath("/");
//blazeDS获取到的RealPath路径E:\apache-tomcat-6.0.26\webapps\proj_valuation\
System.out.println("路径1"+path1);
System.out.println("classes路径1"+path2);
System.out.println("blazeDS获取到的ContextPath路径"+path3);
System.out.println("blazeDS获取到的RealPath路径"+path4);
if(!path4.isEmpty())
{
path4 = path4.replace('\\', '/');
}
3.网上的一些总结
1.可以在servlet的init方法里
String path = getServletContext().getRealPath("/");
这将获取web项目的全路径
例如 :E:\eclipseM9\workspace\tree\
tree是我web项目的根目录
2.你也可以随时在任意的class里调用
this.getClass().getClassLoader().getResource("/").getPath();
这将获取 到classes目录的全路径
例如 : E:\eclipseM9/workspace/tree/WEB-INF/classes/
这个方法也可以不在web环境里确定路径,比较好用
3.request.getContextPath();
获得web根的上下文环境
如 /tree
tree是我的web项目的root context
/*jsp 取得当前目录的路径
path=request.getRealPath("");
/*得到jbossWEB发布临时目录 warUrl=.../tmp/deploy/tmp14544test-exp.war/
path=C:\jboss-4.0.5.GA\server\default\tmp\deploy\tmp14544test-exp.war\
String path = (String)request.getContextPath();
/*得到项目(test)应用所在的真实的路径 path=/test
String path = request.getRequestURI();
/*得到应用所在的真实的路径 path=/test/admin/admindex.jsp
String savePath=request.getRealPath(request.getServletPath());
/*得到当前文件的磁盘绝对路径
//JAVA 取得当前目录的路径
File file=new File(".");
String path=file.getAbsolutePath();
path=file.getPath();
/*得到jboss运行目录 path=C:\jboss-4.0.5.GA\bin\
4.一些有用或者没有的资料
web工程:
servletContext.getRealPath("/");(当前web应用的绝对路径)
根目录所对应的绝对路径:request.getServletPath();
普通的java:
单独的Java类中获得绝对路径:
FileTest.class.getClassLoader().getResource("")
JSP/Servlet中获得当前web应用程序的相对路径和绝对路径:http://blogold.chinaunix.net/u2/65993/showart_574062.html