Servlet Overview: Introduction, Lifecycle, Eclipse Development, URL Mapping, and Thread Safety

This article provides a comprehensive tutorial on Java Servlets, covering their purpose, lifecycle, creation in Eclipse, configuration of web.xml mappings, URL pattern rules, default servlet behavior, thread‑safety concerns, synchronization techniques, and the deprecated SingleThreadModel approach.

Java Captain
Java Captain
Java Captain
Servlet Overview: Introduction, Lifecycle, Eclipse Development, URL Mapping, and Thread Safety

1. Introduction to Servlets

Servlet is a Sun‑provided technology for developing dynamic web resources. To create a servlet you implement the Servlet interface (or extend HttpServlet) and deploy the class to a web server.

2. Servlet Lifecycle

When a client requests a servlet, the web server checks if an instance exists; if not, it loads and creates the instance, calls init(), creates HttpServletRequest and HttpServletResponse objects, invokes service(), and finally calls destroy() when the application stops.

3. Developing a Servlet in Eclipse

Eclipse can generate a web project with the required directory structure and create a servlet class. The generated code looks like:

package gacl.servlet.study;<br/>import java.io.IOException;<br/>import java.io.PrintWriter;<br/>import javax.servlet.ServletException;<br/>import javax.servlet.http.HttpServlet;<br/>import javax.servlet.http.HttpServletRequest;<br/>import javax.servlet.http.HttpServletResponse;<br/>public class ServletDemo1 extends HttpServlet {<br/>    public void doGet(HttpServletRequest request, HttpServletResponse response)<br/>            throws ServletException, IOException {<br/>        response.setContentType("text/html");<br/>        PrintWriter out = response.getWriter();<br/>        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");<br/>        out.println("<HTML>");<br/>        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");<br/>        out.println("  <BODY>");<br/>        out.print("    This is ");<br/>        out.print(this.getClass());<br/>        out.println(", using the GET method");<br/>        out.println("  </BODY>");<br/>        out.println("</HTML>");<br/>        out.flush();<br/>        out.close();<br/>    }<br/>    public void doPost(HttpServletRequest request, HttpServletResponse response)<br/>            throws ServletException, IOException {<br/>        doGet(request, response);<br/>    }<br/>}

The corresponding web.xml entries for the servlet and its mapping are also generated, for example:

<servlet><br/>    <servlet-name>ServletDemo1</servlet-name><br/>    <servlet-class>gacl.servlet.study.ServletDemo1</servlet-class><br/></servlet><br/><servlet-mapping><br/>    <servlet-name>ServletDemo1</servlet-name><br/>    <url-pattern>/servlet/ServletDemo1</url-pattern><br/></servlet-mapping>

4. URL Mapping Configuration

Servlets are mapped to URLs using <servlet> and <servlet-mapping> elements. Multiple mappings can point to the same servlet, and patterns may use exact paths, /* or *.ext wildcards.

4.1 Example of Multiple Mappings

1 <servlet><br/>2     <servlet-name>ServletDemo1</servlet-name><br/>3     <servlet-class>gacl.servlet.study.ServletDemo1</servlet-class><br/>4 </servlet><br/>5 <br/>6 <servlet-mapping><br/>7     <servlet-name>ServletDemo1</servlet-name><br/>8     <url-pattern>/servlet/ServletDemo1</url-pattern><br/>9 </servlet-mapping><br/>10 <br/>11 <servlet-mapping><br/>12     <servlet-name>ServletDemo1</servlet-name><br/>13     <url-pattern>/1.htm</url-pattern><br/>14 </servlet-mapping><br/>15 ... (additional mappings for /2.jsp, /3.php, /4.ASPX)

4.2 Wildcard Mapping

Using /* allows any URL to reach the servlet:

1 <servlet><br/>2     <servlet-name>ServletDemo1</servlet-name><br/>3     <servlet-class>gacl.servlet.study.ServletDemo1</servlet-class><br/>4 </servlet><br/>5 <br/>6 <servlet-mapping><br/>7     <servlet-name>ServletDemo1</servlet-name><br/>8     <url-pattern>/*</url-pattern><br/>9 </servlet-mapping>

5. Servlet Details

5.1 URL Mapping Example

Shows how a single servlet can be accessed via several URLs such as /servlet/ServletDemo1, /1.htm, /2.jsp, etc.

5.2 Wildcard Mapping

Explains the two allowed wildcard formats: *.ext and /path/*.

5.3 Difference from Ordinary Java Classes

Servlets are managed by the servlet container; a single instance typically serves many requests. The init() method runs once, while service() (and consequently doGet / doPost) runs for each request, with new request/response objects each time.

5.4 Default Servlet

A servlet mapped to “/” becomes the default servlet that handles any request not matched by other mappings. The container’s built‑in DefaultServlet serves static resources.

5.5 Thread‑Safety Issues

When multiple threads access shared instance variables, race conditions occur. Example of unsafe code:

public class ServletDemo3 extends HttpServlet {<br/>    int i = 1;<br/>    public void doGet(HttpServletRequest request, HttpServletResponse response)<br/>            throws ServletException, IOException {<br/>        i++;<br/>        Thread.sleep(1000*4); // simulate delay<br/>        response.getWriter().write(i+"");<br/>    }<br/>    public void doPost(HttpServletRequest request, HttpServletResponse response)<br/>            throws ServletException, IOException {<br/>        doGet(request, response);<br/>    }<br/>}

Both browsers see the same final value because the shared i is modified concurrently.

Safe code using a local variable (no shared state) does not suffer from this problem:

public void doGet(HttpServletRequest request, HttpServletResponse response)<br/>        throws ServletException, IOException {<br/>    int i = 1;<br/>    i++;<br/>    response.getWriter().write(i+"");<br/>}

Another safe approach is to synchronize access to the shared resource:

public class ServletDemo3 extends HttpServlet {<br/>    int i = 1;<br/>    public void doGet(HttpServletRequest request, HttpServletResponse response)<br/>            throws ServletException, IOException {<br/>        synchronized (this) {<br/>            i++;<br/>            try { Thread.sleep(1000*4); } catch (InterruptedException e) { e.printStackTrace(); }<br/>            response.getWriter().write(i+"");<br/>        }<br/>    }<br/>    public void doPost(HttpServletRequest request, HttpServletResponse response)<br/>            throws ServletException, IOException {<br/>        doGet(request, response);<br/>    }<br/>}

While synchronization eliminates race conditions, it serializes access and can become a bottleneck under heavy load.

5.6 SingleThreadModel (Deprecated)

Implementing javax.servlet.SingleThreadModel marks a servlet for single‑threaded handling. The container may create a pool of servlet instances to serve concurrent requests, but the approach is deprecated since Servlet API 2.4 because it does not truly solve thread‑safety and harms scalability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javathread safetyWeb DevelopmentServletEclipseURL Mapping
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.