A Servlet is a Java class that runs within a web container in an application server, servicing multiple client requests concurrently forwarded through the server and the web container. The web browser establishes a socket connection to the host server in the URL , and sends the HTTP request. Servlets can forward requests to other servers and servlets and can also be used to balance load among several servers.
A browser and a servlet communicate using the HTTP protocol (a stateless request/response based protocol).
A “ServletRequest”, which encapsulates client request from the client and the “ServletResponse”, which encapsulates the communication from the servlet back to the client.
Servlet's Life Cycle :
The Web container is responsible for managing the servlet’s life cycle. The Web container creates an instance of the servlet and then the container calls the init() method. At the completion of the init() method the servlet is in ready state to service requests from clients. The container calls the servlet’s service() method for handling each request by spawning a new thread for each request from the Web container’s thread pool [It is also possible to have a single threaded Servlet, refer Q16 in Enterprise section]. Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.
Get and Post Methods :
All client requests are handled through the service() method. The service method dispatches the request to an appropriate method like doGet(), doPost() etc to handle that request.
Below diagram summarizes the differences between Get and Post Methods :
Prefer using doPost() because it is secured and it can send much more information to the server.
If you want a servlet to take the same action for both GET and POST request, you should have doGet call doPost, or vice versa.Below is the code snippet illustration.
ServletConfig:
The ServletConfig parameters are for a particular Servlet.The parameters are specified in the web.xml(i.e. deployment descriptor). It is created after a servlet is instantiated and it is used to pass initialization information to the servlet.
ServletContext:
The ServletContext parameters are specified for the entire Web application. The parameters are specified in the web.xml(i.e.deployment descriptor).Servlet context is common to all Servlets. So all Servlets share information through ServletContext.
Servlet Life Cycle Events:
Servlet lifecycle events work like the Swing events.
RequestDispatcher:
Defines an object that receives requests from the client and sends them to any resource(such as a servlet, HTML file, or JSP file) on the server.The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
This interface is intended to wrap servlets,but a servlet container can create RequestDispatcher
objects to wrap any type of resource.
It uses :
Following image depicts the difference between Forward or Include and sendRedirect:
Following image depicts the difference between the getRequestDispatcher(String path) method of “ServletRequest” interface and ServletContext interface:
How to make Servlet thread safe:
One approach is to use single threaded model of a servlet by implementing the marker or null interface javax.servlet.SingleThreadedModel.The container will use one of the following approaches to ensure thread safety:
It is better to avoid instance and static variables
Pre-initialization of a Servlet :
By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading. The servlet deployment descriptor(web.xml) defines the element, which can be configured to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called pre-loading or pre-initializing a servlet. We can also specify the order in which the servlets are initialized.
Servlet clustering :
The clustering promotes high availability and scalability. The considerations for servlet clustering are:
Session replication is the term that is used when your current service state is being replicated across multiple application instances. Session replication occurs when we replicate the information (i.e. session attributes) that are stored in your HttpSession. The container propagates the changes only when you call the setAttribute(..) method.
Note: Mutating the objects in a session and then by-passing the setAttribute(………..) will not replicate the state change. Example : If you have an ArrayList in the session representing shopping cart objects and if you just call getAttribute(…) to retrieve the ArrayList and then add or change something without calling the setAttribute(…) then the container may not know that you have added or changed something in the ArrayList. So the session will not be replicated.
Constructors in Servlets :
Constructors for dynamically loaded java classes such as Servlets cannot accept arguments.Therefore init() is used to initialize by passing the servletConfig object and other needed parameters.
Also java constructors cannot be declared in an interface and javax.servlet.Servlet is an interface.
However the constructor can be defined in the servlet but the servletConfig object is no accessible in the constructor.
A browser and a servlet communicate using the HTTP protocol (a stateless request/response based protocol).
A “ServletRequest”, which encapsulates client request from the client and the “ServletResponse”, which encapsulates the communication from the servlet back to the client.
Servlet's Life Cycle :
The Web container is responsible for managing the servlet’s life cycle. The Web container creates an instance of the servlet and then the container calls the init() method. At the completion of the init() method the servlet is in ready state to service requests from clients. The container calls the servlet’s service() method for handling each request by spawning a new thread for each request from the Web container’s thread pool [It is also possible to have a single threaded Servlet, refer Q16 in Enterprise section]. Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.
Get and Post Methods :
All client requests are handled through the service() method. The service method dispatches the request to an appropriate method like doGet(), doPost() etc to handle that request.
Below diagram summarizes the differences between Get and Post Methods :
Prefer using doPost() because it is secured and it can send much more information to the server.
If you want a servlet to take the same action for both GET and POST request, you should have doGet call doPost, or vice versa.Below is the code snippet illustration.
ServletConfig:
The ServletConfig parameters are for a particular Servlet.The parameters are specified in the web.xml(i.e. deployment descriptor). It is created after a servlet is instantiated and it is used to pass initialization information to the servlet.
ServletContext:
The ServletContext parameters are specified for the entire Web application. The parameters are specified in the web.xml(i.e.deployment descriptor).Servlet context is common to all Servlets. So all Servlets share information through ServletContext.
Servlet Life Cycle Events:
Servlet lifecycle events work like the Swing events.
- Any listener interested in observing the ServletContext lifecycle can implement the ServletContextListener interface
- Listener interested in the ServletContext attribute lifecycle can implement the ServletContextAttributesListener interface.
- The session listener model is similar to the ServletContext listener model ServletContext’s and Session’s listener objects are notified when servlet contexts and sessions are initialized and destroyed, as well as when attributes are added or removed from a context or session.
RequestDispatcher:
Defines an object that receives requests from the client and sends them to any resource(such as a servlet, HTML file, or JSP file) on the server.The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
This interface is intended to wrap servlets,but a servlet container can create RequestDispatcher
objects to wrap any type of resource.
It uses :
- Forward - rd.forward(request,response):When it needs to forward the control to another servlet or JSP to generate response.This method allows one servlet to do preliminary processing of a request and another resource to generate the response.
- Include - rd.include(request, response):When it needs to include the content of the resource such as Servlet, JSP, HTML, Images etc into the calling Servlet’s response.
Following image depicts the difference between Forward or Include and sendRedirect:
Following image depicts the difference between the getRequestDispatcher(String path) method of “ServletRequest” interface and ServletContext interface:
How to make Servlet thread safe:
One approach is to use single threaded model of a servlet by implementing the marker or null interface javax.servlet.SingleThreadedModel.The container will use one of the following approaches to ensure thread safety:
- Instance pooling where container maintains a pool of servlets.
- Sequential processing where new requests will wait while the current request is being processed.
It is better to avoid instance and static variables
Pre-initialization of a Servlet :
By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading. The servlet deployment descriptor(web.xml) defines the
Servlet clustering :
The clustering promotes high availability and scalability. The considerations for servlet clustering are:
- Objects stored in a session should be serializable to support in-memory replication of sessions.Also consider the overhead of serializing very large objects. Test the performance to make sure it is acceptable.
- Design for idempotence. Failure of a request or impatient users clicking again can result in duplicate requests being submitted. So the Servlets should be able to tolerate duplicate requests.
- Avoid using instance and static variables in read and write mode because different instances may exist on different JVMs. Any state should be held in an external resource such as a database.
- Avoid storing values in a ServletContext. A ServletContext is not serializable and also the different instances may exist in different JVMs.
- Avoid using java.io.* because the files may not exist on all backend machines. Instead use getResourceAsStream().
Session Replication :
Session replication is the term that is used when your current service state is being replicated across multiple application instances. Session replication occurs when we replicate the information (i.e. session attributes) that are stored in your HttpSession. The container propagates the changes only when you call the setAttribute(..) method.
Note: Mutating the objects in a session and then by-passing the setAttribute(………..) will not replicate the state change. Example : If you have an ArrayList in the session representing shopping cart objects and if you just call getAttribute(…) to retrieve the ArrayList and then add or change something without calling the setAttribute(…) then the container may not know that you have added or changed something in the ArrayList. So the session will not be replicated.
Constructors in Servlets :
Constructors for dynamically loaded java classes such as Servlets cannot accept arguments.Therefore init() is used to initialize by passing the servletConfig object and other needed parameters.
Also java constructors cannot be declared in an interface and javax.servlet.Servlet is an interface.
However the constructor can be defined in the servlet but the servletConfig object is no accessible in the constructor.
No comments:
Post a Comment