Wednesday 21 March 2007

Servlet Interview Questions 1-25

I would post a series of servlets questions in coming days, I think its very important for any guy to have a glance who is going for J2EE technical discussion. These set of questions would help you find out, if there are any grey areas left in your preparation. I would post the answers some time later, Till then try to find if you can answer them.
Here goes the first list.

Q1. Define the webapplication directory structure.
Ans:

Table 1. The Web Application Directory Structure

Directory

Contains

/MyApp

This is the root directory of the web application. All JSP, images, js and XHTML files are stored here or in its subdirectories. Files other than in WEB-INF can be directly accessed through URL or are the Universal scope files.

/MyApp/WEB-INF

This directory contains all resources related to the application This is where your web application deployment descriptor is located. Note that the WEB-INF directory is not in the public/universal scope. No files contained in this directory can be directly accessed from url/browsers.

/MyApp/WEB-INF/classes

This directory is where servlets, utility classes and packages are located.

/MyApp/WEB-INF/lib

This directory contains Java Archive files that the web application depends upon. For example, this is where you would place a JAR file that contained a JDBC driver.


Q2. What is web.xml and whats its purpose? Is it mandatory to have it in your web application?

Ans:
Web.xml is called the web application deployment descriptor. We define/configure
the web application related settings/configurations in this file. e.g. Servlet definitions
and configurations.

Q3. Can a web application have more than one web.xml?

Ans:
No, one webapplication have one web.xml in WEB-INF/

Q4. What is a war file?

Ans:
Archived form of a web application.

Q5. What is <welcome-file-list>?

Ans:
<welcome-file-list> element in web.xml configures the web application's entry point or welcome page.e.g. Following example defines the Home.jsp to be default home page of the application
<welcome-file-list>
<welcome-file>Home.jsp</welcome-file>
</welcome-file-list>

Q6. What is the difference between Webserver and Application Server?

Ans:
Webserver is capable of handling requests and responses over HTTP where as Application Server is capable of executing/serving the application logic of an application. So whenever there is runtime application logic execution is involved, this would be done by the application server. Some people think that if a server has EJB container only then its application server, Just think guys EJB container is just an another way of defining the application logic, If I am not using EJB does that mean I don't have application logic? Funny isn't it?

Q7. Tomcat is a pure web server? True | False or the question can be asked in number of ways also... Tomcat is also an application server True | False? Is tomcat s application server?

Ans:
Tomcat is not a pure Web server. It can also execute the application logics through servltes/Jsps so it's also an application server.


Q8. How do you define the servlet element and servlet-mapping element in web.xml file?
Ans:

The servlet element contains the declarative data of a servlet. The following table describes the elements you can define within a servlet element.

Element

Required?

Description


Required

Defines the canonical name of the servlet, used to reference the servlet definition elsewhere in the deployment descriptor.


Required

The fully-qualified class name of the servlet.


Optional

Contains a name/value pair as an initialization attribute of the servlet.

Use a separate set of tags for each attribute.


Optional

Server initializes this servlet when Server starts up. The optional content of this element must be a positive integer indicating the order in which the servlet should be loaded. Lower integers are loaded before higher integers. If no value is specified, or if the value specified is not a positive integer, Server can load the servlet in any order during application startup.

The servlet-mapping element defines a mapping between a servlet and a URL pattern.

Element

Required?

Description


Required

The name of the servlet to which you are mapping a URL pattern. This name corresponds to the name you assigned a servlet in a declaration tag.


Required

Describes a pattern used to resolve URLs. The portion of the URL after the http://host:port + WebAppName is compared to the by Server. If the patterns match, the servlet mapped in this element will be called.


Q9. If we call the destroy() from service(), does that mean the servlet would be destroyed?

Ans: No, Its just like a any other method call from within service(). However your Servlet
may not function as expected if we do this.

Q10. doGet () and doPost () are overridden from HttpServlet true | false?

Ans:
True.

Q11. If the same URL point to 2 servlets which one would be called? OR both would be called? Tell me the order?

Ans: Only one Servlet would be called. The servlet which is mapped last would be called.

