Basics of Java Servlets
What is servlet and web server?A servlet is a Java program that runs on the server. To run servlet programs, we need a web server. In this tutorial, we will use Tomcat.
The servlets were introduced by Sun Microsystems as an alternative to CGI which was then most popular for developing web applications. Sun Microsystems did not provide code for working with servlets, they have only specified some set of rules according to which the servlet related classes must be written.
According to those guidelines specified by the Sun, several companies which produce server software like Tomcat have written their own classes that enable programmer to work with servlets.
Two important keywords you need to know:
request: Request made to the server by the browser for data.
response: Output (data) given by the server to the browser after request.
The main aim of the web applications is to take input from the user and give the output. This output which is based on the input given is called as dynamic content.
catalina.jar is called as servlet
container. The birth, life and death of a servlet is under the control
of this container i.e. this container is responsible for the creation,
execution and death of a servlet.
Servlets do not contain a main() method. The corresponding methods are called upon each request by the container itself. The programmer doesn't need to worry about it.
Advantages of Servlets over CGI
Servlets are better than CGI under a lot of circumstances. Sure, the disadvantages of CGI in the growing world wide web had been devastating, so are servlets introduced. In CGI:
Every user request is processed by a program, i.e. for every request a new program is loaded into the RAM by the web server and that program, processes the request and gives the response.
Because of this, servers required large memory RAMs and high working processors to serve a large number of users at a time. Also, when the program has to interact with the database, for every request, a database connection is created, which is both late and a security loop hole.
Combined with the statelessness of HTTP protocol (as discussed in the previous chapter), CGI has got another disadvantage. For every request, a program is loaded and then after the response is given, the program is killed. So, there is no way to keep track of the previous requests. This has been of greater disadvantage in all spheres of web applications.
The concept of servlets changed the entire thing.
- Instead of using, a new program for serving each user request, a thread is used to serve a request. Thereby, making the process more efficient and less costly.
- Only one database connection serves several user requests, hence more secure.
- Also, the concepts of cookies and session tracking made it possible to keep track of user's previous requests.
Photo credit: copyblogger.com