Java Servlet Projects

Servlet Project 3

Servlet Subjective Questions And Answers
More interview questions and answers

What is a servlet ?

Servlets are the server side programs that runs on the server allow developer to add dynamic content and hand it to the web server and web server sent back to the client. 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. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs.

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.

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.

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


Can we use the constructor, instead of init(), to initialize servlet?

Yes. But you will not get the servlet specific things from constructor. So do not use constructor instead of init(). 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. Plus, all the other servlet programmers are going to expect your init code to be in init().

What is servlet context ?

Servlet context 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. A servlet context object is one per web application per JVM and this object is shared by all the servlet. You can get and set the Servlet context object. You can use servelt context object in your program by calling directly getServletContext() or getServletConfig().getServletContext().

What is servlet mapping?

Servlet mapping controls how you access a servlet. Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. For this purpose web container uses the Deployment Decriptor (web.xml) file. Servlets are registered and configured as a part of a Web Application. To register a servlet, you add several entries to the Web Application deployment descriptor.

Servlet Mapping : 









A developer can map all the servelts inside its web application.

What is session?

A session refers to all the connections that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables. A session keeps all of the state that you build up bundled up so that actions you take within your session do not affect any other users connected to other sessions.

What Difference between GET and POST ?

Difference between GET and POST : 

  * Client can send information to the server by two methods : GET and POST.

  * The GET method appends parameters (name/value) pairs to the URL. The length of a URL is limited, there is a character restriction of 255 in the URL.  so this method only works if there are only a few parameters.  

  * The main difference between GET and POST is, POST has a body. Unlike GET, parameters are passed in the body of the POST insteat of appending to the URL. We can send large number of data with the POST.  

  * \"GET\" is basically for just getting (retrieving) data whereas \"POST\" may involve anything, like storing or updating data, or ordering a product, or sending E-mail.

  * The data send with the GET method is visible at the browser\'s address bar. Don\'t send important and sensitive data with GET method, use POST.

  * Get is idempotent, means it has no side effects on re-requesting the same thing on the server.

What mechanisms are used by a Servlet Container to maintain session information?

 The mechanisms used by a Servlet Container to maintain session information : 

a) Cookies

b) URL rewriting

c) Hidden form fields

d) SSL (using HTTPS protocol) Sessions

What are the different ways for session tracking?

The concept of session tracking allows you to maintain the relation between the two successive request from the same client (browser). The browser sends the request to the server and server process the browser request generate the response and send back response to the browser. The server is not at all bothered about who is asking for the pages. The server (because of the use of HTTP as the underlying protocol) has no idea that these 2 successive requests have come from the same user. There is no connection between 2 successive requests on the Internet. 

There are three ways of tracking sessions : 

   * Using Cookies.

   * Using URL Rewriting.

   * Using Hidden Form Fields.


What is the difference between ServletContext and ServletConfig?

ServletContext and ServletConfig are declared in the deployment descriptor. ServletConfig is one per servlet and can be accessed only within that specific servlet. ServletContext is one per web application and accessible to all the servlet in the web application.

How can a servlet refresh automatically?

We can Refresh Servlet Page by two ways : one through client side and another through Server Push.

Client Side Refresh :

< META HTTP-EQUIV=\"Refresh\" CONTENT=\"5; URL=/servlet/MyServlet/\">

Server Side Refresh :


This will update the browser after every 5 seconds

What is Server side push?

The term \'server push\' generally means that a server pushes content to the browser client. Server push is a Netscape-only scheme for providing dynamic web content. Server side push is a mechanism that support real time connection to the server with the advantage of instant updates.

Server side push may be emulated in a number of ways.

    * The client polls the server at a certain interval, say every five minutes. This technique is typically used to update news information. The client does this by reloading a page every so often.

    * The client uses the \'multipart/x-mixed-replace\' content type when sending a response. The content type is expected to send a series of documents one after the other, where each one will replace the previous one. The server might delay between each part, which gives the illusion that the data is being updated after an interval. This technique requires a connection to stay open.


What is the Max amount of information that can be saved in a Session Object ?

