java中几种获取项目路径方式

ava中获得完整的URl字符串

 

 

[java]  view plain copy
 
  1. HttpServletRequest httpRequest=(HttpServletRequest)request;  
  2.           
  3. String strBackUrl = "http://" + request.getServerName() //服务器地址  
  4.                     + ":"   
  5.                     + request.getServerPort()           //端口号  
  6.                     + httpRequest.getContextPath()      //项目名称  
  7.                     + httpRequest.getServletPath()      //请求页面或其他地址  
  8.                 + "?" + (httpRequest.getQueryString()); //参数  
  1. 在jsp和class文件中调用的相对路径不同。在jsp里,根目录是WebRoot 在class文件中,根目录是WebRoot/WEB-INF/classes 当然你也可以用System.getProperty("user.dir")获取你工程的绝对路径。( 不过听说在linux下无法获取,未试验)

  2. 另:在Jsp,Servlet,Java中详细获得路径的方法!

  3. 1.jsp中取得路径:

  4. 以工程名为TEST为例:

  5. (1)得到包含工程名的当前页面全路径:request.getRequestURI()

  6. 结果:/TEST/test.jsp

  7. (2)得到工程名:request.getContextPath()

  8. 结果:/TEST

  9. (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;
}

猜你喜欢

转载自zhitangrui2010.iteye.com/blog/2220367