servletcontext的小结

ServletContext对象:每个Servlet可以通过ServletContext对象来获取web应用的配置信息,也从侧面说明了ServletContext代表了这个web应用,也就是通过servlet可以获得真个web应用的配置信息

功能:tomcat为每个web项目都创建一个ServletContext实例,tomcat在启动时创建,服务器关闭时销毁,在一个web项目中共享数据,管理web项目资源,为整个web配置公共信息等,通俗点讲,就是一个web项目,就存在一个ServletContext实例,每个Servlet读可以访问到它。

Web容器在启动时会为每个web应用创建一个ServletContext对象,而这个ServletContext对象就代表当前这个web应用。因为一个ServletContext对象代表一个web应用,所以该web应用中所有的Servlet和其他资源都共享一个ServletContext对象,这时,我们就可以通过ServletContext对象进行Servlet对象之间的通讯。而ServletContext对象也称之为Context域对象。 

这是Servlet中一个非常重要的类。当然ServletContext对象还可以从父类的方法中直接获取,获取方式:getServletContext(); 、getServletConfig().getServletContext();应该还有其他的获取方式

也就是说我们只要拿到了ServletContext对象,通过读取这个对象,就可以获得相应的配置信息,从而进行下一步操作,比如获取到spring的bean,通过读取配置文件中的<bean>

有三种方式可以获得(spring项目中获取ApplicationContext对象,然后手动获取bean):

ApplicationContext的介绍:如果说BeanFactory是Spring的心脏,那么ApplicationContext就是完整的身躯了。ApplicationContext由BeanFactory派生而来,提供了更多面向实际应用的功能

Spring上下文(ApplicationContext)的获取有三种方式。

   1.通过WebApplicationUtils工具类获取。WebApplicationUtils类是在Spring框架基础包spring-web-3.2.0. RELEASE.jar(我使用的是3.2.0版的jar包,大家可以去spring官网下载最新版的jar)中的类。使用该方法的必须依赖Servlet容器。 使用方法如下: 

ApplicationContext ap =WebApplicationUtils.getWebApplicationContext(servletContextParam)
怎么得到具体的bean:
Userservice us=ap.getBean("UserserviceId",Userservice.class)
或者:
Userservice us=(Userservice)ap.getBean("UserserviceId")这是强制转换的写法

     其中servletContextParam是你需要传入的Servlet容器参数。

     2. 通过ClassPathXmlApplicationContext类获取。ClassPathXmlApplicationContext 类是在Spring框架基础包spring-context-3.2.0. RELEASE.jar(我使用的是3.2.0版的jar包,大家可以去spring官网下载最新版的jar)中的类。使用方法如下:

ApplicationContext ap = new ClassPathXmlApplicationContext("applicationContext.xml");


     其中applicationContext.xml文件放在src下面,这样就保证可以读取到该文件。这个XML的作用是集中配置和管理所有Bean。

    applicationContext.xml代码: 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        //中间部分是你自己配置的所有bean
</beans>



猜你喜欢

转载自www.cnblogs.com/cherishforchen/p/10937624.html