您的位置:首页 > 编程语言 > Java开发

JSP、JAVA获取各种路径总结

2012-09-22 11:50 295 查看
3.1 JSP中获得当前应用的相对路径和绝对路径

  根目录所对应的绝对路径:request.getRequestURI()

  文件的绝对路径  :application.getRealPath(request.getRequestURI());

  当前web应用的绝对路径 :application.getRealPath("/");

  取得请求文件的上层目录:new File(application.getRealPath(request.getRequestURI())).getParent()

  3.2 Servlet中获得当前应用的相对路径和绝对路径

  根目录所对应的绝对路径:request.getServletPath();

  文件的绝对路径 :request.getSession().getServletContext().getRealPath

  (request.getRequestURI())

  当前web应用的绝对路径 :servletConfig.getServletContext().getRealPath("/");

  (ServletContext对象获得几种方式:

  

javax.servlet.http.HttpSession.getServletContext()

  javax.servlet.jsp.PageContext.getServletContext()

  javax.servlet.ServletConfig.getServletContext()

  )

  4.java 的Class中获得相对路径,绝对路径的方法

  4.1单独的Java类中获得绝对路径

  根据java.io.File的Doc文挡,可知:

  默认情况下new File("/")代表的目录为:System.getProperty("user.dir")。

  一下程序获得执行类的当前路径

  

package org.cheng.file;

  import java.io.File;

  public class FileTest {

  public static void main(String[] args) throws Exception {

  System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));

  System.out.println(FileTest.class.getClassLoader().getResource(""));

  System.out.println(ClassLoader.getSystemResource(""));

  System.out.println(FileTest.class.getResource(""));

  System.out.println(FileTest.class.getResource("/")); //Class文件所在路径

  System.out.println(new File("/").getAbsolutePath());

  System.out.println(System.getProperty("user.dir"));

  }

  }

  4.2服务器中的Java类获得当前路径(来自网络)

  (1).Weblogic

  WebApplication的系统文件根目录是你的weblogic安装所在根目录。例如:如果你的weblogic安装在c:/bea /weblogic700.....那么,你的文件根路径就是c:/.所以,有两种方式能够让你访问你的服务器端的文件:a.使用绝对路径:比如将你的参数文件放在c:/yourconfig/yourconf.properties,直接使用 new FileInputStream("yourconfig/yourconf.properties");b.使用相对路径:相对路径的根目录就是你的
webapplication的根路径,即WEB-INF的上一级目录,将你的参数文件放在yourwebapp/yourconfig /yourconf.properties,这样使用:new FileInputStream("./yourconfig/yourconf.properties");这两种方式均可,自己选择。

  (2).Tomcat

  在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin

  (3).Resin

  不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET的路径为根.比如用新建文件法测试File f = new File("a.htm");这个a.htm在resin的安装目录下

  (4).如何读相对路径哪?

  在Java文件中getResource或getResourceAsStream均可

  例:getClass().getResourceAsStream(filePath);//filePath可以是" /filename",这里的/代表web发布根路径下WEB-INF/classes默认使用该方法的路径是:WEB-INF/classes。已经在 Tomcat中测试。

  总结:

  通过上面内容的使用,可以解决在Web应用服务器端,移动文件,查找文件,复制删除文件等操作,同时对服务器的相对地址,绝对地址概念更加清晰。建议参考URI,的RFC标准文挡。同时对Java.io.File. Java.net.URI.等内容了解透彻对其他方面的理解可以更加深入和透彻。

/article/5513304.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: