java路径各种使用获取

 

最原始方法获取,适合于小项目,也是最笨的方法
可能导致的问题,如果工程是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())

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值