There is no limit for amount of information that can be seve into the session object. It depends upon the RAM available on the server machine. The only limit is the Session ID length which should not exceed more than 4K. If the data to be store is very huge, then it\'s preferred to save it to a temporary file onto hard disk, rather than saving it in session.

Why should we go for inter servlet communication?

Due ot the following reason need inter servlet communication :

  * Two servlet want to communicate to complete the shopping cart.

  * One servlet handles the client request and forward it to another servlet to do some calculation or add some information to complete the view.

  * One servlet want to reuse the some methods of another servlet.

What is a output comment?

A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page

source from your Web browser.

JSP Syntax

<!-- comment [ <%= expression %> ] -->

Example 1

<!-- This is a commnet sent to client on

<%= (new java.util.Date()).toLocaleString() %>


What are the differences between a session and a cookie?

Differences between a session and a cookie :

  * A cookie is a special piece of data with a bit of associated metadata that an HTTP server includes in an HTTP response. A session is a series of related HTTP requests and responses that

together constitute a single conversation between a client and server.

  * Cookies are stored at the client side whereas session exists at the server side.

  * A cookie can keep information in the user\'s browser until deleted, whereas you close your browser you also lose the session.

  * Cookies are often used to store a session id, binding the session to the user. 

  * There is no way to disable sessions from the client browser but cookies.

What is HttpTunneling?

Encapsulating the information into the Http header and directed it to a server at the other end of the communication channel that takes the packets, strips the HTTP encapsulation headers and redirects the packet to its final destination.

HTTP-Tunnel acts as a socks server, allowing you to use your Internet applications safely despite restrictive firewalls and/or you not be monitored at work, school, goverment and gives you a extra layer of protection against hackers, spyware, ID theft\'s with our encryption. 

Reason For HTTP-Tunnel : 

    *  Need to bypass any firewall

    * Need secure internet browsing

    * Need to use favorite programs with out being monitored by work, school, ISP or gov.

    * Extra security for online transactions

    * Encrypt all your Internet traffic.

    * Need play online games

    * Visit sites that you are previously blocked

    * Prevent 3rd party monitoring or regulation of your Internet browsing and downloads

    * Use your favorite applications previously blocked

    * Hide your IP address

    * Make it next to impossible for you to identify online.

    * Free unlimited data transfer

    * Compatible with most major Internet applications

    * Secure and virus-free servers

    * 99% uptime

    * No spam, pop-ups, or banners

 In many cases it is not possible to establish a connection between JMS clients and a SwiftMQ message router or between two SwiftMQ message routers if one part stands behind a firewall. In general it exists a proxy server to which it is allowed exclusively to establish an internet connection by a firewall. To avoid this fact, an operation called HTTP tunneling is used. 

Why in Servlet 2.4 specification SingleThreadModel has been deprecated?

Tere is no practical implementation to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

How can I set a cookie?

The following program demonstrate that how to set the cookie :

import javax.servlet.*;

