Professional Documents
Culture Documents
Servletqb
Servletqb
A servlet is a Java programming language class that’s wont to extend the capabilities of
servers that host applications accessed by means of a request-response programming
model. Although servlets can answer any sort of request, they’re commonly want to extend
the appliance hosted by web servers. Java Servlet technology defines HTTP-specific
servlet classes for such applications.
Servlets are created using the javax.servlet and javax.servlet.http packages. These
packages are a standard part of Java’s enterprise edition and an expanded version of the
Java class library that supports large-scale development projects.
javax.servlet.*: It contains a number of classes and interfaces. It describes and defines the
contracts between a servlet class and the runtime environment.
This is one of the frequently asked Servlet Interview Questions and Answers. Typical uses
for HTTP Servlets include:
This is one of the frequently asked Servlet Interview Questions and Answers. Servlets have
several advantages over CGI:
1. Portability: Servlets are highly portable across operating systems and server
implementations because servers are written in java and follow well-known
standardized APIs so they are.
2. Powerful: It is possible to do several things with the servlets which were
difficult or even impossible to do with CGI.
3. Efficiency: As compared to CGI the invocation of the servlet is highly
efficient. When the servlet gets loaded in the server, it remains in the
server’s memory as a single object instance.
4. Safety: As servlets are written in java, servlets inherit the strong type-
safety of java language. Servlets are generally safe from memory
management problems because of Java’s automatic garbage collection
and a lack of pointers.
5. Integration: Servlets are tightly integrated with the server. Servlet basically
uses the server to translate the file paths, perform logging, check
authorization, and MIME type mapping, etc.
6. Extensibility: The servlet API is designed in such a way that it can be
easily extensible. As it stands today, the servlet API supports HTTP
Servlets, but later it can be extended for another type of servlets.
7. Inexpensive: There are a number of free web servers available for
personal use or for commercial purposes. Web servers are relatively
expensive. So by using the available web servers you can add servlet
support to it.
This is one of the frequently asked Servlet Interview Questions and Answers. The life cycle
of a Servlet consists of the following phases:
Loading and Instantiation
The servlet container loads the servlet during startup or when the primary request is formed.
Loading of the servlet depends on the attribute of the web.xml file. If the attribute has a
positive value then the servlet is loaded with the loading of the container otherwise it loads
when the first request comes for service. The container creates the instances of the servlet
after loading the servlet.
Initialization
After creating the instances, the servlet container calls the init() method and passes the
servlet container before the servlet can service any request. The initialization parameters
persist until the servlet is destroyed. The init() method is named just one occasion
throughout the life cycle of the servlet. The servlet is going to be available for service if it’s
loaded successfully otherwise the servlet container unloads the servlet.
After successfully completing the initialization process, the servlet is going to be available
for service. Servlet creates separate threads for each request. The servlet container calls
the service() method for servicing any request. The service() method determines the kind of
request and calls the appropriate method (doGet() or doPost()) for handling the request and
sends the response to the client using the methods of the response object.
If the servlet is not any longer needed for servicing any request, the servlet container calls
the destroy() method. Like the init() method this method is additionally called just one
occasion throughout the life cycle of the servlet. Calling the destroy() method indicates to
the servlet container to not sent any request for service and therefore the servlet releases
all the resources related to it. Java virtual Machine claims for the memory related to the
resources for garbage pickup.
The life cycle of a servlet is controlled by the container in which the servlet has been
deployed.
Servlets has three lifecycle methods and they are defined in Servlet Interface. The three
lifecycle methods of servlet are:
init(): init() method would be executed by the container automatically as soon as an object
of the servlet is created, the object of the servlet would be created only once. Thus init()
method would be executed only once i.e. when the object of the servlet is created for the
first time.
service(): service() method would be executed by the container automatically as and when
the request is coming to as servlet. A container always calls service() method by passing
the data (i.e. coming from the client) in the form of ServletRequest object and address of the
client (from where the request is received) in the form of servletResponse object as
arguments.
destroy(): destroy() method would be executed before the object of the servlet is deleted.
The container maintains every servlet object for a certain period of time even if no request is
coming to that servlet. After a certain period of time container deletes the object of the
servlet before deleting or destroying the servlet object. The container automatically calls
destroy() method and executes destroy() method completely and after the execution of the
destroy() method, the servlet object would be completely deleted.
As per the technology which we used to design server-side components. There are some
containers:
1. Servlet Container – To execute Servlets
2. JSP Container – To execute JSP’s
3. EJB Container – To execute EJB’s
Note: All the above-specified containers can be used to execute the respective components
because the above containers have implemented the respective technology API.
As per the containers physical existence, there are three types of containers:
The init() method is by which a servlet Container will run to configure the Servlet. It provides
a servletConfig object which gives the Servlet instance access to the ServletContext and
other configuration elements from the deployment descriptor.
It ensures that the servlet can handle only one request at a time. It has no methods. If a
servlet implements this interface it is guaranteed that no two threads will execute
concurrently in the servlet’s service method. The servlet container guaranteed it by
synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet
instances and dispatching each new request to a free servlet. SingleThreadModel interface
does not prevent synchronization problems that result from servlets accessing shared
resources such as static class variables or classes outside the scope of the servlet.
It provides the power of dispatching the request to a different resource it’s going to be
HTML, servlet, or JSP. In web applications, we are ready to achieve web-component
communication within the following 2 ways:
1. Include Mechanism
2. Forward Mechanism
If we would like to perform the above mechanisms internally we must use the
RequestDispatcher object. So that both include and forward mechanisms are commonly
called Request Dispatching Mechanisms.
What methods we can call on the Request Dispatcher object?
Include: Include Request Dispatching mechanism can be used to include the target
resource response into the present resource response. In the case of the Include
mechanism, when we send a request to the first resource then the container will prepare the
request and response objects, by executing some parts in the first resource container may
generate some response in the response object.
Forward: In web applications, the main purpose of the forward mechanism is to forward
requests from the present resource to the target resource. In the case of the forward
mechanism, when we send a request to the first resource then the container will create
request and response objects, by executing some part in the first resource container may
generate some response in the response object.
A servlet is loaded by making a request first then the server starts up. There is only a single
instance that answers all requests concurrently. Then administrator manually loads.
A servlet is unloaded when the server shuts down or the administrator manually unloads.
The servlet interface is for developing servlets. A servlet may be a body of Java code that’s
loaded into and runs inside a servlet engine, as an internet server. It receives and responds
to requests from clients. For example, a client may have information from a database; a
servlet is often written that receives the request, gets and processes the info as required by
the client, and then returns it to the client.
Note: Most Servlets, however, extend one of the standard implementations of that interface,
namely javax.servlet.GenericServlet and javax.servlet.httpServlet.
GenericServlet is an abstract class that implements the Servlet interface and the
ServletConfig interface. In addition to the methods declared in these two interfaces, this
class also provides simple versions of the lifecycle methods init and destroy, and
implements the log method declared in the ServletContext interface.
Note: This class is known as a generic servlet since it is not specific to any protocol.
GenericServlet
HttpServlet
1. An abstract class that simplifies writing HTTP servlets. It extends the
GenericServlet base class and provides a framework for handling the HTTP
protocol.
2. The HttpServlet subclass passes generic service method requests to the
relevant doGet() or doPost() method.
3. HttpServlet only supports HTTP and HTTPS protocol.
This is one of the frequently asked Servlet Interview Questions and Answers. The
HttpServlet class is declared abstract because the default implementations of the main
service methods do nothing and must be overridden. This is a convenient implementation of
the Servlet interface, which means that developers do not need to implement all service
methods. If your servlet is required to handle doGet() requests, for example, there is no
need to write a doPost() method too. required to handle doGet() requests, for example,
there is no need to write a dpPost() method too.
Yes, Servlets can have a constructor but it is not the right way to initialize the Servlet and
you should use the init() method provided by the Servlet.
It extends the GenericServlet base class and provides a framework for handling the HTTP
protocol. So HttpServlet only HTTP and HTTPS protocol.
The doGet() method is called by the server via the service method to allow a servlet to
handle a GET request whereas the doPost() method is called by the server to allow a
servlet to handle a PUT request.
doGet()
1. In doGet() the parameters are appended to the URL and sent along with
header information.
2. The amount of information you can send back using a GET is restricted as
URLs can only be 1024 characters.
3. doGet() is a request for information; it does not (or should not) change
anything on the server. (doGet() should be idempotent)
4. Parameters are not encrypted
5. doGet() is faster if we set the response content length since the same
connection is used. Thus, increasing the performance
6. doGet() should be idempotent. i.e. doGet should be able to be repeated safely
many times
7. doGet() should be safe without any side effects for which the user is held
responsible
8. It allows bookmarks.
doPost()
1. In doPost(), on the other hand, will (typically) send the information through a
socket back to the webserver and it won’t show up in the URL bar.
2. You can send much more information to the server this way – and it’s not
restricted to textual data either. It is possible to send files and even binary
data such as serialized Java objects!
3. doPost() provides information (such as placing an order for merchandise) that
the server is expected to remember.
4. Parameters are encrypted
5. doPost() is generally used to update or post some information to the server.
doPost is slower compared to doGet since doPost does not write the content
length
6. This method doesn’t need to be idempotent. Operations requested through
POST can have side effects for which the user can be held accountable.
7. This method does not need to be either safe
8. It disallows bookmarks.
It is always preferred to use the get method because the get method is faster than the post
method. Use post method only id data is sensitive if data is greater than 1024 characters
and if your application doesn’t need bookmarks.
How do I support both GET and POST from the same Servlet?
The easy way is, just support POST, then have your doGet method call your doPost
method:
doPost(request, response);
}
This is one of the frequently asked Servlet Interview Questions and Answers. It is not
required to override the service method since the HTTP Servlets have already taken care of
it. HTTP service method checks the request method and calls the appropriate handler
method so it is not necessary to override the service method itself.
ServletContext is an object, it will manage all the context details of a particular web
application, where the context details include the logical name of the web application and
context parameters, and so on. ServletConetxt is an object, it will provide the complete view
of the particular web application.
What are the differences between the ServletConfig interface and the
ServletContext interface?
In the case of forward(), redirect happens at the server end and is not visible to the client,
whereas in the case of sendRedirect(), redirection happens at the client’s end and it’s
visible to the client.
The main difference is forward() method closes the output stream after it has been invoked,
whereas the include() method leaves the output stream open.
This is one of the frequently asked Servlet Interview Questions and Answers. The main
purpose of Servlet Wrappers in web applications is to simplify the customization of request
and response objects. In general in web application execution when we send a request from
the client to server for a particular servlet then the container will pick up the request, identify
the requested servlet, perform servlet life cycle stages like servlet loading, servlet
instantiation, servlet initialization, request processing, and servlet de-instantiation.
This is one of the frequently asked Servlet Interview Questions and Answers. It refers to the
configuration file for an artifact that is deployed to some container/engine. It describes the
classes, resources, and configuration of the application and how the web server uses them
to serve web requests.
Preinitialization is the process of loading a java servlet before receiving any request. Servlet
is loaded in the order of number (non-zero integer) specified. It is also known as load-on-
startup.
<servlet>
<servlet-name>ServletName</servlet-name>
<servlet-class>ClassName</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Note: The container loads the servlets in the order specified in the <load-on-startup>
element.
What is a session?
The session is a time duration, it will start from the starting point of client conversation with
the server and will terminate at the ending point of client conversation with the server. The
data which we transferred from client to server through multiple numbers of requests during
a particular session then that data is called State of the Session.
Session Tracking is used to recognize the particular user. It is a way to maintain the state
(data) of the user about a series of requests from the same user (that is, requests
originating from the same browser) across the same period of time. Each time the user
requests to the server, the server always treats the request as the new request.
This is one of the frequently asked Servlet Interview Questions and Answers. In web
applications, there are 4 types of Session Tracking Mechanisms:
This is one of the frequently asked Servlet Interview Questions and Answers. In a servlet,
the HttpServletResponse and HttpServletRequest objects passed to method
HttpServlet.service() can be used to create cookies on the client and use cookie information
transmitted during client requests. JSPs can also use cookies, in scriptlet code or,
preferably, from within custom tag code.
To set a cookie on the client, use the addCookie() method in class HttpServletResponse.
Multiple cookies may be set for the same request, and a single cookie name may have
multiple values.
To get all of the cookies associated with a single HTTP request, use the getCookies()
method of class HttpServletRequest
● To work with cookies our servlet type must be HttpServlet (cookies do not
work with GenericServlet).
● Cookies can be deleted through browser settings. This may fail session
tracking.
○ In Internet Explorer: Tools menu -> internet options -> delete
cookies option
○ In Netscape : Tools menu -> cookie manager -> manage stored
cookies -> remove all cookies option
● Cookies can be restricted from coming to clients from the server through
browser settings. This may fail session tracking.
○ In Internet Explorer:
○ Tools menu -> internet options -> privacy tab (to block cookies)
○ In Netscape:
○ Tools menu -> cookie manager -> block cookies from this site to
block the cookies.
● The values placed in cookies can be viewed through browser settings that
means there is not data secrecy.
● There is a restriction on the number of cookies that can be there that is per
browser window, per domain maximum of 20 cookies, and all domains
together per browser window maximum of 300 cookies (may vary browser to
browser).
1. URL rewriting works just about everywhere, especially when cookies are
turned off.
2. Multiple simultaneous sessions are possible for a single user. Session
information is local to each browser instance since it’s stored in URLs in each
page being displayed. This scheme isn’t foolproof, though, since users can
start a new browser instance using a URL for an active session, and confuse
the server by interacting with the same session through two instances.
3. Entirely static pages cannot be used with URL rewriting, since every link must
be dynamically written with the session state. It is possible to combine static
and dynamic content, using (for example) templating or server-side includes.
This limitation is also a barrier to integrating legacy web pages with newer,
servlet-based pages.
We can invalidate the existing session by using invalidate() method. It invalidates the
current session and unbinds any objects that were previously bound to it.
A container initializes a servlet when it receives a request for the servlet first time as it does
not initialize the servlets as soon as it starts up. This is called lazy loading.
Taking the request from a browser window and processing that request by using multiple
servlets as a chain is called servlet chaining. In servlet chaining, we perform communication
between servlet programs to process the request given by a client.
This is one of the frequently asked Servlet Interview Questions and Answers. Intercepting
filter is a special web resource program of a web application that can trap all the requests
and responses of other web resource programs. Intercepting filter contains common and
global pre-request logic and post-response generation logic. In servlet programming, we
can use servlet filter as the “Interceptor” filter of the web application. Without disturbing the
existing web resource of a web application if you want to add additional functionality to web
application then use servlet filter support.
This is one of the frequently asked Servlet Interview Questions and Answers. The functions
of the servlet container are as follows: