java如何得到项目的webRoot 路径

java如何得到项目的webRoot 路径,第1张

使用JAVA后台代码取得WEBROOT物理路径,可以有如下两种方式:

1、使用JSP Servlet取得WEB根路径可以用requestgetContextPath(),相对路径requestgetSession()getServletContext()getRealPath("/"),它们可以使用我们很容易取得根路径。

2、如果使用了spring, 在WEB-INF/webxml中,创建一个webAppRootKey的param,指定一个值(默认为webapproot)作为键值,然后通过Listener,或者Filter,或者Servlet执行String webAppRootKey = getServletContext()getRealPath("/"); 并将webAppRootKey对应的webapproot分别作为Key,Value写到System Properties系统属性中。之后在程序中通过SystemgetProperty("webapproot")来获得WebRoot的物理路径。

具体示例代码如下:

webxml

<xml version="10" encoding="UTF-8">

<web-app version="24"

xmlns=">

需要使用路径时,用下面的方法取得项目根目录的绝对路径(Tools为方法类)

public static String getRootPath() {

String classPath = ToolsclassgetClassLoader()getResource("/")getPath();

String rootPath = "";

//windows下

if("\\"equals(Fileseparator)){

rootPath = classPathsubstring(1,classPathindexOf("/WEB-INF/classes"));

rootPath = rootPathreplace("/", "\\");

}

//linux下

if("/"equals(Fileseparator)){

rootPath = classPathsubstring(0,classPathindexOf("/WEB-INF/classes"));

rootPath = rootPathreplace("\\", "/");

}

return rootPath;

}

java获取根路径有两种方式:

1),在servlet可以用一下方法取得:

requestgetRealPath(“/”) 例如:filepach = requestgetRealPath(“/”) ”//upload//”;

2),不从jsp,或servlet中获取,只从普通java类中获取:

String path =

getClass()getProtectionDomain()getCodeSource()getLocation()getPath();

SAXReader() saxReader = new SAXReader();

if(pathindexOf(“WEB-INF”)>0){

path = pathsubstring(0,pathindexOf(“/WEB-INF/classes”) 16);

// ‘/WEB-INF/classes’为16位

document = saxReaderread(path filename);

}else{

document = saxReaderread(getClass()getResourceAsStream(filename));

}

weblogic tomcat 下都有效

String path =

getClass()getProtectionDomain()getCodeSource()getLocation()getPath();

<!--EndFragment-->

实现思路就是先获取到类路径,之后再类路径中截取出相应的项目根路径(因为是知道类和项目的相对位置的)。

可以通过“ 类名classgetResource("")getPath()”方法实现获取到当前的路径。

举例:”String path = XMLSclassgetResource("")getPath()“

解释:以上语句就是获取到XMLS编译后的绝对路径(无法获取到java文件路径的,因为java运行的都是class文件),之后根据实际情况截取任意位置的路径都可以。

java获取src目录下文件夹的相对路径问题如下:

目录结构:

project

out

src

readjava

testtxt

files

opts

项目为priject

out目录为class输出目录

src下为文件目录

src下有两个包,files、opts

想通过相对路径获取testtxt的路径

但是用反射只能获取到class,也就是out里的路径

输出后的目录不就是在out里面了,那个里面的和src里面的文件是一样的, getClass()getResource()就可以得到classpath了啊

看看设置的资源文件编译路径

楼主这个路径C:\\Documents and Settings\\Administrator\\桌面\\Tomcat60\\webapps\\webmusic这块要是固定的 可以使用字符串 *** 作,如:

String s = "C:\\Documents and Settings\\Administrator\\桌面\\Tomcat60\\webapps\\webmusic\\image/1jpg";

s=ssubstring(0,69);

以上就是关于java如何得到项目的webRoot 路径全部的内容,包括:java如何得到项目的webRoot 路径、java怎么获取上传文件的路径、linux下 Java如何获取文件的绝对路径等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9635692.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-30
下一篇2023-04-30

发表评论

登录后才能评论

评论列表(0条)

    保存