我在jsp页面可以调用this.getServletContext().getRealPath("/") 获取绝对路径
但是在java文件中,我该如何调用这个方法?是要把ServletContext对象显式传入到java类中吗?
谢谢了!

解决方案 »

  1.   

    如果在普通类中使用 application对象,你可以写一个构造方法。import javax.servlet.ServletContext;
    public class test(){
        public ServletContext context=null;
        public test(ServletContext context){
              this.context=context;     
        }
        public void other{            //这里可以就可以通过 context.get...方法获取路径了。
         }}
      

  2.   

    java.io.File.getAbsolutePath()?
    返回的是这个路径
    TOMCAT E:\Program Files\Java\Tomcat 5.5\bin\
    WEBSPHERE /apps/IBM/WebSphere/AppServer/profiles/AppSrv01/
    (gerRealPath返回:/apps/IBM/WebSphere/AppServer/profiles/AppSrv01/installedApps/linuxNode01Cell/ss_war.ear/ss.war)
      

  3.   


    我也用过这样的办法,只是这个类可能不是通过jsp直接调用的,还要经过其他类,这样这个ServletContext 就得在这几个类中传递,觉得比较麻烦。
      

  4.   

    不用传ServletContext。
    File uploadfile = new File(filedir + "/" + mFileName); //


    System.out.println("上传文件[" + uploadfile.getAbsolutePath() + "]成功!!"); //
      

  5.   

    如果你在servlet中想获得绝对路径,直接用request.getRealPath("/");就行了
      

  6.   

    是要把ServletContext对象显式传入到java类中吗? 
    没必要这样,可以在servlet中获action中得到路径后传到你要用的地方就可以了