Difference between Servlet and CGI
Servlet
- Definition: Servlets are Java programs that run on a server and handle client requests by generating dynamic content.
- Execution: They run within a web server’s JVM (Java Virtual Machine), making them more efficient by handling multiple requests using threads.
- Performance: High performance due to the multithreading Servlet and CGI capabilities. Each request is handled by a lightweight thread rather than a heavy process.
- Platform Dependency: Platform-independent due to Java’s “write once, run anywhere” capability.
- Memory Management: Efficient memory management due to the JVM and garbage collection.
- Persistence: Servlets are persistent as they stay in memory, ready to handle multiple requests over time.
- Maintenance: Easier to maintain because of the robust Java ecosystem and development tools.
CGI (Common Gateway Interface)
- Definition: CGI is a standard protocol for web servers to execute programs that execute outside the web server to generate web content dynamically.
- Execution: Each request spawns a new process, which can be resource-intensive.
- Performance: Lower performance compared to servlets Servlet and CGI because each request requires a new process, consuming more system resources.
- Platform Dependency: Can be written in various programming languages like C, Perl, Python, etc., and are platform-dependent.
- Memory Management: Each CGI script runs in its own process, leading to higher memory usage.
- Persistence: Not persistent as each request creates a new process, which is destroyed after the request is processed. – Maintenance: Can be more challenging to maintain due to the diversity of languages and lack of a standardized development ecosystem

Table of Contents
Java Servlet Example
java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       response.setContentType("text/html");
       response.getWriter().println("<h1>Hello, World!</h1>");
   }
}
  CGI Script Example (Perl)
perl
!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<html><body><h1>Hello, World!</h1></body></html>";