webApplicationContext 与servletContext

1.WebApplicationContext的研究

      ApplicationContext是spring的核心,Context通常解释为上下文环境,用“容器”来表述更容易理解一些,ApplicationContext则是“应用的容器了”了。

     spring把bean放在这个容器中,在需要的时候,用getBean()方法取出,在web应用中,会用到webApplicationContext,继承自ApplicationContext

    在web.xml初始化WebApplicationContext:

   <context-param>

           <param-name>contextConfigLocation</param-name>

           <param-value>/WEB-INF/applicationContext.xml</param-value>

  </context-param>

<listener>

     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

或者用ContextLoaderServlert亦可(加<load-on-startup>1</load-on-startup>)

 

2.ServletContext详解

    ServletContext 是Servlet与Servlet容器之间直接通信的接口,Servlet容器在启动一个web应用时,会为它创建一个ServletContext对 象,每个web应用有唯一的ServletContext对象,同一个web应用的所有Servlet对象共享一个 ServletContext,Servlet对象可以通过它来访问容器中的各种资源

存取共享数据方法:

 setAttribute(String name,Object obj)

getAttribute(String name)


     WebApplicationContext  ctx=WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
       
         DataSource ds=    ctx.getBean(DataSource.class);
         jRExportService.setDataSource(ds)

这里得到了spring 的webApplicationContext ,spring的bean都放在里面,然后直接getBean就可以得到了


 WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。

   ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。

  由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。

1.多个Servlet通过ServletContext对象实现数据共享。

InitServletService方法中利用ServletContext对象存入需要共享的数据

/*获取ServletContext对象*/  

ServletContext context = this.getServletContext();   

//存入共享的数据    

context.setAttribute("name", "haha"); 

在其它的Servlet中利用ServletContext对象获取共享的数据   

/*获取ServletContext对象*/  

ServletContext context = this.getServletContext();   

//获取共享的数据   

String name = context.getAttribute("name");   

System.out.println("共享的内容值是:"+name);  

2.获取WEB应用的初始化参数。

web.xml文件中配置需要初始化的参数信息。

<web-app>   

 <context-param>   

<param-name>url</param-name>   

<param-value>jdbc:mysql://localhost:3306/4g</param-value>   

 </context-param>   

<context-param>   

 <param-name>password</param-name>   

 <param-value>1314qr</param-value>   

 </context-param>   

 <context-param>   

  <param-name>user</param-name>   

  <param-value>root</param-value>   

  </context-param>   

</web-app>  

DemoServletdoPost方法中测试获取初始化参数的步骤如下:   

/*获取ServletContext对象*/  

 ServletContext context = this.getServletContext();   

/*获取初始化参数*/  

//获取指定名称的初始化参数   

String url = context.getInitParameter("url"); 

 //获取web.xml文件中所有的初始化应用参数          

 Enumeration<String> enumer = context.getInitParameterNames();   

while(enumer.hasMoreElements()){   

String name = enumer.nextElement();   

 String value = context.getInitParameter(name);   

 System.out.println(name+"=========="+value);   

    }   

2.实现Servlet的转发:

在测试的Servlet中实现转发的步骤如下:  

/*要利用ServletContext对象实现转发获取对象*/  

ServletContext context = this.getServletContext();   

 //request对象中存入name属性    

request.setAttribute("name", "haha");   

 /*根据转发的地址获取 RequestDispatcher对象*/  

RequestDispatcher  rd  = context.getRequestDispatcher("/index.jsp");   

//调用转发方法 以下采用任意方法即可    

rd.forward(request, response);   

  //rd.include(request, response);   

注意:forwardinclude的区别 

forward方法是把请求的内容转发到另外的一个servlet.include是把另一个servlet处理过后的内容拿过来.

