Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When the Servlet container starts, it:</p> <ol> <li>reads <code>web.xml</code>;</li> <li>finds the declared Servlets in the classpath; and</li> <li>loads and instantiates each Servlet <strong>only once</strong>.</li> </ol> <p>Roughly, like this:</p> <pre><code>String urlPattern = parseWebXmlAndRetrieveServletUrlPattern(); String servletClass = parseWebXmlAndRetrieveServletClass(); HttpServlet servlet = (HttpServlet) Class.forName(servletClass).newInstance(); servlet.init(); servlets.put(urlPattern, servlet); // Similar to a map interface. </code></pre> <p>Those Servlets are stored in memory and reused every time the request URL matches the Servlet's associated <code>url-pattern</code>. The servlet container then executes code similar to:</p> <pre><code>for (Entry&lt;String, HttpServlet&gt; entry : servlets.entrySet()) { String urlPattern = entry.getKey(); HttpServlet servlet = entry.getValue(); if (request.getRequestURL().matches(urlPattern)) { servlet.service(request, response); break; } } </code></pre> <p>The <a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServlet.html#service%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29" rel="noreferrer"><code>GenericServlet#service()</code></a> on its turn decides which of the <code>doGet()</code>, <code>doPost()</code>, etc.. to invoke based on <a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html#getMethod%28%29" rel="noreferrer"><code>HttpServletRequest#getMethod()</code></a>.</p> <p>You see, the servletcontainer reuses the <strong>same servlet instance</strong> for every request. In other words: the servlets are shared among <em>every request</em>. That's why it's extremely important to write servlet code the threadsafe manner --which is actually simple: just do <strong>not</strong> assign request or session scoped data as servlet instance variables, but just as method local variables. E.g.</p> <pre><code>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. } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload