JAVATECH NEWS

Java

CORE JAVA

Interview

OFF-CAMPUS

Saturday 3 January 2015

Servlet interview Questions


Servlet is very important topic in Java EE. In Interview interviewer prefer to ask some questions from Servlet. Here I am providing some most frequently asked Servlet questions which will help you to answer the Servlet related Questions in interview. Here Answers are kept simple and Straight forward to understand easily.


1. What is servlet?

Ans: 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.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.

2. What is the difference between an Applet and a Servlet?

a. An Applet is a client side java program that runs within a Web browser on the client machine. but Servlet is a server side component which runs on the web server.
b. An applet can use the user interface classes like AWT or Swing, Applet Life Cycle Methods: init(),paint(),start(),stop(),destroy().but The servlet does not have a user interface. Servlet Methods: doGet(), doPost() .
c. Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers. but Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server.

3.What are the advantages of servlet over CGI?

Ans:Advantages of servlet over CGI are-

a. Platform Independence:Servlet are plateform independent. Servlets can run on any operating system if  JVM is installed.But in case of CGI we have to recompile the program if we change the Operating system.
b. Performance:Servlet runs on JVM and gives more performance than the CGI because it creates  it creates a thread for each request not PROCESS where CGI starts a process for each request.
c. Extensibility:Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets take all these advantages and can be extended from existing class to provide the ideal solutions.
d. Safety:Java provides very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension.
eSecurity:Since servlets are server side Components, it inherits the security of server.Servlets are also benefited with java security manager, provided by web server.

4. What is the life cycle of servlet?

Ans-The life cycle of a servlet is controlled by the container in which the servlet has been deployed.
Life cycle of  a Servlet contains:
a. Loading  the servlet class.
b. Creating an instance of the servlet class.
c. Initialization of servlet instance by calling the init() method.
d. Invoking  the service() method
e. Calling  the destroy() method.

5. Why servlet are used?

Ans-Servlet are used to-
a. Process or store data that was submitted from an HTML form.
b. Provide dynamic content such as results of a database query.
c. Manage state information that does not exist in the stateless HTTP protocol, such as filling the articles into the shopping cart of the appropriate customer.


6. Difference between a Web Server, Web Container, and an Application Server?

Ans-A Web Server is a server capable of receiving HTTP requests from client or web browser,  interprete them, process the corresponding HTTP Responses and send them to the appropriate clients or Web Browsers. A web server understands HTTP language and runs on HTTP protocol only. Example: Apache Web Server.
Web container (also known as a Servlet container) is the component of a web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.Eg of web container is Tomcat.

An Application Server is a complete web server which provides an environment for running the business components like EJBs, ADF BCs, etc. Application server are more heavy than web server in terms of resource utilization. Eg of Application server are- Bea WebLogic, IBM WebSphere, Oracle Application Server, etc.

7. Why do we need constructor in servlet if we already have the init () method?

Ans-Even though there is an init() method in a servlet which gets called to initialize servlet, a constructor is still required to instantiate the servlet. it cannot be called explicitly using the ‘new’ keyword. This is implicitly handled by the servlet container. Thus, the container performs initialization as well as constructor functions.

8. How servlet is loaded?

Ans: The servlet is loaded
a. When First request is made.
b. Server starts up (auto-load).
c. There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
d. Administrator manually loads.

9. What is the pre initialization of servlet?

Ans-The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or pre initializing a servlet.

10.what is servlet lazy loading?

Ans- A container does not initialize the servlets as soon as it starts up; it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.

11. What is the <load-on-startup> element?

Ans-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 is also used to specify the order in which the files are to be loaded.

12.How a Servlet is unloaded?

Ans- Servlet is unloaded when:
a. Server shuts down.
b. Administrator manually unloads.

13. What is servlet interface?

Ans- The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or more commonly by extending a class that implements it.

14. What is the generic servlet class?

Ans- GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init() and destroy(), and implements the log method declared in the ServletContext interface.
Since this class is not specific to any protocol, it is known as generic servlet class.

15. Explain why HttpServlet is declared abstract?

Ans-The Constructor HttpServlet() does nothing because this is an abstract class. Default implementations in a few Java classes like HttpServlet don’t really do anything. Hence, they need to be overridden.
Usually one of the following methods of HttpServlet must be overridden by the subclass:
a. doGet, if the servlet supports HTTP GET requests
b. doPost, HTTP POST requests
c. doPut, HTTP PUT requests
d. doDelete, HTTP DELETE requests
e. init and destroy, to manage resources
f. getServletInfo, to provide information.

16.What are the difference between Generic Servlet and HttpServlet?

Ans-Difference between Generic Servlet and HttpServlet

a. HttpServlet is a protocol dependent whereas GenericServlet is protocol independent. So GenericServlet can handle all types of protocols, but HttpServlet handle only HTTP specific protocols.
b. GenericServlet belongs to javax.servlet package. HttpServlet belongs to javax.servlet.http package
c. GenericServlet is an abstract class which extends Object and implements Servlet, ServletConfig and java.io.Serializable interfaces. HttpServlet is an abstract class which extends GenericServlet and implements java.io.Serializable interface.
d. GenericServlet supports only service() method does not contain doGet() and doPost() methods. HttpServlet support also doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).

