zoukankan      html  css  js  c++  java
  • 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的引用。

  • 相关阅读:
    Python 三级菜单
    linux 下按文件类型删除
    linux 做内网端口映射
    ss
    fio
    libXtst.so.6 is needed by teamviewer-12.0.76279-0.i686
    copy 浅复制 与深复制
    Git 使用方法
    关于 爬虫使用 urllib.urlopen 提交默认 User-Agent值
    Python 官方模块文档
  • 原文地址:https://www.cnblogs.com/roy-blog/p/6363128.html
Copyright © 2011-2022 走看看