---
title: "servlet specification笔记 II"
author: "燮羽天翔"
date: "2010-05-22T14:26:21Z"
tags: []
categories: ["编程语言"]
slug: "servlet-specification-ii"
draft: false
lastmod: "2010-05-22T14:26:21Z"
id: 672547
url: "https://devilkirin.iteye.com/blog/672547"
---

第四章 Servlet Context

 

1\. Introduction to the ServletContext Interface

     这个接口定义了一个servlet对它运行于其中的Web application的概览。使用ServletContext对象，一个servlet可以记录时间，获得资源的URL，存取属性，而这些属性又可以被别的context访问。一个ServletContext根植于一个Web server的一个已知path。比如，一个ServletContext可以被定为于http://www.mycorp.com/catalog.所有开始于/catalog请求路径的请求都会被导向跟这个ServletContext相关的Web application。

2\. Scope of a ServletContext interface

     对于每个部署到一个容器的网络应用程序，都会有一个ServletContext interface的实例与之相关联。当这个容器被分布到许多个vm上的时候，一个Web application会在每个jvm上都拥有一个ServletContext实例。

     在一个容器中，没有被部署到一个Web app中的servlet，隐含地作为一个“默认”Web app的一部分，同时拥有一个默认的ServletContext。在一个分布式容器中，默认的ServletContext是不能被分配的(non-distributable)而且只能存在于一个jvm中。

3.Initialization Parameters

     servlet可以访问一个Web app相关的context的初始化参数，他们是被app开发者在部署描述文件中定义的

     getInitParameter   getInitParameterNames

4.Context Attributes

     setAttribute  getAttribute getAttributeNames removeAttribute

     4.1 Context Attributes in a DIstributed Container

           上下文属性在他们所创建的jvm上是本地化的。这样防止了ServletContext属性成为一个在分布式容器中的一个可共享内存。当信息需要在运行在分布式环境中的servlets之间共享的时候，应该被置于一个session中，或者是DB，EJB部件中。

5，Resources

     ServletContext接口仅仅对属于Web app一部分的静态内容文档的结构层次的直接访问，包括HTML GIF或者JPEG，通过以下方法。 getResource      getResourceAsStream

     他们以一个用"/"起始的字符串作为变量。他们只能访问静态资源，如JSP之类的动态资源是不会被解析为输出的。资源的完整列表可以通过getResourcePaths(String path)获得

6\. Multiple Hosts and ServletContexts

     Web servers可以在一个server中支持多个共享同一个IP地址的逻辑主机。即“virtual hosting”，ServletContext不能被virtual hosts所共享。

7\. Reloading Considerations 7.1 Temporary working Directories

     javax.servlet.context.tempdir --&gt; java.io.File