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);
打印出來的結果