xdxxdx
www.xdxxdxxdx.com

  起因是我想要获取一个相对路径,需要用到servletContext的getRealPath()方法,于是上网搜索,找到两种方法来获取ServletContext.

  方法1:第一种方法是这样的:

  ServletActionContext.getServletContext();

  或者ServletContext servletContext= req.getServletContext();其中req是一个HttpServletRequest对象。

  上述两种方法第一种局限于Struts中使用,且两种方法只有在发生web请求的时候才能获取到ServletContext对象。

  方法2:WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();    

  ServletContext servletContext = webApplicationContext.getServletContext();

  这种方法通过spring容器来获取servletContext对象,是可以获取到的。其实是因为web项目在启动的时候,将WebApplicationContext作为属性注入到ServletContext的同时,也保留了对ServletContext的引用。

 

posted on 2017-02-03 17:39  xdxxdx  阅读(14732)  评论(0编辑  收藏  举报