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");  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);

打印出来的结果

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM