jsp获取真实或虚拟文件绝对路径
更新:推荐使用 javaweb 获取请求文件绝对路径问题-getServletPath();
google和baidu能找到的就没有一个写法是正确的,当遇到webapps目录或者自定义context的没一个能获取比较准确的方法。
code:
public String getRequestFileRealPath(HttpServletRequest request){
String webRoot = (request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\", "/")+"/").replaceAll("/+", "/"),
context = request.getContextPath(),
uri = request.getRequestURI().replaceAll("/+", "/"),
filePath = (webRoot+uri).replaceAll("/+", "/");
if(!"".equals(context)&&webRoot.endsWith(context+"/")){
return webRoot.substring(0,webRoot.indexOf(context))+uri;
}else{
if(uri.split("/").length>1){
String[] c = uri.split("/");
if(!new File(webRoot+c[1]).exists()){
return (webRoot+(uri.replaceFirst(c[1], ""))).replaceAll("/+", "/");
}
}
}
return filePath;
}