Servlet Interview
Questions - 1
1- How
many objects of a servlet is created?
Only one object at the time of first request by servlet or web container.
2- What
is the life-cycle of a servlet?
The web container maintains the life cycle of a servlet instance. Let's
see the life cycle of the servlet:
Servlet class is loaded.
Servlet instance is created.
init method is invoked.
service method is invoked.
destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created.
After invoking the init() method, Servlet comes in the ready state. In the
ready state, servlet performs all the tasks. When the web container invokes the
destroy() method, it shifts to the end state.
1)
Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.
2)
Servlet instance is created
The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.
3) init
method is invoked
The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life
cycle method of the javax.servlet.Servlet interface. Syntax of the init method
is given below:
public void init(ServletConfig config) throws ServletException
4) service method is invoked
The web container calls the service method each time when request for the
servlet is received. If servlet is not initialized, it follows the first three
steps as described above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet is initialized
only once. The syntax of the service method of the Servlet interface is given
below
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource
for example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:
public void destroy()
3- What
are the life-cycle methods for a servlet?
public void init(ServletConfig config)
It is invoked only once when first request comes for the
servlet. It is used to initialize the servlet.
public void service(ServletRequest request,ServletResponse)throws
ServletException,IOException
It is invoked at each request.The service() method is used to service the
request.
public void destroy()
It is invoked only once when servlet is unloaded.
4- Who
is responsible to create the object of servlet?
The web container or servlet container.
5- When
servlet object is created?
At the time of first request.
6- What
is difference between Get and Post method?
Get -
1) Limited amount of data can be sent because data is sent in header.
2) Not Secured because data is exposed in URL bar.
3) Can be bookmarked
4) Idempotent
5) It is more efficient and used than Post
Post
1) Large amount of data can be sent because data is sent in body.
2) Secured because data is not exposed in URL bar.
3) Cannot be bookmarked
4) Non-Idempotent
5) It is less efficient and used
7- What
is difference between PrintWriter and ServletOutputStream?
PrintWriter is a character-stream class where as ServletOutputStream is a
byte-stream class. The PrintWriter class can be used to write only
character-based information whereas ServletOutputStream class can be used to
write primitive values as well as character-based information.
8- What is difference between GenericServlet and HttpServlet?
The GenericServlet is protocol independent whereas HttpServlet is HTTP protocol
specific. HttpServlet provides additional functionalities such as state
management etc.
9- What
is servlet collaboration?
When one servlet communicates to another servlet, it is known as servlet
collaboration. There are many ways of servlet collaboration:
RequestDispacher interface
sendRedirect() method etc.
10-
What is the purpose of RequestDispatcher Interface?
The RequestDispacher interface provides the facility of dispatching the request
to another resource it may be html, servlet or jsp. This interceptor can also
be used to include the content of antoher resource.
11- Can
you call a jsp from the servlet?
Yes, one of the way is RequestDispatcher interface for example:
RequestDispatcher
rd=request.getRequestDispatcher("/login.jsp");
rd.forward(request,response);
12-
Difference between forward() method and sendRedirect() method ?
forward() method
1) forward() sends the same request to another resource.
2) forward() method works at server side.
3) forward() method works within the server only.
sendRedirect() method
1) sendRedirect() method sends new request always because it uses the URL bar
of the browser.
2) sendRedirect() method works at client side
3) sendRedirect() method works within and outside the server.
13-
What is difference between ServletConfig and ServletContext?
The container creates object of ServletConfig for each servlet whereas object
of ServletContext is created for each web application.
14-
What is Session Tracking?
Session simply means a particular interval of time.
Session Tracking is a way to maintain state of an user.Http
protocol is a stateless protocol.Each time user requests to the server, server
treats the request as the new request.So we need to maintain the state of an
user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It
is shown in the figure given below:
Why use Session Tracking?
To recognize the user It is used to recognize the particular
user.
Session Tracking Techniques
There are four techniques used in Session tracking:
Cookies
Hidden Form Field
URL Rewriting
HttpSession
15-
What are Cookies?
There are 2 types of cookies in servlets.
Non-persistent cookie
Persistent cookie
Non-persistent cookie
It is
valid for single session only. It is removed each time when user closes the
browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes
the browser. It is removed only if user logout or signout.
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
16-
What is difference between Cookies and HttpSession?
Cookie works at client side whereas HttpSession works at server side.
17-
What is filter?
A filter is an object that is invoked at the preprocessing and postprocessing
of a request.
It is mainly used to perform filtering tasks such as conversion,
logging, compression, encryption and decryption, input validation etc.
18- How
can we perform any action at the time of deploying the project?
By the help of ServletContextListener interface.
19- What
is the disadvantage of cookies?
It will not work if cookie is disabled from the browser.
20- How
can we upload the file to the server using servlet?
One of the way is by MultipartRequest class provided by third party.
21-
What is load-on-startup in servlet?
The load-on-startup element of servlet in web.xml is used to load the servlet
at the time of deploying the project or server start. So it saves time for the
response of first request.
22-
What if we pass negative value in load-on-startup?
It will not affect the container, now servlet will be loaded at first request.
23-
What is war file?
A war (web archive) file specifies the web elements. A servlet or jsp project
can be converted into a war file. Moving one servlet project from one place to
another will be fast as it is combined into a single file.
24- How to create war file?
The war file can be created using jar tool found in jdk/bin directory. If you
are using Eclipse or Netbeans IDE, you can export your project as a war file.
To create war file from console, you can write following code.
jar -cvf abc.war *
25-
What are the annotations used in Servlet 3?
There are mainly 3 annotations used for the servlet.
@WebServlet : for servlet class.
@WebListener : for listener class.
@WebFilter : for filter class.
26-
Which event is fired at the time of project deployment and undeployment?
ServletContextEvent.
27-
Which event is fired at the time of session creation and destroy?
HttpSessionEvent.
28-
Which event is fired at the time of setting, getting or removing attribute from
application scope?
ServletContextAttributeEvent.
29-
What is the use of welcome-file-list?
It is used to specify the welcome file for the project.
30- What is the use of attribute in servlets?
Attribute is a map object that can be used to set, get or remove in request,
session or application scope. It is mainly used to share information between
one servlet to another.
Servlet interview
Questions - 2
1- What is a Servlet?
Java Servlets is a Server side technology(basically specification) that allow
the programmer to develop dynamic web resource program or server side web
resource program in Java based web application.
Servlet is the software specification given by sun microsystem that provide set
of rule and guideline for vendor company to develop software called servlet
container.
Servlet is single instance multiple threads based java component in Java web
application to generate dynamic web application.
2- What are the types of Servlet?
There are two types of servlets, GenericServlet and HttpServlet. GenericServlet
defines the generic or protocol independent servlet. HttpServlet is subclass of
GenericServlet and provides http protocl specific functionality.
3- What are the differences between a Servlet and an Applet?
1) Servlets are server side components that executes on the server whereas
applets are client side components and executes on the web browser.
2)Applets have GUI interface but there is no GUI interface in case of
Servlets.
3)Applets have limited capabilities whereas Servlets are very poweful and can
support a wide variety of operations
4)Servlets can perform operations like interacting with other servlets, JSP
Pages, connect to databases etc while Applets cannot do all this.
4- What
are the different methods present in a HttpServlet?
The methods of HttpServlet class are :
doGet() - To handle the GET, conditional GET,
and HEAD requests
doPost() - To handle POST requests
doPut() - To handle PUT requests
doDelete() - To handle DELETE requests
doOptions() - To handle the OPTIONS requests and
doTrace() - To handle the TRACE requests
Apart from these, a Servlet also contains init() and destroy() methods that are
used to initialize and destroy the servlet respectively. They are not any
operation specific and are available in all Servlets for use during their
active life-cycle.
5- What are the advantages of Servlets over CGI
programs?
Java Servlets have a number of advantages over CGI and other API's. Some are:
1. Platform Independence - Java Servlets are 100% pure Java, so it is platform
independent. It can run on any Servlet enabled web server. For example if you
develop an web application in windows machine running Java web server. You can
easily run the same on apache web server without modification code. Platform
independency of servlets provide a great advantages over alternatives of
servlets.
2. Performance - Anyone who has used CGI would agree that Servlets are much
more powerful and quicker than CGI. Because the underlying technology is Java,
it is fast and can handle multiple request simultaneously. Also, a servlet gets
initialized only once in its lifetime and then continues to serve requests
without having to be re-initialized again, hence the performance is much higher
than CGIs.
3. Extensibility - Java Servlets are developed in java which is robust,
well-designed and object oriented language which can be extended or polymorphed
into new objects. So the java servlets takes all these advantages and can be
extended from existing class the provide the ideal solutions.
Also, in terms of Safety & Security Servlets are superior when compared to
CGI.
6- What are the type of protocols supported by HttpServlet?
It extends the GenericServlet base class and provides an framework for handling
the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.
7- What is ServletContext?
ServletContext is an Interface that defines a set of methods that a servlet
uses to communicate with its servlet container, for example, to get the MIME
type of a file, dispatch requests, or write to a log file. There is one context
per "web application" per Java Virtual Machine.
8- What is meant by Pre-initialization of Servlet?
When servlet container is loaded, all the servlets defined in the web.xml file
do not get initialized by default. When the container receives a request to hit
a particular servlet, it loads that servlet. But in some cases if you want your
servlet to be initialized when context is loaded, you have to use a concept
called pre-initialization of Servlet. In this case, the servlet is loaded when
context is loaded. You can specify 1 in between the tag in the
Web.xml file in order to pre-initialize your servlet.
Example.
<Load-on-startup>1</Load-on-startup>
9- What mechanisms are used by a Servlet
Container to maintain session information?
Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information
to maintain the session.
10- What do you understand by servlet mapping?
Servlet mapping defines an association between a URL pattern and a servlet. You
can use one servlet to process a number of url patterns. For example in case of
Struts *.do url patterns are processed by Struts Controller Servlet.
11- What interface must be implemented by all Servlets?
The Servlet Interface must be implemented by all servlets (either the
GenericServlet or the HttpServlet)
12- What are the uses of Servlets?
1) Servlets are used to process the client requests.
2) A Servlet can handle multiple request
concurrently and be used to develop high performance system
3) A Servlet can be used to load balance among
serveral servers, as Servlet can easily forward request.
13- What are the objects that are received when a servlets
accepts call from client?
The objects are:
ServeltRequest and
ServletResponse
The ServeltRequest encapsulates the communication from the client to the
server. While ServletResponse encapsulates the communication from the Servlet
back to the client. All the passage of data between the client and server
happens by means of these request and response objects.
Servlet interview
Questions – 3
1- What are the new features added to Servlet 2.5?
Following are the new features introduced in Servlet 2.5:
• A new dependency on Java SE 5.0
• Support for annotations
• Loading the class
• Several web.xml conveniences
• A handful of removed restrictions
• Some edge case clarifications
2- Why do we need a constructor in a servlet if we use the
init method?
Even though there is an init method in a servlet which gets called to
initialize it, a constructor is still required to instantiate the servlet. Even
though you as the developer would never need to explicitly call the servlet's
constructor, it is still being used by the container (the container still uses
the constructor to create an instance of the servlet).
Let us say in a plain java class, you created an init method that gets invoked
under some condition, will you be able to invoke it without actually instantiating
your class? That is why we need a constructor even for a Servlet.
3- When is the servlet loaded?
A servlet can be loaded when:
First request is made.
Server starts up (auto-load).
There is only a single instance which answers all requests concurrently. This
saves memory and allows a Servlet to easily manage persistent data.
Administrator manually loads.
4- When is a Servlet unloaded?
A servlet is unloaded when:
Server shuts down.
Administrator manually unloads.
5- What is the GenericServlet class?
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 generic servlet, since it is not specific to any
protocol whereas the HttpServlet is specific to the Http Protocol
6- Why is the HttpServlet class declared abstract?
The HttpServlet class is declared abstract because the default implementations
of the main service methods do nothing and must be overridden. Just like any
other abstract class, the HttpServlet is a partial skeleton which defines basic
behavior and then gives the programmer the freedom to implement any of the
other possible features he/she wants.
The simplest example here could be the fact that, any HttpServlet could handle
multiple doXXX() methods as we call them which include doGet(), doPost() etc.
So, in your applications, if you handle just the POST requests, then you need
not implement a doGet() to override the default doGet() implementation.
7- Can a servlet have a constructor?
Sure Yes. Though we don’t explicitly call the constructor using the new()
operator, the container internally invokes the Servlet class’ container when
the servlet is initialized.
8- Should I override the service() method while using the
HttpServlet?
We never override the service method, since the HTTP Servlets have already
taken care of it. The default service method invokes the doXXX() method
corresponding to the method of the HTTP request. For example, if the HTTP
request method is GET, doGet() method is called by default. A servlet should
override the doXXX() method for the HTTP methods that servlet supports. Because
HTTP service method checks the request method and calls the appropriate handler
method, it is not necessary to override the service method itself. Only
override the appropriate doXXX() method.
9- What are the differences between the ServletConfig
interface and the ServletContext interface?
Servlet Config Object-
1.
It is one per our Servlet/JSP program.
2.
Servlet Config object means it is the object of
Servlet container Supplied Java class implement javax.Servlet.ServletConfig
interface.
3.
This object is used to pass additional data to
Servlet and to read additional details from Servlet.
4.
This object is used to read Servlet init()
parameter value of the web application.
5.
Servlet container create the object of Servlet
config during instantiation and initialization.
6.
Servlet container destroys the Servlet config
object during destruction process of our Servlet object.
Servlet Context Object-
1.
It is one per web application so it is called as the global
memory of the web application.
2.
Servlet Context object means it is the object of java class
implementing javax.Servlet.ServletContext interface.
3.
Servlet container create this object during during the
deployement of web application.
4.
Servlet container destroy this object automatically when web
application is undeployed or reloaded or Stopped.
5.
Using this object we can know the detail of underline Server
like Server-name,version and Servlet api version.
10- What are the differences between forward()
and sendRedirect() methods?
Some key differences between the two methods are:
a. A Forward is performed internally by the servlet whereas a redirect is a
two-step process where the web application instructs the web browser to fetch a
second/different URL
b. The browser and the user is completely unaware that a forward has taken
place (The URL Remains intact) whereas in case of redirect, both the browser
and the user will be made aware of the action including a change to the URL
c. The resource to which control is being forwarded has to be part of the same
context as the one that is actually calling it whereas in case of redirect this
is not a restriction.
d. Forwards are faster than redirects. Redirects are slower because it is actually
handling two browser requests in place of forward’s one.
11- What are the difference between the include() and
forward() methods?
The key differences between the two methods are:
a. The include() method inserts the contents of the specified resource directly
into the flow of the servlet response, as if it were part of the calling
servlet, whereas the forward() is used to show a different resource in place of
the servlet that was originally called
b. The include() is often used to include common text or template markup that
may be included in many servlets whereas forward() is often used where a
servlet plays the role of a controller, processes some input and decides the
outcome by returning a particular page response where control is transferred to
a different resource
12- What is the use of the servlet wrapper classes?
The HttpServletRequestWrapper and HttpServletResponseWrapper classes are
designed to make it easy for developers to create custom implementations of the
servlet request and response types. The classes are constructed with the
standard HttpServletRequest and HttpServletResponse instances respectively and
their default behavior is to pass all method calls directly to the underlying
objects.
13- What is a deployment descriptor?
A deployment descriptor is an XML document. It defines a component's deployment
settings. It declares transaction attributes and security authorization for an
enterprise bean. The information provided by a deployment descriptor is
declarative and therefore it can be modified without changing the source code
of a bean.
The Java EE server reads the deployment descriptor at run time and acts upon
the components accordingly.
14- What is the difference between the
getRequestDispatcher(String path) method of javax.servlet.ServletRequest
interface and javax.servlet.ServletContext interface?
The getRequestDispatcher(String path) method of javax.servlet.ServletRequest
interface accepts parameter the path to the resource to be included or
forwarded to, which can be relative to the request of the calling servlet. If
the path begins with a “/” it is interpreted as relative to the current context
root, whereas, the getRequestDispatcher(String path) method of
javax.servlet.ServletContext interface cannot accept relative paths. All path
must start with a “/” and are interpreted as relative to current context root.
15- What is the < load-on-startup > element of the
deployment descriptor?
The element of a deployment descriptor is used to load a servlet file when
the server starts instead of waiting for the first request. This setting by
which a servlet is loaded even before it gets its first request is called
pre-initialization of a servlet. It is also used to specify the order in which
the files are to be loaded. The container will load the servlets in the order
specified in this element.
16- What is servlet lazy loading?
Lazy servlet loading means – the container does not initialize the servlets as
soon as it starts up. Instead it initializes servlets when they receive their
first ever request. This is the standard or default behavior. If you want the
container to load your servlet at start-up then use pre-initialization using
the load-on-startup element in the deployment descriptor.
17- What is Servlet Chaining?
Servlet Chaining is a method where the output of one servlet is piped or passed
onto a second servlet. The output of the second servlet could be passed on to a
third servlet, and so on. The last servlet in the chain returns the output to
the Web browser.
18- What are filters?
Filters are Java components that are used to intercept an incoming request to a
Web resource or the response that is sent back from the resource. It is used to
abstract any useful information contained in the request or response. Some of
the important functions performed by filters are:
Security checks
Modifying the request or response
Data compression
Logging and auditing
Response compression
Filters are configured in the deployment descriptor of a Web application.
Hence, a user is not required to recompile anything to change the input or
output of the Web application.
19- What are the functions of the Servlet container?
The functions of the Servlet container are as follows:
1.
Lifecycle management: It manages the life and death of a
servlet, such as class loading, instantiation, initialization, service, and
making servlet instances eligible for garbage collection.
2.
Communication support: It handles the communication between the
servlet and the Web server.
3.
Multithreading support: It automatically creates a new thread
for every servlet request received. When the Servlet service() method
completes, the thread dies.
4.
Declarative security: It manages the security inside the XML
deployment descriptor file.
5.
JSP support: The container is responsible for converting JSPs to
servlets and for maintaining them.
Session Based Interview
Questions
1. What is a Session?
A Session refers to all the request that a single client makes to a server. A
session is specific to the user and for each user a new session is created to
track all the requests from that particular user. Sessions are not shared among
users and each user of the system will have a seperate session and a unique
session Id. In most cases, the default value of time-out* is 20 minutes and it
can be changed as per the website requirements.
*Time-Out - The Amount of time after which a session becomes
invalidated/destroyed if the session has been inactive.
2. What is Session ID?
A session ID is an unique identification string usually a long, random and
alpha-numeric string, that is transmitted between the client and the server.
Session IDs are usually stored in the cookies, URLs (in case url rewriting) and
hidden fields of Web pages.
3. What is Session Tracking?
HTTP is stateless protocol and it does not maintain the client state. But there
exist a mechanism called "Session Tracking" which helps the servers
to maintain the state to track the series of requests from the same user across
some period of time.
4. What are different types of Session Tracking?
Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions
5. What is HTTPSession Class?
HttpSession Class provides a way to identify a user across across multiple
request. The servlet container uses HttpSession interface to create a session
between an HTTP client and an HTTP server. The session lives only for a
specified time period, across more than one connection or page request from the
user.
6. Why do we need Session Tracking in a Servlet based Web
Application?
In HttpServlet you can use Session Tracking to track the user state. Simply
put, it is used to store information like users login credentials, his choices
in previous pages (like in a shopping cart website) etc
7. What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. It keeps the website
URL clean and concise instead of a long string appended to the URL everytime
you click on any link in the website. Also, when we use url rewriting, it
requites large data transfer from and to the server. So, it may lead to
significant network traffic and access to the websites may be become slow.
8. What is session hijacking?
If you application is not very secure then it is possible to get the access of
system after acquiring or generating the authentication information. Session
hijacking refers to the act of taking control of a user session after
successfully obtaining or generating an authentication session ID. It involves
an attacker using captured, brute forced or reverse-engineered session IDs to
get a control of a legitimate user's Web application session while that session
is still in progress.
9. What is Session Migration?
Session Migration is a mechanism of moving the session from one server to
another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.
10. How to track a user session in Servlets?
The interface HttpSession can be used to track the session in the Servlet.
Following code can be used to create session object in the Servlet:
HttpSession session = req.getSession(true);
Using this session object, the servlet can gain access to the details of the
session.
11. How can you destroy the session in Servlet?
You can call invalidate() method on the session object to destroy the session.
e.g. session.invalidate();
0 Comments