Servlet Interview Question Answers

Q1: What is different between web server and application server?

Following are some of the key differences in features of Web Server and Application Server-
Web Server is designed to serve HTTP Content. App Server can also serve HTTP Content but is not limited to just HTTP. It can be provided other protocol support such as RMI/RPC.
Web Server is mostly designed to serve static content, though most Web Servers have plugins to support scripting languages like Perl, PHP, ASP, JSP etc. through which these servers can generate dynamic HTTP content.
Most of the application servers have Web Server as integral part of them, that means App Server can do whatever Web Server is capable of. Additionally App Server have components and features to support Application level services such as Connection Pooling, Object Pooling, Transaction Support, Messaging services etc.
As web servers are well suited for static content and app servers for dynamic content, most of the production environments have web server acting as reverse proxy to app server. That means while service a page request, static contents such as images/Static html is served by web server that interprets the request. Using some kind of filtering technique (mostly extension of requested resource) web server identifies dynamic content request and transparently forwards to app server.
Example of such configuration is Apache HTTP Server and BEA WebLogic Server. Apache HTTP Server is Web Server and BEA WebLogic is Application Server.

Q2: 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.
HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.

Q3: What is the difference between GET and POST method?

Get: Parameters remain in browser history because they are part of the URL
Can be bookmarked.
GET requests are re-executed but may not be re-submitted to server if the HTML is stored in the browser cache.
GET is less secure
Post:Parameters are not saved in browser history.
Can not be bookmarked.
The browser usually alerts the user that data will need to be re-submitted.
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs.

Q4: What is a web application?

Combination of server side and client side scripts.It runs on server to provide both static and dynamic content.Java Web Applications are packaged as Web Archive (WAR)

Q5: What is a servlet?

Servlets are small,Platform independent server side component which is used to extend the functionality of web server.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.

Q6: What are the advantages of Servlet over CGI?

Servlets provide better performance that CGI in terms of processing time, memory utilization because servlets uses benefits of multithreading.
Servlets are platform and system independent, the web application developed with Servlet can be run on any standard web container such as Tomcat, JBoss, Glassfish servers
Servlets are robust because container takes care of life cycle of servlet.

Q7: 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.

Q8: What are common tasks performed by Servlet Container?

Communication Support: Servlet Container provides easy way of communication between web client (Browsers) and the servlets and JSPs.
Lifecycle and Resource Management: Servlet Container takes care of managing the life cycle of servlet
Multithreading Support: Container creates new thread for every request to the servlet and provide them request and response objects to process
JSP Support: JSPs doesn’t look like normal java classes but every JSP in the application is compiled by container and converted to Servlet and then container manages them like other servlets.
Miscellaneous Task: Servlet container manages the resource pool, perform memory optimizations, execute garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.

Q9: What is the life cycle of servlet?

Life cycle of Servlet:
Servlet class loading
Servlet instantiation
Initialization (call the init method)
Request handling (call the service method)
Removal from service (call the destroy method)

Q10: What is ServletConfig object?

ServletConfig as the name implies provide the information about configuration of a servlet which is defined inside the web.xml file.Its a specific object for each servlet.

Q11: What is ServletContext object?

ServletContext is application specific object which is shared by all the servlet belongs to one application in one JVM .It is single object which represents application and all the servlets access application specific data using this object.

Q12: How can we create deadlock condition on our servlet?

one simple way to call doPost() method inside doGet() and doGet()method inside doPost() it will create deadlock situation for a servlet.

Q13: What is difference between ServletConfig and ServletContext?

Signature: public interface ServletConfig
ServletConfig is implemented by the servlet container to initialize a single servlet using init().
In web.xml – <init-param> tag will be appear under <servlet-class> tag
Signature: public interface ServletContext
ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container
In web.xml – <context-param> tag will be appear under <web-app> tag

Q14: What is Request Dispatcher?

A RequestDispatcher object can forward a client's request to a resource or include the resource itself in the response back to the client. A resource can be another servlet, or an HTML file, or a JSP file, etc.
For constructing a RequestDispatcher object, you can use either the ServletRequest.getRequestDispatcher()(Path can be relative) method or the ServletContext.getRequestDispatcher()(pathname must begin with '/') method.

Q15: What if we override the init(ServletConfig) and don't call super(ServletConfig)?

If you override init(ServletConfig) method and don't call super(servletConfig) then the ServletConfig reference is not stored in the GenericServlet and if we call getServletConfig() we get null.
Another method GenericServlet.init() is provided as a convenience. GenericServlet.init(ServletConfig) internally calls GenericServlet.init(). If you want to add functionality at init-time, you should do it by overriding init(). The default implementation of init(ServletConfig) will save the ServletConfig reference and then call your overriding init().

Q16: 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.

Q17: What is SingleThreadModel interface?

SingleThreadModel interface was provided for thread safety and it guarantees that no two threads will execute concurrently in the servlet’s service method.

Q18: How can we invoke another servlet in a different application?

