获取路径

获取路径的方法:


1、在java类中获取路径(com.zhanggm.Test.java)


// 方式1,通过classZLoader获取路径,参数必须是""。
this.getClass().getClassLoader().getResource("");
// 结果为:“file:/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/”,类型是java.net.URL。
this.getClass().getClassLoader().getResource("").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/”,类型是String。

// 方式2,直接获取,参数可以随意指定,""获取当前类所在的路径、"/"获取根路径(即.../classes/)、"/xx/xx"、"/xx/xx/"等
this.getClass().getResource("").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/com/zhanggm/”
this.getClass().getResource("/").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/”
this.getClass().getResource("/com").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/com”
this.getClass().getResource("/com/").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/com/”
this.getClass().getResource("com").getPath();
// 结果为:“null”
this.getClass().getResource("com/").getPath();
// 结果为:“null”
this.getClass().getResource("/zhanggm").getPath();
// 结果为:“null”




2、通过 request 获取路径


String absolutePath= request.getRealPath("/");
// 结果为:“/D:/workspace/strutsTest/WebRoot/”,即获取是本地的绝对路径,WEB-INF所在的目录。这个路径可以用来存放文件。

String contextPath = request.getContextPath();
// 结果为:“1、有项目名:"/xxPojectName",2、没有项目名:""”




3、在 struts2 中获取路径


String absolutePath = org.apache.struts2.ServletActionContext.getServletContext().getRealPath("/upload/");
// 结果为:“/D:/workspace/strutsTest/WebRoot/upload/”,即获取是本地的绝对路径。这个路径可以用来存放文件。




4、在 spring 中获取路径


/**
* 获取应用的路径
*
* @return 应用的路径
*/
protected String getAppPath() {
org.springframework.web.context.WebApplicationContext webApplicationContext = org.springframework.web.context.ContextLoader.getCurrentWebApplicationContext();
javax.servlet.ServletContext servletContext = webApplicationContext.getServletContext();
return servletContext.getContextPath();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值