You are on page 1of 15

SERVLET INTERVIEW QUESTIONS

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

Learn more about Servlets 2.5 features 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:

The container initializes the servlet by invoking its init() method. or later when a client request is actually delegated to the servlet. To do this. the service() method invokes a different handler method for each type of HTTP request. and so on. passing the request and response objects as parameters.  Servlet instantiation : After loading. the container may keep it ready for handling client requests. the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities.  Request handling (call the service method) : After the servlet is initialized. the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. the container initializes a servlet before it is ready to handle client requests. so the init() method is invoked once and only once by the servlet container. doPost() method for POST requests. When client requests arrive. In the case of HTTP requests.  Initialization (call the init method) : After instantiation. passing an object implementing the ServletConfig interface. 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.  Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons. This can happen when the servlet engine itself is started. the servlet container calls the destroy() method on the servlet. the servlet container locates and loads a class of the type of the servlet. In the init() method. doGet() method for GET requests. it instantiates one or more object instances of the servlet class to service the client requests. the servlet may not service any more client requests. . In the HttpServlet class. Servlet class loading : For each servlet defined in the deployment descriptor of the Web application. such as to conserve memory resources. they are delegated to the servlet through the service() method. Once the destroy() method has been called.

How a Servlet is unloaded? A servlet is unloaded when:   Server shuts down. Just like a normal POJO (plain old java object) that might have an init method. a constructor is still required to instantiate the servlet. This saves memory and allows a Servlet to easily manage persistent data. There is only a single instance which answers all requests concurrently. Server starts up (auto-load). Even though you as the developer would never need to explicitly call the servlet's constructor. Administrator manually loads.How the servlet is loaded? A servlet can be loaded when:     First request is made. it is no use calling the init method if you haven't constructed an object to call it on yet.6. . 8. 7. Administrator manually unloads. it is still being used by the container (the container still uses the constructor to create an instance of the servlet).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.

extend one of the standard implementations of that interface. 10. however. The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method. HttpServlet only supports HTTP and HTTPS protocol. also read:EJB Interview Questions JSF-MyFaces Tag Reference JSF Tutorial iBatis an alternative to Hibernate Note: This class is known as generic Tibco Interview Questions  servlet.HttpServlet. sessions and setting response headers. GenericServlet is not specific to any protocol. cookies.servlet.What's the difference between GenericServlet and HttpServlet? GenericServlet The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods.GenericServlet and javax. more commonly by extending a class that implements it. All servlets implement this interface.What is the GenericServlet class? GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. Note: Most Servlets. and implements the log method declared in the  ServletContext interface. this class also provides simple versions of  the lifecycle methods init and destroy.What is Servlet interface? The central abstraction in the Servlet API is the Servlet interface. either directly or . In addition to the methods declared in these two interfaces. People who read this. The GenericServlet does not include protocol-specific methods for handling request parameters. since it is not specific to any protocol. . 11. HttpServlet An abstract class that simplifies writing HTTP servlets.9. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.servlet.http. namelyjavax.

This is a convenience implementation of the Servlet interface. You can perform common operations with the constructor as you normally do.What is the difference between doGet() and doPost()? # 1 doGet() In doGet() the parameters are appended to the URL and sent along with header information. 13.doPost is slower compared to doGet since doPost does not write the content length The amount of information you can send back 2 using a GET is restricted as URLs can only be 1024 characters. 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. so the constructor is also called by servlet container only.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do. 7 doGet() should be safe without any side effects for which user is held responsible This method does not need to be either safe It disallows bookmarks. 16.In the case of servlet.Even you can use the constrctor in servlet for initialization purpose.e.Can servlet have a constructor ? One can definitely have constructor in servlet. except mentioned in the following reason: . doPost() In doPost(). doGet() is a request for information. it does not 3 (or should not) change anything on the server.and it's not restricted to textual data either. servlet container is responsible for instantiating the servlet.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. (doGet() should be idempotent) 4 Parameters are not encrypted doGet() is faster if we set the response content 5 length since the same connection is used. It is possible to send files and even binary data such as serialized Java objects! doPost() provides information (such as placing an order for merchandise) that the server is expected to remember Parameters are encrypted doPost() is generally used to update or post some information to the server. there is no need to write adoPost() method too. HttpServlet only supports HTTP and HTTPS protocol.12. which means that developers do not need to implement all service methods.What are the types of protocols supported by HttpServlet ? It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. If your servlet is required to handle doGet() requests for example. 14. doget should Operations requested through POST can have side 6 be able to be repeated safely many times effects for which the user can be held accountable. 15.When to use doGet() and when doPost()? Always prefer to use GET (As because GET is faster than POST). Thus increasing the performance This method does not need to be idempotent. You can send much more information to the server this way . doGet() should be idempotent. 8 It allows bookmarks.but this type of approch is not so common. i. So.

