最原始方法获取,适合于小项目,也是最笨的方法
可能导致的问题,如果工程是maven结构,bin编译的class不在web-inf下,完全不起作用,推荐少用
/**
* 得到WebRoot文件夹下的根路径,及web项目的根路径
* @return
*/
public String getWebRootAbsolutePath() {
String path = null;
String folderPath = Path.class.getProtectionDomain().getCodeSource()
.getLocation().getPath();
if (folderPath.indexOf("WEB-INF") > 0) {
path = folderPath.substring(0, folderPath
.indexOf("WEB-INF"));
}
return path;
}
2.通过spring自带的监听获取
在web.xml中加入以下代码
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>tansungWeb.root</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
</listener>
然后在普通的Java类中(不是action中),就可以通过System.getProperty("tansungWeb.root")获取了web根目录了。
然后再拼凑路径的时候,最好不要直接使用/或者\,最好使用File.separatorChar
适合于绝大多数情况,适应于自己框架中木有自定义的监听,采用这个方便快捷
request.getSession().getServletContext().getRealPath("")
request.getRequestURL()
request.getSession().getServletContext().getRealPath(request.getRequestURI())
3.自定义监听工具类
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
SysInfo.realPath = this.context.getRealPath("/");
}
导出引用都可以,放在单实例类的成员变量,适合用于团队开发,框架作业,更为系统和体系化
其他的一些获取路径不多说,如struts获取上下文,spring中获取上下文,
如
request.getSession().getServletContext().getRealPath(request.getRequestURI())