(forward方法调用后在响应中的没有提交的内容被自动消除。将请求转发给其他的Servlet后,由

    被调用的Servlet负责对请求做出响应,而原先Servlet的执行则终止。      

   include方法使原先的Servlet和转发到的Servlet都可以输出响应信息,即原先的Servlet还可以继续输出响应信息

3.利用ServletContext对象读取资源文件。  

读取资源文件(properties文件(属性文件))的三种方式

配置的properties的内容如下:   

url=jdbc\:mysql\://localhost\:3306/3g ; 

user=root;

password=root;  

获取实现的代码如下:   

/*获取ServletContext对象*/  

ServletContext context = this.getServletContext();     

//第一种方式    

URL url = context.getResource("WEB-INF/classes/db.properties");   

InputStream is =  url.openStream();   

//第二种方式   

 /*读取db.properties文件*/  

String path =context.getRealPath("WEB-INF/classes/db.properties");   

 /*根据文件的路径 构建文件对象*/  

File file = new File(path);   

 /*根据file文件对象 创建输入流*/  

InputStream is = new FileInputStream(file);   

//第三种方式   

InputStream is = context.getResourceAsStream("WEB-INF/classes/db.properties ");    

 以三种方式任意一种可以:    

  /*解析properties的文件*/  

     Properties prop = new Properties();   

     //从输入流中读取属性列表(键和元素对)。   

      prop.load(is);   

      Set<String> set = prop.stringPropertyNames();   

       //遍历set集合   

       Iterator<String> it = set.iterator();   

       while(it.hasNext()){   

           String key = it.next();   

           String value = prop.getProperty(key);   

           System.out.println(key+"-----"+value);   

              }   


  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代码解析2,部分摘抄 简单的说,在web容器中,通过ServletContext为Spring的IOC容器提供宿主环境,对应的建立起一个IOC容器的体系。其中,首先需要建立的是根上下文,这个上下文持有的对象可以有业务对象,数据存取对象,资源,事物管理器等各种中间层对象。在这个上下文的基础上,和web MVC相关还会有一个上下文来保存控制器之类的MVC对象,这样就构成了一个层次化的上下文结构。在web容器中启动Spring应用程序就是一个建立这个上下文体系的过程。Spring为web应用提供了上下文的扩展接口 WebApplicationContext: 如转载请注明,转载自:关注Java[http://www.gbsou.com] 本文链接: http://www.gbsou.com/2009/08/11/214.html - - Java代码 public interface WebApplicationContext extends ApplicationContext { //这里定义的常量用于在ServletContext中存取根上下文 String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT"; …… //对WebApplicationContext来说,需要得到Web容器的ServletContext ServletContext getServletContext(); } public interface WebApplicationContext extends ApplicationContext { //这里定义的常量用于在ServletContext中存取根上下文 String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT"; ...... //对WebApplicationContext来说,需要得到Web容器的ServletContext ServletContext getServletContext(); } 而一般的启动过程,Spring会使用一个默认的实现,XmlWebApplicationContext – 这个上下文实现作为在web容器中的根上下文容器被建立起来,具体的建立过程在下面我们会详细分析。 Java代码 public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext { /** 这是和web部署相关的位置信息,用来作为默认的根上下文bean定义信息的存放位置*/ public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml"; public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/"; public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml"; //我们又看到了熟悉的loadBeanDefinition,就像我们前面对IOC容器的分析中一样,这个加载工程在容器的refresh()的时候启动。 protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException { //对于XmlWebApplicationContext,当然使用的是XmlBeanDefinitionReader来对bean定义信息来进行解析 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); } protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) { } //使用XmlBeanDefinitionReader来读入bean定义信息 protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { String[] configLocations = getConfigLocations(); if (configLocations != null) { for (int i = 0; i < configLocations.length; i++) { reader.loadBeanDefinitions(configLocations[i]); } } } //这里取得bean定义信息位置,默认的地方是/WEB-INF/applicationContext.xml protected String[] getDefaultConfigLocations() { if (getNamespace() != null) { return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX}; } else { return new String[] {DEFAULT_CONFIG_LOCATION}; } } } public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext { /** 这是和web部署相关的位置信息,用来作为默认的根上下文bean定义信息的存放位置*/ public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml"; public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/"; public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml"; //我们又看到了熟悉的loadBeanDefinition,就像我们前面对IOC容器的分析中一样,这个加载工程在容器的refresh()的时候启动。 protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException { //对于XmlWebApplicationContext,当然使用的是XmlBeanDefinitionReader来对bean定义信息来进行解析 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); } protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) { } //使用XmlBeanDefinitionReader来读入bean定义信息 protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { String[] configLocations = getConfigLocations(); if (configLocations != null) { for (int i = 0; i < configLocations.length; i++) { reader.loadBeanDefinitions(configLocations[i]); } } } //这里取得bean定义信息位置,默认的地方是/WEB-INF/applicationContext.xml protected String[] getDefaultConfigLocations() { if (getNamespace() != null) { return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX}; } else { return new String[] {DEFAULT_CONFIG_LOCATION}; } } } 对于一个Spring激活的web应用程序,可以通过使用Spring代码声明式的指定在web应用程序启动时载入应用程序上下文(WebApplicationContext),Spring的ContextLoader是提供这样性能的类,我们可以使用 ContextLoaderServlet或者ContextLoaderListener的启动时载入的Servlet来实例化Spring IOC容器 – 为什么会有两个不同的类来装载它呢,这是因为它们的使用需要区别不同的Servlet容器支持的Serlvet版本。但不管是 ContextLoaderSevlet还是 ContextLoaderListener都使用ContextLoader来完成实际的WebApplicationContext的初始化工作。这个ContextLoder就像是Spring Web应用程序在Web容器中的加载器booter。当然这些Servlet的具体使用我们都要借助web容器中的部署描述符来进行相关的定义。 下面我们使用ContextLoaderListener作为载入器作一个详细的分析,这个Servlet的监听器是根上下文被载入的地方,也是整个 Spring web应用加载上下文的第一个地方;从加载过程我们可以看到,首先从Servlet事件中得到ServletContext,然后可以读到配置好的在web.xml的中的各个属性值,然后ContextLoder实例化WebApplicationContext并完成其载入和初始化作为根上下文。当这个根上下文被载入后,它被绑定到web应用程序的ServletContext上。任何需要访问该ApplicationContext的应用程序代码都可以从WebApplicationContextUtils类的静态方法来得到:

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值