servlet interview questions and answers


1.What is the Servlet?

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.


2.What are the new features added to Servlet 2.5?

Following are the changes introduced in Servlet 2.5:

*       A new dependency on J2SE 5.0

*       Support for annotations

*       Loading the class

*       Several web.xml conveniences

*       A handful of removed restrictions

*       Some edge case clarifications

3.What are the uses of Servlet?

Typical uses for HTTP Servlets include:

*       Processing and/or storing data submitted by an HTML form.

*       Providing dynamic content, e.g. returning the results of a database query to the client.

*       A Servlet can handle multiple request concurrently and be used to develop high performance system

*       Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

4.What are the advantages of Servlet over CGI?

Servlets have several advantages over CGI:

*       A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.

*       A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.

*       There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.

*       Several web.xml conveniences

*       A handful of removed restrictions

*       Some edge case clarifications


5.What are the phases of the servlet life cycle?

The life cycle of a servlet consists of the following phases:

*       Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.

*       Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.

*       Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.

*       Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.

*       Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection

The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

 
6.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). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven't constructed an object to call it on yet.


7.How the servlet is 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.


8.How a Servlet is unloaded?

A servlet is unloaded when:

*       Server shuts down.

*       Administrator manually unloads.


9.What is Servlet interface?

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , more commonly by extending a class that implements it.


Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.



10.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.

11.What's the difference between GenericServlet and HttpServlet?

GenericServlet
HttpServlet
The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods.
An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.
The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers.
The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method.
GenericServlet is not specific to any protocol.
HttpServlet only supports HTTP and HTTPS protocol.

12.Why is HttpServlet declared abstract?

The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience 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.


13.Can servlet have a constructor ?

One can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose,but this type of approch is not so common. You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.


14.What are the types of protocols supported by HttpServlet ?

It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.


15.What is the difference between doGet() and doPost()?

#
doGet()
doPost()
1
In doGet() the parameters are appended to the URL and sent along with header information.
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
The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.
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
doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent)
doPost() provides information (such as placing an order for merchandise) that the server is expected to remember
4
Parameters are not encrypted
Parameters are encrypted
5
doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance
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
doGet() should be idempotent. i.e. doget should be able to be repeated safely many times
This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
7
doGet() should be safe without any side effects for which user is held responsible
This method does not need to be either safe
8
It allows bookmarks.
It disallows bookmarks.
What is the servlet?
Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.


What’s the difference between servlets and applets?
Servlets are to servers;
applets are to browsers.
Unlike applets, however, servlets have no graphical user interface.

What’s the advantages using servlets than using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with Java Servlet API, a standard Java extension.

What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

What’s the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet. Servlets–>Generic Servlet–>HttpServlet–>MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

When a servlet accepts a call from a client, it receives two objects. What are they?
ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

What is Java Servlet?
A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request/response paradigm.

Why is Servlet so popular?
Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.

What is servlet container?
The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.

When a client request is sent to the servlet container, how does the container choose which servlet to invoke?
The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.

If a servlet is not properly initialized, what exception may be thrown?
During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.

Given the request path below, which are context path, servlet path and path info?
/bookstore/education/index.html

context path: /bookstore
servlet path: /education
path info: /index.html

What is filter? Can filter be used as request or response?
A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?
I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.

What is new in ServletRequest interface?(Servlet 2.4)
The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()

Request parameter How to find whether a parameter exists in the request object?
1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)

How can I send user authentication information while makingURLConnection?
You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

Can we use the constructor, instead of init(), to initialize servlet?
Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.

How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push

The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to execute.

What mechanisms are used by a Servlet Container to maintain session information?
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

Difference between GET and POST in Java Servlets?
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.

What is Java Servlet session?
The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.

What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

What is servlet context ?
The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial).

Which interface must be implemented by all servlets?
Servlet interface.


No comments:

Post a Comment