17. What are the type of protocols supported by the HttpServlet?

Ans-HttpServlet extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So,HttpServlet supports only two protocol.One is HTTP another is HTTPS protocol.

18.What do you mean by idempotent(safe) method?

Ans- Idempotent(safe):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.
Non-idempotent: A HTTP method is said to be non-idempotent if it returns the different result every time. HTTP method POST is non-idempotent method

19.What is the difference between the doGet () and doPost ()? 

Ans-difference between the doGet () and doPost are-

a.In doGet() Method the parameters are appended to the URL and sent along with header information but In doPost() method parameters are sent in separate line in the body.
b. doGet() is when you want to get something from the server , doPost() is to post data to the server.
c.In doGet() size of the header should not exceed 1024 bytes. but  doPost() does not have this constraint.
d. doGet() shall be used when small amount of data and insensitive data like a query has to be sent as a request. But doPost() shall be used when comparatively large amount of sensitive data has to be sent. Examples are sending data after filling up a form or sending login id and password.
e .doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance DoPost() is slower compared to doGet() since doPost does not write the content length.

20. When to use doGet() and when to use doPost()?

Ans-Always prefer to use doGet()  Because doGet() is faster than doPost().
But use doPost() when-
a.Data is sensitive.
b.Data is greater than 1024 characters.
c.If your application don't need bookmarks.

21. Should we override the service () method?

Ans-we are not supposed to override the service method, Because in http servlet class,the abstart service method of generic servlet class implemented along with two more concrete methods i.e;doGet and do Post,So when we define servlet class that extends http servlet then we can override either dopost() or doget() or both. For example, doGet() method for get requests.doPost() method is for post requests of HTML.

22.What is the ServletContext?

Ans-ServletContext. 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. There is one context per "web application" per Java Virtual Machine.

23.What is MIME Type?

Ans-MIME stands for Multi-purpose Internet Mail Extensions.The “Content-Type” response header is known as MIME Type. The Content-Type header field is used to specify the nature of the data in the body of an entity, by giving type and subtype identifiers. Type and a subtype separated by a slash (/). For example, the MIME type for Microsoft Word files is application and the subtype is msword. Together, the complete MIME type is application/msword. Some of the mostly used mime types are text/html, text/xml, application/xml etc.

24.What is the difference between the ServletConfig and ServletContext interface?

Ans- ServletConfig and ServletContext  both are interface in the package javax.servlet

a.Servlet config object represent single servlet but ServletContext represent whole web application running on particular JVM and it is common for all the servlets.
b. ServletConfig like local parameter associated with particular servlet only but ServletContext  is like global parameter associated with whole application.
c.The ServletConfig is a servlet configuration object which is implemented by the servlet container in order to pass configuration information to a servlet during initialization.
But A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
d. getServletConfig() method is used to get the config object and getServletContext() method is  used to get the context object.

25.What is Request Dispatcher?

Ans-Request Dispatcher is used for inter-servlet communication in the same context which perform mainly two operation. One is- it is used to forward the REQUEST to another resource that may be HTML, JSP or another servlet in same application. Another is- this is used to include the content of another resource to the response..
The RequestDispatcher interface provides two methods. They are:

a.public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

b.public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.

26.What is the difference between forward () and sendRedirect()?

a. we are not able to see the forwarded address in case of forward() method, its is transparent but In case of sendRedirect() method in address bar we are able to see the new redirected address,it’s not transparent
b.In forward method REQUEST is transfer to other resource within the same server for further processing and Web container handle all process internally and client or browser is not involved.
But in sendRedirect REQUEST is transfer to another resource to different domain or different server for futher processing and client or browser is involved.
c. Using forward () method is faster then send redirect. sendRedirect() is slower.

27.What is the difference between forward() and include()?

Ans-The RequestDispatcher include() method inserts the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet.
The RequestDispatcher forward() method is used to show a different resource in place of the servlet that was originally called.

28. What is the use of servlet wrapper classes?

Ans:Servlet HTTP API provides two wrapper classes- HttpServletRequestWrapper and HttpServletResponseWrapper.The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. We can extend these classes and override only specific methods we need to implement for custom request and response objects. These classes are not used in normal servlet programming.

29.What are common tasks performed by Servlet Container?

Ans-Servlet containers are also known as web container, for example Tomcat. Some of the important tasks of servlet container are:
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. Servlet Container loads servlets into memory, initialize servlets, invoke servlet methods and destroy them.
Multi-threading Support: Container creates new thread for every request to the servlet and provide them request and response objects to process. So servlets are not initialized for each request and saves time and memory.
JSP Support: JSP compiled by container and converted to Servlet and then container manages them like other servlets.
Other 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.

30. What is a deployment descriptor?

Ans- Deployment Descriptor is a XML document with .xml extension.
It basically describes the deployment settings of an application or module or the component.
At runtime J2EE server reads the deployment descriptor and understands it and then acts upon the component or module based the information mentioned in descriptor.


No comments:

Post a Comment

Designed By Blogger Templates