Servlet & Web
A Servlet is a Java class that handles HTTP requests and responses on a server. While CGI (Common Gateway Interface) can also be done in Java, Servlets are a far more efficient standard — they run within the same JVM as the server, handle each request in a separate thread, and have a lifecycle managed by the servlet container (Tomcat, Jetty).
Jakarta Servlet (formerly Java Servlet, which moved its namespace from javax to jakarta since Jakarta EE 9+) is the modern API. JSP (Chicago Server Pages) makes it easy to build web pages by combining HTML and Java code. For modern web APIs, use Spring Boot or Jakarta RESTful Web Services (JAX-RS).
Servlet lifecycle: init() → service() → destroy(). The container manages instance creation, thread pooling, and garbage collection automatically.
Java Web Components:
| Technology | Use | Status |
|---|---|---|
| Servlet | Request/Response handler | The basics, still used |
| JSP | Dynamic web pages | Legacy, still active |
| JAX-RS | RESTful APIs | Jakarta EE |
| Spring Boot | Modern web framework | Most popular |
Code Example
// Simple servlet (Jakarta Servlet API)
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><body>");
out.println("<h1>Hello from Servlet!</h1>");
out.println("<p>Server time: " + new java.util.Date() + "</p>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, " + name + "!</h1>");
out.println("</body></html>");
}
}
// web.xml (deployment descriptor) — manual version
/*
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
*/
// Or use @WebServlet (annotations)
import jakarta.servlet.annotation.WebServlet;
@WebServlet("/hello")
public class HelloServletAnnotation extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().println("<h1>Halo Dunia!</h1>");
}
}
Code Explanation
- doGet(): handles HTTP GET requests — usually for reading/displaying data.
reqcontains the request information,respis used to send the response. - doPost(): handles HTTP POST requests — usually for submitting/creating new data.
req.getParameter("name")retrieves a form field's value. - setContentType(): sets the response type —
"text/html"for a web page. - @WebServlet("/hello"): a modern annotation that replaces
web.xmlconfiguration — more compact. - The servlet container (Tomcat) handles the lifecycle, threading, and security automatically.
Everyday Example
A simple REST API using Jakarta RESTful Web Services (JAX-RS):
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.*;
import java.util.*;
@Path("/product")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ProductResource {
static List<Map<String, Object>> product = new ArrayList<>();
static {
product.add(Map.of("id", 1, "name", "Laptop", "price", 15000000));
product.add(Map.of("id", 2, "name", "Mouse", "price", 150000));
}
@GET
public List<Map<String, Object>> getAll() {
return product;
}
@GET
@Path("/{id}")
public Map<String, Object> getById(@PathParam("id") int id) {
return product.stream()
.filter(p -> (int) p.get("id") == id)
.findFirst()
.orElse(Map.of("error", "Not found"));
}
@POST
public Response add(Map<String, Object> newItem) {
product.add(newItem);
return Response.status(Response.Status.CREATED).entity(newItem).build();
}
}
Summary
Java has a mature web ecosystem. Servlets are a foundation that is still relevant for understanding how web servers work. For modern projects, use Spring Boot, which builds on top of Servlets with far more complete features. JAX-RS is a good fit for compact REST APIs.