spring mvc获取绝对路径的几种方法

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");
       //可以试试 request.getSession().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 }
复制代码

第2行和第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方法中,想要获取绝对路径,其实也是可以的,参考第一种方法,我们只要获取了ServletContextJ就可以了,可通过以下方法曲线救国。

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

打印出来的结果

原文地址:https://www.cnblogs.com/liuyingke/p/7356310.html