zoukankan      html  css  js  c++  java
  • Spring如何获取ServletContext

    一、获取ServletContext的几种方式

    实现WebApplicationInitializer接口,重写onStartup方法
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import org.springframework.web.WebApplicationInitializer;
    
    public class ApplicationInitializer implements WebApplicationInitializer {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            System.out.println(servletContext);
        }
    }
    使用ServletContextListener

    创建一个实现ServletContextListener的监听器

    // 必不可少,声明为监听器,注册到web容器中
    @WebListener
    public class InitContextListener implements ServletContextListener {
        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            ServletContext servletContext = servletContextEvent.getServletContext();
            System.out.println(servletContext);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
    
        }
    }
    使用ContextLoader
    WebApplicationContext webApplicationContext  = ContextLoader.getCurrentWebApplicationContext();
    ServletContext servletContext = webApplicationContext.getServletContext();
    使用spring自动注入
    @Autowired
    private ServletContext servletContext;
    request获取servletContext
    ServletContext servletContext = request.getServletContext();

    二、使用ServletContext存取

    添加属性:setAttribute(String name,Object ob);

    得到值:   getAttribute(String);    //返回Object

    删除属性:removeAttribute(String name);

  • 相关阅读:
    爬虫框架之Scrapy——爬取某招聘信息网站
    爬虫框架之Scrapy
    centos6创建用户,设置ssh登录
    VmWare扩展硬盘分区
    centos安装python与jdk
    vmware安装——CentOS-6.5和Mysql
    python——读取MATLAB数据文件 *.mat
    经纬度坐标互换
    原码, 反码, 补码 详解
    MATLAB——textscan
  • 原文地址:https://www.cnblogs.com/myitnews/p/12905269.html
Copyright © 2011-2022 走看看