Servlet - Interview FAQ's for Experience to tackle tricky questions
What is different between web server and application server?
A web server responsibility is to handler HTTP requests from client browsers and respond with HTML response. A web server understands HTTP language and runs on HTTP protocol.Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat.
Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications.
What is the use of servlet?
Processing and storing data submitted by an HTML form.Providing dynamic content.
A Servlet can handle multiple request concurrently and be used to develop high performance system
Managing state information on top of the stateless HTTP.
What is the life cycle of servlet?
Servlet class loadingServlet instantiation
Initialization (call the init method)
Request handling (call the service method)
Removal from service (call the destroy method)
What is the difference between GenericServlet and HttpServlet?
The difference is:The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods. But HttpServlet extends the GenericServlet base class and provides a 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.
What are the new features added to Servlet 2.5?
A new dependency on J2SE 5.0Support for annotations
Loading the class
Several web.xml conveniences
A handful of removed restrictions
Some edge case clarifications
How a Servlet is unloaded?
A servlet is unloaded when:Server shuts down.
Administrator manually unloads.
What are the functions of Servlet container?
a.) Lifecycle management - Managing the lifecycle events of a servlet lik class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.b.) Communication support : Handling the communication between servlet and Web server.
c.) Multithreading support : Automatically creating a new thread for every servlet request and finishing it when the Servlet service() method is over.
d.) Declarative security : Managing the security inside the XML deployment descriptor file.
e.) JSP support : Converting JSPs to servlets and maintaining them.
What is Servlet Chaining?
- It is a method in which the output of one servlet is piped into the next servlet.- It is the last servlet in the chain that provides the output to the Web browser.
Why is HttpServlet declared abstract?
- The default implementations of the main service methods do not do anything and need to be overridden. This calls of the HttpServlet class to be declared as abstract.-With its use the developers do not need to implement all the service methods.
When should you prefer to use doGet() over doPost()?
GET is preferred over POST in most of the situations except for the following:- When the data is sensitive.
- When the data is greater than 1024 characters
What are the types of Session Tracking ?
a.) URL rewriting: In this method of session tracking, some extra data is appended at the end of the URL, which identifies the session. This methodis used for those browsers which do not support cookies or when the cookies are disabled by the user.
b.) Hidden Form Fields: This method is similar to URL rewriting. New hidden fields are embedded by the server in every dynamically generated form
page for the client. When the form is submitted to the server the hidden fields identify the client.
c.) Cookies: Cookie refers to the small amount of information sent by a servlet to a Web browser. Browser saves this information and sends it back to the server when requested next. Its value helps in uniquely identifying a client.
d.) Secure Socket Layer (SSL) Sessions
What are the disadvantages of storing session state in cookies?
- Using a cookie, all the session data is stored with the client. If the cookies at client side get corrupt, purged or expired, the information received won't be complete.- Some user may disable the cookies or their browser might not support them. Some users might have a firewall filtering out the cookies. So, you may either not receive the information or trying to switch to an alternate means may cause complexity.
- Cookie based solutions work only for HTTP clients.
- A low-level API controls the cookies. It is quite difficult to implement them.
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.Why super.init (config) wiil be the first statement inside init(config) method.
This will be the first statement if we are overriding the init(config ) method by this way we will store the config object for future reference and we can use by getServletConfig () to get information about config object if will not do this config object will be lost and we have only one way to get config object because servlet pass config object only in init method . Without doing this if we call the servletConfig method will get NullPointerException.
Can we call destroy() method inside the init() method is yes what will happen?
Yes we can call like this but if we have not override this method container will call the default method and nothing will happen.after calling this if any we have override the method then the code written inside is executed.How can you get the information about one servlet context in another servlet?
In context object we can set the attribute which we want on another servlet and we can get that attribute using their name on another servlet.Context.setAttribute (“name”,” value”)
Context.getAttribute (“name”)
what is servlet collaboration?
1. RequestDispatchers include () and forward() method .2. Using sendRedirect()method of Response object.
3. Using servlet Context methods
What is the difference between ServletConfig and ServletContext?
ServletConfig as the name implies provide the information about configuration of a servlet which is defined inside the web.xml file or we can say deployment descriptor.its a specific object for each servlet.ServletContext is application specific object which is shared by all the servlet belongs to one application in one JVM .this is single object which represent our application and all the servlet access application specific data using this object.servlet also use their method to communicate with container.
What are the important functions of filters?
Security checkModifying the request or response
Data compression
Logging and auditing
Response compression
What's 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 behaviour is to pass all method calls directly to the underlying objects.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. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session.Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.
E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
Advantages
URL rewriting works just about everywhere, especially when cookies are turned off.Multiple simultaneous sessions are possible for a single user. Session information is local to each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't foolproof, though, since users can start a new browser instance using a URL for an active session, and confuse the server by interacting with the same session through two instances.
Entirely static pages cannot be used with URL rewriting, since every link must be dynamically written with the session state. It is possible to combine static and dynamic content, using (for example) templating or server-side includes. This limitation is also a barrier to integrating legacy web pages with newer, servlet-based pages.
DisAdvantages
Every URL on a page which needs the session information must be rewritten each time a page is served. Not only is this expensive computationally, but it can greatly increase communication overhead.URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in awkward restrictions on the page.
URL rewriting does not work well with JSP technology.
If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are lost.
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.
It intercepts the response from the servlet back to the client and modifies the request if required.
There can be many filters forming a chain, in which case the output of one filter becomes an input to the next filter. Hence, various modifications can be performed on a single request and response.
Which HTTP method is non-idempotent?
A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.For example, to access an HTML page or image, we should use GET because it will always return the same object but if we have to save customer information to database, we should use POST method. Idempotent methods are also known as safe methods and we don’t care about the repetitive request from the client for safe methods.
What is MIME Type?
The “Content-Type” response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.We can use ServletContext getMimeType() method to get the correct MIME type of the file and use it to set the response content type. It’s very useful in downloading file through servlet from server.
What is difference between PrintWriter and ServletOutputStream?
PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.
How can we create deadlock situation in servlet?
We can create deadlock in servlet by making a loop of method invocation, just call doPost() method from doGet() method and doGet() method to doPost() method to create deadlock situation in servlet.What are different ways for servlet authentication?
HTTP Basic AuthenticationHTTP Digest Authentication
HTTPS Authentication
Form Based Login: A standard HTML form for authentication, advantage is that we can change the login page layout as our application requirements rather than using HTTP built-in login mechanisms.