CGI - Common Gateway Interface is used for generating dynamic content to the user.
CGI is used to execute a program that resider in the server to process data/access database to
produce the relevent dynamic result.
Servlets are server side application that we develop using java language.
Server side application to be placed in web server or it should be placed in a application server.
To resolve the problem of CGI are reslove in java. Servlet are written in java. Java id flatform
independent so servlet can run on any OS. In servlet thread is created for each request.
Servlet | CGI |
---|---|
It is thread based i.e. for every new request new thread is created. Thread is lightweight. | It is process based i.e. for every new request new process is created. Process is heavy weight. |
Servlet is Portable (platform independent) | CGI is not Portable (platform dependent) |
Can handle cookies and track session | CGI can't handle cookies or session |
Less expensive | more expensive |
Faster | Slower |
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
public void init() throws ServletException {
// Do required initialization
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}