Sobes.tech
Senior

What is a servlet? What is a servlet container? Which popular containers do you know?

sobes.tech AI

Answer from AI

A servlet is a Java class that extends the capabilities of servers, typically web servers, to handle HTTP requests and generate HTTP responses. It runs on the server side and is used to create dynamic web content.

A servlet container is a runtime environment that manages the lifecycle of servlets, handles requests, and facilitates interaction between servlets and the web server. The container is responsible for loading, initializing, calling servlet methods, and destroying them.

Popular servlet containers:

  • Apache Tomcat
  • Jetty
  • WildFly (formerly JBoss)
  • GlassFish

Example of a simple servlet in Java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<h1>Hello, Servlet!</h1>");
    }
}