spring创建web项目的监听器

依赖项

	<!--servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    
    <!--jsp依赖-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>

    <!--为了使用监听器,加入依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>

在Servlet中,每一次页面跳转都会创建一个spring容器,所以要把容器放到全局作用域ServletContext中

// 创建spring的容器对象
// 但是这样做,每一次页面跳转都会创建一个spring容器,所以要把容器放到全局作用域ServletContext中
// 使用监听器,当全局作用域被创建时,创建容器,放到ServletContext中
String config = "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
StudentService studentService = (StudentService)ac.getBean("studentService");

解决方法:使用监听器,当全局作用域被创建时,创建容器,放到ServletContext中

在web.xml文件中配置

<!--配置监听器ContextLoaderListener
        监听器被创建对象后,会读取 /WEB-INF/applicationContext.xml
        为什么要读取配置文件:在监听器中要创建ApplicationContext对象,需要加载配置文件
        /WEB-INF/applicationContext.xml 就是监听器默认读取的spring配置文件路径
        默认路径是在WEB-INF下,可以修改默认路径
    -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!--classpath:默认是从resource目录下-->
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

servlet代码改为:

//这样就能获取到容器对象ac
WebApplicationContext ac = null;
String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
Object attr = getServletContext().getAttribute(key);
if(attr != null){
      ac = (WebApplicationContext) attr;
}

或者使用框架方法,获取容器对象

ServletContext sc = getServletContext();
ac = WebApplicationContextUtils.getWebApplicationContext(sc);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值