We can use ServletResponse sendRedirect() method and provide complete URL of another servlet. This sends the response to client with response code as 302 to forward the request to another URL

Q19: What are different methods of session management in servlets?

Some of the common ways of session management in servlets are:
User Authentication
HTML Hidden Field
Cookies
URL Rewriting
Session Management API

Q20: Why do we have servlet filters?

Filter is a component which dynamically intercepts request and response to transform or use information contained in request and responses.It runs on server before the servlet with which it is associated.
Some common tasks that we can do with filters are:
Logging request parameters to log files.
Authentication and autherization of request for resources.
Formatting of request body or header before sending it to servlet.
Compressing the response data sent to the client.
Alter response by adding some cookies, header information etc.

Q21: What is difference between GenericServlet and HttpServlet?

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

Q22: What is the difference between forward () and sendRedirect ()?

Difference is:
A forward is performed internally by the servlet. A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
Browser is completely unaware that it has taken place, so its original URL remains intact. But in sendRedirect, the browser, in this case, is doing the work and knows that it's making a new request.

Q23: What is the inter-servlet communication?

It can be done using request dispatcher to pass the request from one servlet to other(servlet/jsp/html etc). Data among servlets acn be shared using attributes set in request objects.

Q24: Why not declare a constructor in servlet?

You can declare constructor but constructors for dynamically loaded Java classes such as servlets cannot accept arguments.Therefore init() is used to initialize by passing the implemented object of ServletConfig interface and other needed parameters.

Q25: Are Servlets Thread Safe? How to achieve thread safety in servlets?

HttpServlet init() method and destroy() method are called only once in servlet life cycle, so no problem in their synchronization. But service methods such as doGet() or doPost() are getting called in every client request and since servlet uses multithreading, we should provide thread safety in these methods.
And doGet/doPost is also specific to a servlet thread but if we are using and sharable resource then thread safety is required using synchronization.

Q26: What is servlet attributes and their scope?

Attributes are used to do inter servlet communication. Scope can be request, session and application scope.

Q27: What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?

The forward method of RequestDispatcher will forward the ServletRequest and ServletResponse that it is passed to the path that was specified in getRequestDispatcher(String path). Response will not be sent back to the client and so the client will not know about this change of resource on the server.
The sendRedirect(String path) method of HttpServletResponse will tell the client that it should send a request to the specified path. So the client will build a new request and submit it to the server, because a new request is being submitted all previous parameters stored in the request will be unavailable. The client's history will be updated so the forward and back buttons will work. This method is useful for redirecting to pages on other servers and domains.

Q28: Why HttpServlet class is declared abstract?

It's because it follows the Template Method design pattern. The doXxx() methods have all default behaviours of returning a HTTP 405 Method Not Implemented error. If those methods were all abstract, you would be forced to override them all, even though your business requirements don't need it at all. It would only result in boilerplate code and unspecified/unintuitive behaviour.

Q29: What is URL Encoding?

URL Encoding is the process of converting string into valid URL format. Valid URL format means that the URL contains only what is termed "alpha | digit | safe | extra | escape" characters.
URL encoding is normally performed to convert data passed via html forms, because such data may contain special character, such as "/", ".", "#", and so on, which could either: a) have special meanings; or b) is not a valid character for an URL; or c) could be altered during transfer.

Q30: 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.

Q31: What is the difference between encodeRedirectUrl and encodeURL?

encodeURL() is used for all URLs in a servlet's output. It helps session ids to be encoded with the URL.
encodeRedirectURL() is used with res.sendRedirect only. It is also used for encoding session ids with URL but only while redirecting.

Q32: How to handle exceptions thrown by application with another servlet?

You canuse the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes.
In web.xml
<error-page>
<error-code>404</error-code>
<location>/ErrorHandler</location>
</error-page>

OR

<error-page>
<exception-type>
javax.servlet.ServletException
</exception-type >
<location>/ErrorHandler</location>
</error-page>

Q33: What is a deployment descriptor?

It is a web.xml file in your web application project which specifies the application components like servlets,security constraints,welcome file,session timeout,listeners,error page mapping etc.

Q34: How to make sure a servlet is loaded at the application startup?

We can use below tag in servlet tag in web.xml
<load-on-startup>5</load-on-startup>
The load-on-startup value should be int, if it's negative integer then servlet container will load the servlet based on client requests and requirement but if it's 0 or positive, then container will load it on application startup.
If there are multiple servlets with load-on-startup value such as 0,1,2,3 then lower integer value servlet will be loaded first.

Q35: How to get the actual path of servlet in server?

We can use below method to get the actual path of the servlet in file system.
getServletContext().getRealPath(request.getServletPath())

Q36: How to get the server information in a servlet?

We can use below method to get the servlet information in a servlet through servlet context object.
getServletContext().getServerInfo()

Q37: How to get the IP address of client in servlet?

We can use request.getRemoteAddr() to get the client IP address in servlet.