You have already discussed that JSPs are being translated into servlets, which i
ID: 3664969 • Letter: Y
Question
You have already discussed that JSPs are being translated into servlets, which is as a base of Java Web. It is essential to understand how servlets work in order to get a solid comprehension of the entire Java web programming framework.
What is a servlet ? What does it "know", recognize and what can it do ?
What classes, interfaces and methods are of primary importance for a servlet ? What is a servlet context and what to use it for? How does a servlet handle concurrent requests?
Finally, what is a servlet life cycle in a Web application? How does a servlet handle multiple concurrent requests? What are the pros and cons of servlets as compared with JSPs ?
Explanation / Answer
1.What is a servlet ? What does it "know", recognize and what can it do ?
A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. TheHttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
2.What classes, interfaces and methods are of primary importance for a servlet ?
When we write a servlet, we must either directly or indirectly implement the servlet interface that is, 'javax.servlet.Servlet'. This interface specifies the contract between the web container and a servlet. We will most likely always implement the interface indirectly by extending any one of the following classes: javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. The interface contains five methods: init(), service(), destroy(), ServletConfig(), and getServletInfo().
The web container calls the init() method once the servlet has been instantiated. The purpose of this method is to allow a servlet perform any initialization required, before being invoked against HTTP requests. The container passes an object of type ServletConfig to the init() method. The init() method throws a ServletException in the event of the init() method not completing normally. This method will be called exactly only once on any given instance of the servlet and the init() method will be allowed to complete before any requests are passes to the servlet. Some of th primary tasks concerned with this method are reading configuration data from persistent resources such as configuration files, reading initialization parameters using the javax.servlet.ServletConfig object and initializing one-time activities such as registering a database driver, a connection pool or a logging service.
The service() method is called by the web container in response to incoming requests. This is the starting point for executing application logic in a servlet. This method will be called only after the init() method. This method accepts two arguments, implementing the javax.servlet.ServletRequest and javax.servlet.ServletResponse interfaces respectively.
The destroy() method is for destroying a servlet instance, which is out of service. This will become necessary for reclaiming some memory or if the web server is being shut down. This method will be called only after the servlet finishes execution of service and there is no request in the queue. Some of the activities that can be implemented in this method are performing cleanup tasks, such as unregistering a database driver, closing a connection pool, or even informing another application/system that the servlet will no longer be in service and persisting any state associated with a servlet.
The getServletConfig() method returns the ServletConfig object that was passed to the servlet during the initialization process. The getServletInfo() method will return a String object containing information about the servlet for example, author, creation date, description etc.
The GenericServlet class provides a basic implementation of the Servlet interface and it is an abstract class. All subclasses of this class should implement the service() method. This class has three methods: init(), log(String message) and log(String message, Throwable t) in addition to those declared in javax.servlet.Servlet and javax.servlet.ServletConfig interfaces. The GenericServlet class has to implement the methods of these interfaces.
The HttpServlet class extends GenericServlet and provides an HTTP-specific implementation of the Servlet interface. This class has service(), doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace() methods.
There are two service() methods. The first one casts the request and response objects to HttpServletRequest and HttpServletResponse and calls the second overloaded service() method. The overloaded method takes HTTP-specific request and response objects. The HttpServlet class implements the doXXX() methods, which stands for each of the HTTP request method.
3.What is a servlet context and what to use it for?
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-param> element.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don't need to modify the servlet. Thus it removes maintenance problem.
Usage of ServletContext Interface
There can be a lot of usage of ServletContext object. Some of them are as follows:
4. How does a servlet handle concurrent requests?
Struts/Spring frameworks are actually written on top of Servlet specification so doesn't matter what you use underneath it use Servlets.
You are right, Only single instance of Servlet is created, but that instance is shared across multiple threads. For this reason you should never have shared mutable states in your Servlets.
For example you have following servlet mapped to http://localhost/myservlet
The Web Server will have something similar (Not necessarily same) in its code.
5. what is a servlet life cycle in a Web application?
We discuss here how a servlet interacts with a Web server via a Web container, which is a runtime that manages the servlets. Of the various responsibilities of a container, lifecycle management is the most crucial. The life cycle of a servlet contains the following stages: Instantiation, Initialization, Service, Destroy and Unavailable.
Firstly, a Web browser connects to a Web server and sends an HTTP request over the connection. Based on the request URL, the following sequence of events happens. The first thing the Web server has to do is to figure out if the incoming request corresponds to a Web application in the Web container. This needs an implicit understanding between the Web server and the Web container. Web containers use the notion of a servlet context to identify Web applications. We can specify the context when we are deploying the application onto the container.
Once the application figures out that the web container has to handle the request, the Web server delegates the request to the Web container. We can think of this process as the Web server invoking a local/remote method on the Web container, with the request information.
Once the Web container receives the request from the Web server, it should decide which application should handle this request. In a J2EE Web application, an HTTP request can be mapped to a servlet, or a JSP file, or any static resource based on URL patterns. Static resources include HTML/XML documents, images, applet class/JAR files, etc. These resources are part of the web application. When we package and deploy a Web application, we also specify this mapping information. The Web container uses this mapping information to map each incoming request to a servlet, a JSP, or a static resource. If the needed resource is mapped to a static resource, all that the Web container has to do is to pass that resource to the Web server and this forms the body of the response that the Web server sends to the Web browser.
Suppose if the Web container determines, based on the mapping information, that the request should be handled by a servlet, the Web container creates or locates a servlet instance, and delegates the request to the servlet instance in addition to the objects encapsulating the HTTP request and HTTP response. For a servlet instance, these objects represent the request and response streams from the browser. The servlet can read the request information, and write response to these streams. For writing response, the servlet can use the java.io.PrintWriter object associated with the response, and write content using println methods to the response. This is equivalent to writing content to the already opened connection from the Web browser.
6.What are the pros and cons of servlets as compared with JSPs ?
A very basic difference:
Other diff are:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.