For example. just support POST. A servlet should override the doXXX() method for the HTTP methods that servlet supports.How do I support both GET and POST from the same Servlet? The easy way is. if the HTTP request method is GET. Only override the appropriate doXXX() method. 17. response). Because HTTP service method check the request method and calls the appropriate handler method. 19. IOException { doPost(request. doGet() method is called by default.Should I override the service() method? We never override the service method. it is not necessary to override the service method itself. since the HTTP Servlets have already taken care of it . } 18.   If data is sensitive Data is greater than 1024 characters If your application don't need bookmarks.How the typical servlet code look like ? . The default service function invokes the doXXX() method corresponding to the method of the HTTP request. then have your doGet method call your doPost method: public void doGet(HttpServletRequest request. HttpServletResponse response) throws ServletException.

21.What's the difference between forward() and sendRedirect() methods? . 22. The param-value pairs for ServletConfig object are specified in the <init-param> within the <servlet> tags in the web. The server passes an object that implements the ServletConfig interface to the servlet's init() method.xml file.What are the differences between the ServletConfig interface and the ServletContext interface? ServletConfig The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. There is one ServletContext for the entire webapp and all the servlets in a webapp share it. Each Web application in a container has a single servlet context associated with it.xml file ServletContext A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container. There is one ServletConfig parameter per servlet.What is a servlet context object? A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. The param-value pairs for ServletContext object are specified in the <context-param> tags in the web.20.

processing some input and "boilerplate" text or template markup that may be deciding the outcome by returning a particular response included by many servlets. the included resource must not attempt to change the response status code or HTTP headers. but will rather fetch the second URL. also read:    Core Java Questions iBatis Tutorials PMP Certification iBatis an alternative to Hibernate . In other words. This method can be used to redirect users to resources that are not part of the current context. but the response is issued under the same URL that was originally requested. with all of its parameters and attributes are no longer available after a redirect. The forwarded resource may be another servlet. or even in the same domain. so its original URL remains intact. The browser. People who read this. the original request context is retained sendRedirect() A redirect is a two step process. not one. which differs from the original. A browser reloads of the second URL . Because this involves a new request. as if it were part of the was originally called. 23. calling servlet. is doing the work and knows that it's making a new request.What is the difference between the include() and forward() methods? include() forward() The RequestDispatcher include() method inserts the The RequestDispatcher forward() method is used to the contents of the specified resource directly in the show a different resource in place of the servlet that flow of the servlet response.forward() A forward is performed internally by the servlet. The forward() method is often used where a servlet is The include() method is often used to include common taking a controller role. any such request will be ignored. JSP or static HTML document. in this case. Any browser reload of the resulting page will simple repeat the original request. the previous request scope objects. If you include a servlet or JSP document. where the web application instructs the browser to fetch a second URL. redirect is marginally slower than a forward. with the original URL Both resources must be part of the same context (Some containers make provisions for cross-context communication but this tends not to be very portable) Since both resources are part of same context. (Variables will need to be passed by via the session object). since it requires two browser requests. Forward is marginally faster than redirect. it is not the same as a redirection.will not repeat the original request. The browser is completely unaware that it has taken place. page.

servlet. The JavaEE server reads the deployment descriptor at run time and acts upon the component accordingly.What is the difference between the getRequestDispatcher(String path) method of javax. The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects. 27.xml extension. It defines a component's deployment settings.ServletRequest interface and javax.What is the directory structure of a WAR file? 26.ServletContext interface? . 25.What's the use of the servlet wrapper Struts Interview Questions  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.What is a deployment descriptor? A deployment descriptor is an XML document with an . It declares transaction attributes and security authorization for an enterprise bean.servlet.24.

which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.servlet.What is Session Tracking? . The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.What is session? A session refers to all the requests 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. All path must start with a “/” and are interpreted as relative to current context root.servlet. which can be relative to the request of the calling servlet.ServletRequest. 29. 28. every user of an application has a separate session and has access to a separate set of session variables. This is called lazy loading.What is the <load-on-startup> element? The <load-on-startup> element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. it initializes a servlet when it receives a request for that servlet first time.getRequestDispatcher(String path) The getRequestDispatcher(String path) method ofjavax. 30. If the path begins with a “/” it is interpreted as relative to the current context root. It is also used to specify the order in which the files are to be loaded. 31. As a result.ServletContext interface cannot accept relative paths. ServletContext. The <load-on-startup> element is written in the deployment descriptor as follows: <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. The servlet specification defines the element.getRequestDispatcher(String path) The getRequestDispatcher(String path) method ofjavax.What is preinitialization of a servlet? A container does not initialize the servlets as soon as it starts up.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to.

This extra data identifies the session. every request is treated as new request.e. then checking out--each page request must somehow be associated with previous requests.What is the need of Session Tracking in web application? HTTP is a stateless protocol i.How do I use cookies to store session state on the client? In a servlet. . from within custom tag code. Such information which is part of the application is reffered as "state". and optional attributes.  Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL's support via HTTPS for generating a unique session key as part of the encrypted conversation. A cookie has a name. For web applications to be more realistic they have to retain information across multiple requests. Saved by the browser. The server can associate this session identifier with the data it has stored about that session. a single value. requests originating from the same browser) across some period of time.What are the types of Session Tracking ? Sessions need to work with all web browsers and take into account the users security preferences.Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is. 33. 32.service() can be used to create cookies on the client and use cookie information transmitted during client requests. the HttpServletResponse and HttpServletRequest objects passed to method HttpServlet.. Therefore there are a variety of ways to send and receive the identifier:  URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This method is used with browsers that do not support cookies or where the user has disabled the cookies.  Hidden Form Fields : Similar to URL rewriting. Typical example: Putting things one at a time into a shopping cart. When the client submits the form to the server the hidden fields identify the client. A cookie's value can uniquely identify a client. Learn more about Session Tracking 34. The server embeds new hidden fields in every dynamically generated form page for the client. in scriptlet code or. JSPs can also use cookies. preferably.  Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. and later sent back to the server in subsequent requests. To keep track of this state we need session tracking.

Cookie-based solutions work only for HTTP clients.) can be maintained easily with no server interaction.jsp. This extra data identifies the session. and a single cookie name may have multiple values. package javax. user data that needs to be stored longterm (such as a user ID.and medium-sized session data. the browser version may not support them. Servlets and JSP pages that rely exclusively on cookies for client-side session state will not operate properly for all clients. Browser instances share cookies. historical information. Cookies may not be available for many reasons: the user may have disabled them.What is URL rewriting? URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL. complicates development and maintenance. Corruption. Each time a URL is output. which encodes session ID in the URL if the browser isn't accepting cookies. Every URL on the page must be encoded using method HttpServletResponse. 37. and so on.http supports session management (via classHttpSession). especially when cookies are turned off.servlet. E.encodeURL(). so for low-security sites. so users cannot have multiple simultaneous sessions..g. which Hibernate Tutorial  is more difficult to implement than  SCWCD Certification some other approaches. Multiple cookies may be set for the same request. This is because cookies are a feature of the HTTP protocol. To get all of the cookies associated with a single HTTP request. the entire session data (instead of just the session ID) can be kept in the cookie. or if the session tracking is turned off. 36. Notice that the while package javax. inconsistent. use the addCookie() method in class HttpServletResponse.jsessionid=123465hfhs Advantages  URL rewriting works just about everywhere. http://abc/path/index. expiration or purging of cookie files can all result Hibernate Interview Questions  in incomplete.servlet has no such support. or missing information. and then switching to an alternate clientside session state strategy in cases where cookies aren't available.  To set a cookie on the client. use the getCookies() method of class HttpServletRequest 35. the browser may be behind a firewall that filters cookies. Using cookies. etc.What are some disadvantages of storing session state in cookies?  People who read this. also read:-      JDBC Interview Questions Cookies are controlled by programming a low-level API. the servlet passes the URL to encodeURL(). . For small. The server can associate this session identifier with the data it has stored about that session.What are some advantages of storing session state in cookies?   Cookies are usually persistent. All data for a session are kept on  iBatis an alternative to Hibernate the client.

This scheme isn't foolproof.e. Entirely static pages cannot be used with URL rewriting. 38. The syntax for setting the timeout programmatically is as follows: public void setMaxInactiveInterval(int interval) The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid. URL rewriting limits the client's interaction with the server to HTTP GETs. It is possible to combine static and dynamic content. This limitation is also a barrier to integrating legacy web pages with newer.How can an existing session be invalidated? An existing session can be invalidated in the following two ways:  Setting timeout in the deployment descriptor: This can be done by specifying timeout between the <session-timeout>tags as follows: <session-config> <session-timeout>10</session-timeout> </session-config> This will set the time for session timeout to be ten minutes.invalidate() method. using (for example) templating or server-side includes. i. since every link must be dynamically written with the session state.  Multiple simultaneous sessions are possible for a single user. session never expires. all of the URLs (and therefore all of the data for that session) are lost. which makes the container abonden the session on which the method is called. but it can greatly increase communication overhead. makes the container stop tracking session. since it's stored in URLs in each page being displayed. 39. though. Note :Setting the inactive period as negative(-1). Session information is local to each browser instance. since users can start a new browser instance using a URL for an active session. If a client workstation crashes. URL rewriting does not work well with JSP technology. DisAdvantages     Every URL on a page which needs the session information must be rewritten each time a page is served. which can result in awkward restrictions on the page. . Not only is this expensive computationally. servlet-based pages. and confuse the server by interacting with the same session through two instances.  Setting timeout programmatically: This will set the timeout for a specific session.How can the session in Servlet can be destroyed? An existing session can be destroyed in the following two ways:  Programatically : Using session.

44. a user is not required to recompile anything to change the input or output of the Web application. 40. The last servlet in the chain returns the output to the Web browser. Hence. It intercepts the response from the servlet back to the client and modifies the request if required.What is Servlet Chaining? Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet. This is called lazy loading. which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.What is servlet lazy loading?    A container doesnot initialize the servlets ass soon as it starts up.A client sends requests to two different web components. 42. 43. When the server itself is shutdown.e. There can be many filters forming a chain. .How are filters? Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. Sessions is specific to the client but not the web components. they end up with using same session . in which case the output of one filter becomes an input to the next filter. Will they end up using the same session object or different session ? Creates only one session i.What are the functions of an intercepting filter? The functions of an intercepting filter are as follows:    It intercepts the request from a client before it reaches the servlet and modifies the request if required. various modifications can be performed on a single request and response. Both of the components access the session.. It is used to abstract any useful information contained in the request or response. And there is a 1-1 mapping between client and a session. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet. 41. Hence. The servlet specification defines the <load-on-startup> element. and so on. Some of the important functions performed by filters are as follows:      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. it initializes a servlet when it receives a request for that servlet first time.

initialization. Declarative security : It manages the security inside the XML deployment descriptor file. When the Servlet service() method completes. . service. JSP support : The container is responsible for converting JSPs to servlets and for maintaining them. such as class loading. instantiation. Communication support : It handles the communication between the servlet and the Web server.45.What are the functions of the Servlet container? The functions of the Servlet container are as follows:      Lifecycle management : It manages the life and death of a servlet. and making servlet instances eligible for garbage collection. Multithreading support : It automatically creates a new thread for every servlet request received. the thread dies.