xdxxdx
www.xdxxdxxdx.com

1.首先如果是在一个controller方法中,则很简单,直接用下面语句。

 1     @RequestMapping("categoryHome")
 2     public ModelAndView categoryHome(ParamModel pm,HttpServletRequest req) {
 3         String path=req.getServletContext().getContextPath();
 4         System.out.println(path);
 5         String realPath=req.getServletContext().getRealPath("/uploadFile");
 6         System.out.println(realPath);
 7         ModelAndView mv = new ModelAndView("back/category/CategoryHome");
 8         mv.addObject("pm", pm);
 9         return mv;
10     }

第3行和第5行分别获取到项目的根目录和/uploadFile的绝对目录,打印如下。

2.还有一种方法是在web.xml配置如下代码

<context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>www.qgranite.com</param-value>
</context-param>

然后在java代码中我们可以这样来获取绝对路径。

 String basePath = System.getProperty("www.qgranite.com");
System.out.println("basePath:"+basePath);

打印结果如下:

3.当我们不在controller方法中,想要获取绝对路径,其实也是可以的,参考第一种方法,我们只要获取了ServletContext就可以了,可通过以下方法曲线救国。

    WebApplicationContext webApplicationContext = ContextLoader
                .getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext
                .getServletContext();
        // 得到文件绝对路径
        String realPath = servletContext.getRealPath("/uploadFile");
        System.out.println("realPath:"+realPath);

打印出来的结果

 

posted on 2017-06-22 17:23  xdxxdx  阅读(28907)  评论(0编辑  收藏  举报