by Steven J. Owens (unless otherwise attributed)
This has been merged into the Java Web Applications tutorial:
Here is a short description of how servlets work.
Servlets are entry points into the JVM:
The servlet engine listens for incoming network connections.
When a connection comes in, the servlet engine parses the data sent over the connection - the HTTP request, which may include parameters - as an HTTPServletRequest object.
Once the servlet engine has parsed the data, the engine looks at the file that the HTTP request is for.
If that file name is listed in the servlet engine configuration file as a servlet, the servlet engine checks to see if the servlet class has been instantiated yet.
If the servlet class for that servlet has not been instantiated, the servlet engine instantiates it.
After the servlet engine instantiates the servlet class, the engine invokes the servlet class init() method, so the servlet can do any setup work necessary.
After the servlet init() method returns, the servlet engine invokes the servlet doGet method, with the HTTP request object as a parameter.
The servlet can do anything a normal java program can do, except that because it is running on a separate machine, it cannot display a GUI to the user. Any user interaction has to take place within the HTTP request and response.
The other major limitation of a servlet - and of the HTTP protocol - is that it has to rely on the client - the browser, or a special HTTP client you write - to send each request.
For example, there is no way for the servlet engine to know if the user shuts down the browser, unless the user first clicks on a "log out" link or button. The browser does not usually keep a connection open to the server. There is no way, without going outside the HTTP protocol, for the servlet to open a connection to the browser without the browser first opening a connection to the servlet.
When the servlet engine invokes the servlet doGet() method, it also passes a response object as a parameter, in addition to the request object. The servlet uses the response object to format the response and send it back.
The servlet engine also provides a framework for maintaining user session data, and a framework for the servlet to forward requests off to other servlets running on the same servlet engine.