java类中获取ServletContext的方法

时间:2023-03-09 21:27:12
java类中获取ServletContext的方法

  起因是我想要获取一个相对路径,需要用到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的引用。