Q12. Is it mandatory that servlet should have default argument constructor, why?

Ans:
Yes, because container uses that to instantiate a servlet.

Q13. If you can define servlet constructor then why would you override init() method?

Ans:
You can not access the ServletContext and ServletConfig objects within the constructor. If you need some init parameter and some context parameter, you need to override init.

Q14. What is singlethread model in servlets?

Ans: Single thread model enables one request at a time to execute the servlet. It's up to the servlet container, which strategy it would use to do so. E.g. container can make one servlet instance per request or it can synchronize the access to service method. Whichever strategy the server follows, We simply do this by implementing the SingleThreadModel interface to our Servlet.

Q15. Can you synchronize the service() method?

Ans:
Yes we can.

Q16. If you can synchronize the service() method then would you do that or implement single thread model? Why?

Ans: Implement single thread model, this would help us to achieve the most optimum approach doing this the servlet container way.

Q17. Are servlets multi-threaded?

Ans:
Yes, Servlets are multithreaded. Each request executes the service method of the same instance.

Q18. Why we use SingleThreadedModel then if servlets are multi-threaded?

Ans: If the servlets have thread safety issues, because of some instance level variables/shared objects being used and updated by the parallel requests, we would use the single thread model to achieve the thread safety across multiple parallel requests.

Q19. We always say that request executes the service() method of servlet, however we always implement doGet() or doPost(). Then how do these methods get called?

Ans:
The container always invokes the service() method of a servlet.
depending upon the request method doGet or doPost are called from within service() method.

Q20. Difference between Get and Post

Ans:
Get request is throught URL the parametes are passed in a query string,
the URL size can not exceed 1K whereas there is no such limitation on POST.
Default request method is GET. There is no difference between the 2 in terms of performance.


Q21. What are init parameters? Where do you define them?
Ans: Init parameters are used to pass default initializations/configurations values to the servlet.
e.g. you may want to pass the database username and password information to a servlet or a file name and path etc.
We define them in web.xml. They are of 2 types. Servlet Init Parameters and context parameters. Servlet Init Parameters are available only to the servlet for which they have been defined.context init paramters are available to all the servlets.
If we want to use the same set of parmeters for 2 or more servlets we define them as context init parameters.


Q22. What if I give the same name to 2 init parameters would this be error?

Ans:
No this is not an error, we would get the value of the init parameter defined last in the order.

Q23. How would you fetch init parameters in servlets?

Ans: We fetch the Servlet specific init parameters through ServletConfig.getInitParameter(String paramname) and context init paramters through ServletContext.getInitParameter(String paramname)
The init parameter name should be unique in the Servlets. If 2 init parameter names are not unique, the servlet would pick the value of the init parameter defined last in web.xml.

Q24. Can I fetch Init parameters in servlet constructor?

Ans:
No, we don't have the Servlet config reference in servlet constructor.

Q25. What is servlets pre-initialization?

Ans:
Before any request can hit the service method, We may require some setup/initializations in the servlet. e.g. you may want to open the database connection, some datafile or load some cache before the servlet is ready for request handling. To do this we override the init() method of the servlet. The servlet container would call the init before the servlet go into service ready state.
By default the servlet life cycle kicks in when first request is recieved by the servlet, Servlet instantiates and then init is called. untill init is not successfull, each request for the servlet will have to wait.
You may want to intialize the servlet as soon as the webapplication starts or the servle container starts, This can be done if we define the <load-on-startup> for <servlet> in web.xml.
Preinitializing the servlet along with the container is called servlet the pre-intialization.

My Favourite Books :

Core Java: Programmer's Guide to Java Certification : A Comprehensive Primer (Second Edition) by Mughal and Rasmussen

I am very big fan of this book, this is a must have book if you want to explore the core of java in detail.

I recently discovered that the Authors are coming up with their next book called Java Actually : A first course in programming

Table of Contents can been seen at http://www.ii.uib.no/~khalid/jact/toc.html
The TOC looks very good.

Servlets: Java Servlet Programming by Jason Hunter and Head First Servlets & JSP are my all time favourite for servlets.


0 comments: