A Servlet is a class, which implements the javax.servlet.Servlet
interface. However instead of directly implementing the javax.servlet.Servlet
interface we extend a class that has implemented the interface like javax.servlet.GenericServlet
or javax.servlet.http.HttpServlet
.
Servlet Exceution
This is how a servlet execution takes place when client (browser) makes a request to the webserver.
Servlet architecture includes:
a) Servlet Interface
To write a servlet we need to implement Servlet interface. Servlet interface can be implemented directly or indirectly by extending GenericServlet or HttpServlet class.
b) Request handling methods
There are 3 methods defined in Servlet interface: init(), service() and destroy().
The first time a servlet is invoked, the init method is called. It is called only once during the lifetime of a servlet. So, we can put all your initialization code here.
The Service method is used for handling the client request. As the client request reaches to the container it creates a thread of the servlet object, and request and response object are also created. These request and response object are then passed as parameter to the service method, which then process the client request. The service method in turn calls the doGet or doPost methods (if the user has extended the class from HttpServlet ).
c) Number of instances
Basic Structure of a Servlet
public class firstServlet extends HttpServlet { public void init() { /* Put your initialization code in this method, * as this method is called only once */ } public void service() { // Service request for Servlet } public void destroy() { // For taking the servlet out of service, this method is called only once } }
Abhinav says
This is only one site and knowledge area where i got every solution with high commands thanking you and have a great wishes to your site.. ☺️☺️
swetha says
what is the difference between servlets and webservices
Aravind Reddy says
1. Servlets provide webservices.
2. webservices in the sense services provided by the server containing servlet container and in that servlet container we have webapplications. And webapplications may contain different servlets in order to retrive dynamic data and also process the data provided by the user.
Sonym says
Thank You so much for the answer . This is the best answer i got, because it explained along with diagram and besides that the english is simple, very easy to understand ,,, It helps me alot !