Skip to main content

Server-side programming and Java Servlet

Short answer

Server-side programming runs code on the server to generate dynamic responses, accessing databases and sending only HTML to the browser. A servlet is a Java class loaded once in a container; init() runs once, service() calls doGet or doPost per request in a thread, and destroy() runs at shutdown.

What is server-side programming? Explain how a Java Servlet works.

Server-side programming

Server-side programming is writing programs that run on the web server to process client requests and generate dynamic responses. The server executes the code, accesses databases and files, applies business logic and sends only the resulting HTML (or JSON/XML) to the browser. Examples: PHP, JSP/Servlets, ASP.NET, Python (Django/Flask), Node.js. Uses: login and sessions, database-driven pages, form processing, e-commerce.

Java Servlet

A servlet is a Java class that runs inside a servlet container (web container) such as Apache Tomcat or Jetty. It extends HttpServlet and handles HTTP requests. Unlike CGI, a servlet is loaded once and each request runs in a lightweight thread, so it is fast and portable.

How a servlet works (life cycle)

  1. The browser sends an HTTP request to a URL mapped to the servlet.
  2. The web server passes it to the servlet container.
  3. Loading and init(): On the first request (or at startup) the container loads the class, creates one instance and calls init() once.
  4. service(): For every request the container creates HttpServletRequest and HttpServletResponse objects and calls service() in a new thread, which calls doGet() or doPost().
  5. The servlet reads parameters, may use JDBC to access the database, and writes the response through response.getWriter().
  6. The container sends the response back to the browser.
  7. destroy(): When the container shuts down or unloads the servlet, destroy() is called once to release resources.
Browser -> Web server -> Servlet container
                           init() (once)
                           service() -> doGet()/doPost()  (per request)
                           destroy() (once)
Browser <- response <------+
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
        throws IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<h1>Hello, " + req.getParameter("name") + "</h1>");
  }
}

✓ Answer checked by Claude Opus 5.5 (high effort)

All Web Technology chapter 3 questions →