import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response) {

    response.addCookie(new Cookie(\"cookie_name\", \"cookie_value\"));



  public void doGet(HttpServletRequest req, HttpServletResponse res) {

    doPost(req, res);



How will you delete a cookie?

To delete cookie from servlet, get the cookie from the request object and use setMaxAge(0) and then add the cookie to the response object. 


     Cookie killMyCookie = new Cookie(\"mycookie\", null);



What is the difference between Context init parameter and Servlet init parameter?

Context init parameter is accessible through out the web application and declared outside the <servlet>...</servlet> element tag in the deployment descriptor(DD) . Servlet init parameters are declared inside the <servlet>...</servlet> element and only accessible only to the that specific servlet. You can access the context init parameters using the getServletContext() method and Servlet init parameters using the getServletConfig() method. 

Declaring the Servlet init parameter in DD :



   <servlet-name>My Page</servlet-name>




      <param-value></param-value) </init-param>


Declaring the Context init parameter in DD :





What are the different ways for getting a servlet context?

The different ways for getting a servlet context :

  * ServletConfig.getServletContext()

  * GenericServlet implements ServletConfig, so HttpServlets all have a getServletContext() method

  * In a Filter you have access to the FilterConfig which is set in the init(FilterConfig fc) callback. You can use FilterConfig.getServletContext().

  * In a ServletContextListener or a ServletContextAttributeListener, the event passed to the listener methods has a getServletContext() method. 

What is the difference between an attribute and a parameter?

Request parameters are the name/value pairs, and the result of submitting an HTML form. The name and the values are always strings. For example, when you do a post from html, data can be automatically retrieved by using request.getParameter() at the server side. Parameters are Strings, and generally can be retrieved, but not set. 

Attributes are objects, and can be placed in the request, session, or context objects. Because they can be any object, not just a String, they are much more flexible. You can also set attributes programatically using setAttribute() method, and retrieve them later using getAttribute() method.

How to make a context thread safe?

To make the context scope thread safe, you need a lock on context object. To synchronize the context attribute is to synchronize on context object. If a thread gets a lock on context object, then you are guaranteed that only one thread at a time can be getting or setting the context attribute. It only works if all of the other code that manipulate the context attribuet also synchronizes on the servlet context.

What is the difference between setting the session time out in deployment descriptor and setting the time out programmatically?

Setting the time out programmatically means calling setMaxInactiveInterval(int seconds) from your servlet.

Setting the session time out in deployment descriptor means declaratively setting the session timeout. The following setting in the deployment descriptor causes the session timeout to be set to 10 minutes:




Setting the session time out in deployment descriptor allows you to modify the time easily, hard code it into the program requires recompilation overhead.

How can my application get to know when a HttpSession is removed?

To get notified that a HttpSession is removed or created, you should implement the HttpSessionBindingListener in the class that implements the two of its method : sessionCreated() and sessionDestroyed(). If a session is created or destroyed, the  sessionCreated() or sessionDestroyed() method respectively will be called automatically. You must register this listener implementing class inside the <listener>...</listener> element in the deployment descriptor(web.xml) file.

How many cookies can one set in the response object of the servlet? Also, are there any restrictions on the size of cookies?

A cookie has a maximum size of 4K, and no domain can have more than 20 cookies.

When a session object gets added or removed to the session, which event will get notified ?

When an object is added or removed from a session, the container checks the interfaces implemented by the object. If the object implements the HttpSessionBindingListener, the container calls the matching notification method. 

If session is added then sessionCreated() method, and if session is removed then sessionDestroyed() method will be callled automatically by the web container.

What is URL Encoding and URL Decoding ?

Some characters are not valid in URLs like & can\'t be placed in a URL query string without changing the meaning of that query string.

These problems can be be fixed by \'escaping\' them. This process involves scanning the text for those characters, and replacing them with a special character-code that browsers can interpret as the correct symbol, without actually using that symbol in your URL.

For example, the escaped character code for \'=\' is \'%3d\'. 

What is the difference between an applet and a servlet?

Applets are client side java program that are dynamically downloaded over the internet and executed by browser. Servlets are server side program runs on the server. When a request come to server for the specific servlet, then servlet handles the client request, and send response back to the client. 

Servlet doesn\'t have GUI , while applet have GUI. Applet are very heavy to handle as compared to servlet.

What is life cycle of servlet?

A web container manages the life cycle of the servlet :

  * Loading and Inatantiation: container load the servlet class at the first request to that servlet. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. Instantiation is done by calling the default constructor.

  * Initialization: calling the init() method.

  * Servicing the Request: calling the service() method and pass the HttpServletRequest and HttpServletResponse object as the parameters.

  * Destroying the Servlet: calling the destroy() method.

When init() and Distroy() will be called.

Both init() and destroy() method called only once within its lifecycle.

The init() method will be called after instantaition of servlet, i.e. after the constructor calling. The destroy() method will be called when servlet is removed from the server, i.e. when server shuts down.

What is the use of setComment and getComment methods in Cookies ?

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. 

The setComment(java.lang.String purpose) method Specifies a comment that describes a cookie\'s purpose.The getComment() method returns the comment describing the purpose of the cookie, or null if the cookie has no comment.

Why we are used setMaxAge() and getMaxAge() in Cookies ?

The \"public void setMaxAge(int expiry)\" method sets the maximum age of the cookie. After the specified time the cookie will be deleted.

The \"public int getMaxAge()\" method will return the maximum specified age of the cookie.

What is the use of setSecure() and getSecure() in Cookies ?

The setSecure(boolean flag) method indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.

The getSecure() method returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol.

How do you communicate between the servlets?

Servlets can communicate using the request, session and context scope objects by setAttribute() and getAttribute() method. A servlet can placed the information in one of the above scope object and the other can find it easily if it has the reefrence to that object.

What is Servlet chaining?

Servlet Chaining is a phenomenon wherein response Object (Output) from first Servlet is sent as request Object (input) to next servlet and so on. The response from the last Servlet is sent back to the client browser.

In Servlets, there are two ways to achieve servlet chaining using javax.servlet.RequestDispatcher:

   1. Include:

    RequestDispatcher rd = req.getRequestDispatcher(\"Servlet2\");

      rd.include(req, resp);

   2. Forward, where req is HttpServletRequest and resp is HttpServletResponse:

    RequestDispatcher rd = req.getRequestDispatcher(\"Servlet3\");

      rd.forward(req, resp);

How will you communicate from an applet to servlet?

You can write a servlet that is meant to be called by your applet. 

Applet-Servlet Communication with HTTP GET and POST : 

The applet can send data to the applet by sending a GET or a POST method. If a GET method is used, then the applet must URL encode the name/value pair parameters into the actual URL string.

Communicating with Object Serialization :

Instead of passing each parameter of student information as name/value pairs, we\'d like to send it as a true Java object. Upon receipt of the this object, the servlet would add the this to the database.

Sending Objects from a Servlet to an Applet : 

After registering the object in the database. Now the servlet has to return an updated list of registered students that is then returned as a vector of  objects.

Can we call a servlet with parameters in the URL?

Yes! We can call a servlet with parameters in the URL using the GET method. Parameters are appended to the URL separated with the \'?\' with the URL and if there are more than one parameter, these are separated with the \'&\' sign.

How do servlets handle multiple simultaneous requests?

Servlets are under the control of web container. When a request comes for the servlet, the web container find out the correct servelt based on the URL, and create a separeate thread for each request. In this way each request is processed by the different thread simultaneously. 

Explain the directory structure of a web application?

The directory structure of a web application consists of two parts.

A private directory called WEB-INF

A public resource directory which contains public resource folder.

WEB-INF folder consists of

1. web.xml file that consist of deployment information.

2. classes directory cosists of business logic.

3. lib directory consists of jar files.

What is pre initialization of a servlet?

Servlets are loaded and initialized at the first request come to the server and stay loaded until server shuts down. However there is another way you can initialized your servlet before any request come for that servlet by saying <load-on-startup>1</load-on-startup> in the deployment descriptor. You can specify <load-on-startup>1</load-on-startup> in between the <servlet></servlet> tag.

What are the uses of ServletRequest?

ServletRequest defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet\'s service method.

A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest. 

Packages that use ServletRequest :

  * javax.servlet  

  * javax.servlet.http  

  * javax.servlet.jsp

What are the uses of ServletResponse interface?

ServletResponse interface defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet\'s service method.

To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually. 

Packages that use ServletResponse : 

  * javax.servlet  

  * javax.servlet.http  

  * javax.servlet.jsp  


How HTTP Servlet handles client requests?

HTTP Servlet is an abstract class that must be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these: 

  * doDelete(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a DELETE request.

  * doGet(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a GET request.

  * doOptions(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a OPTIONS request.

  * doPost(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a POST request.

  * doPut(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a PUT request.

  * doTrace(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a TRACE request. etc.


Is HTML page a web component?

No! Html pages are not web component, even the server-side utility classes are not considered web components. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification.

What is the web container?

The Web container provides the runtime environment through components that provide naming context and life cycle management, security and concurrency control. A web container provides the same services as a JSP container as well as a federated view of the Java EE. Apache Tomcat is a web container and an implementation of the Java Servlet and JavaServer Pages technologies.

What is deployment descriptor?

Deployment descriptor is a configuration file named web.xml that specifies all the pieces of a deployment. It allows us to create and manipulate the structure of the web application. Deployment descriptor describes how a web application or enterprise application should be deployed. For web applications, the deployment descriptor must be called web.xml and must reside in a WEB-INF subdirectory at the web application root. Deployment descriptor allows us to modify the structure of the web application without touching the source code.

Do objects stored in a HTTP Session need to be serializable? Or can it store any object?

It\'s important to make sure that all objects placed in the session can be serialized if you are building a distributed applicatoin. If you implement Serializable in your code now, you won\'t have to go back and do it later. 

How can you implement singleton pattern in servlets ?

Singleton is a useful Design Pattern for allowing only one instance of your class. you can implement singleton pattern in servlets by using using Servlet init() and <load-on-startup> in the deployment descriptor.

What is the difference between an application server and a web server?

A web server deals with Http protocols and serves the static pages as well as it can ask the helper application like CGI program to generate some dynamic content. A web server handles the client request and hands the response back to the client.

An application server exposes business logic to client applications through various protocols, possibly including HTTP. An application server provides access to business logic for use by client application programs. In addition, J2EE application server can run EJBs - which are used to execute business logic. An Application server has a \'built-in\' web server, in addition to that it supports other modules or features like e-business integration, independent management and security module, portlets etc.

What is servlet exception?

ServletException is a subclass of the Exception. It defines a general exception a servlet can throw when it encounters difficulty. ServletException class define only one method getRootCause() that returns the exception that caused this servlet exception. It inherit the other methods like fillInStackTrace, getLocalizedMessage, getMessage, printStackTrace, printStackTrace, printStackTrace, toString etc from the Throwable class.

Packages that use ServletException :

  * javax.servlet

  * javax.servlet.http


What is a WAR file?

A Web archive (WAR) file is a packaged Web application. WAR files can be used to import a Web application into a Web server. The WAR file also includes a Web deployment descriptor file. There are special files and directories within a WAR file. The /WEB-INF directory in the WAR file contains a file named web.xml which defines the structure of the web application. If the web application is only serving JSP files, the web.xml file is not strictly necessary. If the web application uses servlets, then the servlet container uses web.xml to ascertain to which servlet a URL request is to be routed. One disadvantage of web deployment using WAR files in very dynamic environments is that minor changes cannot be made during runtime. WAR file is created using the standard Java jar tool. For example:

    cd /home/alex/webapps/mywebapp 

    jar cf ../mywebapp.war * 

What is a servlet filter?

A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be \"attached\" to any type of servlet or JSP page. Filters provide the ability to encapsulate recurring tasks in reusable units and can be used to transform the response from a servlet or a JSP page. Filters can perform many different types of functions:

  * Authentication

  * Logging and auditing

  * Data compression

  * Localization

The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. A filter chain, passed to a filter by the container, provides a mechanism for invoking a series of filters. Filters must be configured in the deployment descriptor :

<!--Servlet Filter that handles site authorization.-->




     <description>This Filter authorizes user access to application components based upon request URI.</description>










What is Web resource ?

Web Resource is bassically a Static or dynamic object, Which is contained in a Web application that can be referenced by a URL. 

I plugged in a version of Apache Xalan that I downloaded from the Apache Web site, and now I get errors when I try to transform documents. What is the problem?

We must ensure that the version of Apache Xalan we download from the Apache Web site is compatible with Apache Xerces version 1.3.1. Because we can\'t plug in a different version of Apache Xerces , the only version of Apache Xerces that is compatible with WebLogic Server 6.1 is 1.3.1. The built-in parser and transformer have been modified by BEA to be compatible with each other.

What is Web server ?

Web server is type of Software, Its use for the providing to the many type of services like access the Internet, an intranet, or an extranet. A Web server hosts Web sites, provides support for HTTP and other protocols, and executes server-side programs that perform certain functions.