When the Servlet container starts, it:

  1. reads web.xml;
  2. finds the declared Servlets in the classpath; and
  3. loads and instantiates each Servlet only once.

Roughly, like this:

String urlPattern = parseWebXmlAndRetrieveServletUrlPattern();
String servletClass = parseWebXmlAndRetrieveServletClass();
HttpServlet servlet = (HttpServlet) Class.forName(servletClass).newInstance();
servlet.init();
servlets.put(urlPattern, servlet); // Similar to a map interface.

Those Servlets are stored in memory and reused every time the request URL matches the Servlet's associated url-pattern. The servlet container then executes code similar to:  

for (Entry<String, HttpServlet> entry : servlets.entrySet()) {
String urlPattern = entry.getKey();
HttpServlet servlet = entry.getValue();
if (request.getRequestURL().matches(urlPattern)) {
servlet.service(request, response);
break;
}
}

The GenericServlet#service() on its turn decides which of the doGet()doPost(), etc.. to invoke based on HttpServletRequest#getMethod().

You see, the servletcontainer reuses the same servlet instance for every request. In other words: the servlets are shared among every request. That's why it's extremely important to write servlet code the threadsafe manner --which is actually simple: just do not assign request or session scoped data as servlet instance variables, but just as method local variables. E.g.

public class MyServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object thisIsThreadSafe; thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
}
}

(Comments: I will just add that if the same servlet class is mapped to two different urls in web.xml, then two instances are created. But the general principle still holds, one instance serves multiple requests.)

There is only one instance of the servlet which is reused for multiple requests from multiple clients. This leads to two important rules:

  • don't use instance variables in a servlet, except for application-wide values, most often obtained from context parameters.
  • don't make methods synchronized in a servlet

(same goes for servlet filters and jsps)

According to the Java Servlet Specification Version 3.0 (pp. 6-7), there will be one instance per declaration per JVM  

  

How many instances created in the WebContainer的更多相关文章

  1. 【Cocoa】 Initializing View Instances Created in Interface Builder

    Initializing View Instances Created in Interface Builder View instances that are created in Interfac ...

  2. Java 修饰符

    Java语言提供了很多修饰符,主要分为以下两类: 访问修饰符 非访问修饰符 修饰符用来定义类.方法或者变量,通常放在语句的最前端.我们通过下面的例子来说明: public class classNam ...

  3. openswan-ipsec.conf配置说明

    Name ipsec.conf - IPsec configuration and connections Description The optional ipsec.conf file speci ...

  4. JAVA修饰符

    修饰符用来定义类.方法或者变量,通常放在语句的最前端.我们通过下面的例子来说明: public class className { // ... } private boolean myFlag; s ...

  5. CKEditor Html Helpers for ASP.NET MVC3 Razor/WebForms Views

    一.原生方法: 在 razor 中 使用Fckeditor 编辑内容,需要引入js <script src="@Url.Content("~/fckeditor/fckedi ...

  6. openstack Icehouse发布

    OpenStack 2014.1 (Icehouse) Release Notes General Upgrade Notes Windows packagers should use pbr 0.8 ...

  7. 读文档readarx.chm

    readarx.chm <Tips and Techniques> Incremented AutoCAD Registry Number Ideally, a change of reg ...

  8. 函数buf_pool_init

    /********************************************************************//** Creates the buffer pool. @ ...

  9. 译:Spring框架参考文档之IoC容器(未完成)

    6. IoC容器 6.1 Spring IoC容器和bean介绍 这一章节介绍了Spring框架的控制反转(IoC)实现的原理.IoC也被称作依赖注入(DI).It is a process wher ...

随机推荐

  1. Android 反编译apk 详解

    测试环境: win 7 使用工具: CSDN上下载地址: apktool (资源文件获取)  下载          dex2jar(源码文件获取) 下载        jd-gui  (源码查看)  ...

  2. [Jetty] jetty 内存调优

    在start.ini中配置代码如下 -Dcom.sun.management.jmxremote=true -Xmx6144m -XX:PermSize=256M -XX:MaxPermSize=10 ...

  3. Flask+mongodb 实现简易个人博客

    最近学习完了<flask-web开发>,实现了一个简易的个人博客网站,由flask+mongodb+bootstrap做成, 这个软件是在阅读<Flask-Web开发>后写的一 ...

  4. HTML5自学笔记[ 18 ]canvas绘图基础5

    获取图像数据:getImgData(x,y,w,h),返回的是一个ImageData对象,这个对象有三个属性保存图像信息:width/height/data.data是一个数组,保存了每个像素的信息, ...

  5. 详细解读Jquery各Ajax函数

    $.get(),$.post(),$.ajax(),$.getJSON() 一,$.get(url,[data],[callback]) 说明:url为请求地址,data为请求数据的列表,callba ...

  6. IO流--切割 合并文件

    import java.io.*; import java.util.*; public class io { public static void main(String[] args)throws ...

  7. oracle错误码

    ORA-00001: 违反唯一约束条件 (.) ORA-00017: 请求会话以设置跟踪事件 ORA-00018: 超出最大会话数 ORA-00019: 超出最大会话许可数 ORA-00020: 超出 ...

  8. Java script基础

    Java script基础 Js的每个语句后面都要有分号. <script  type="text/java script">所有JS内容</script> ...

  9. Codeforces Round #313 (Div. 2) C. Gerald's Hexagon

    C. Gerald's Hexagon time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  10. String.equals()方法的实现代码,

    通常对String的比较有两种情况,一个是使用==,另一个是使用equals()方法,注意==是对对象的地址进行比较的,而String中的equals()方法是覆盖了Object类的方法,并且实现为对 ...