Thursday, October 10, 2013

Servlet Q&A

Questions : 1
What is Servlet?
Answers : 1
Servlet is small program which execute on the server. The environment exploiting the functionalities of the web server.More


Questions : 2
What are advantages of servlets over CGI?
Answers : 2
In CGI for every request there is a new process started which is quiet an overhead. In servlets JVM stays running and handles each request using a light weight thread. In CGI if there are 5000 request then 5000 CGI program is loaded in memory while in servlets there are 5000 thread and only one copy of the servlet class.


Questions : 3
What is Servlet life cycle?
Answers : 3
There are three methods which are very important in servlet life cycle those one init(), service() and destroy(). Server invokes "init ()" method when servlet is first loaded in to the web server memory. Servlet reads HTTP data provided in HTTP request in the "service ()" method. Once initialized servlet remains in memory to process subsequent request. So for every HTTP request "service ()" method of the servlet is called. Finally when server unloads the "servlet ()" from the memory it calls the "destroy" method which can be used to clean up any resource the servlet is consuming.


Questions : 4
What are the two important API’s in for Servlets?
Answers : 4
Two important packages are required to build servlet "javax.servlet" and javax.servlet.http". They form the core of Servlet API. Servlets are not part of core Java but are standard extensions provided by Tomcat.


Questions : 5
Can you explain in detail “javax.servlet” package?
Answers : 5
javax.servlet package has interfaces and classes which define a framework in which servlets can operate. Let’s first make a walk through of all the interfaces and methods and its description.
Interfaces in javax.servlet :-
Servlet Interface This interface has the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. Following are the method in Servlet interface :- void destroy( ):- Executed when servlet is unloaded from the web server memory. ServletConfig getServletConfig() :- Returns back a ServletConfig object that contains initialization data. String getServletInfo( ):- Returns a string describing the servlet. init method :- Called for first time when the servlet is initialized by the web server. void service() method :- Called to process a request from a client. ServletConfig Interface This interface is implemented by the servlet container. Servlet can access any configuration data when its loaded. The methods declared by this interface are summarized here: Following are the methods in ServletConfig interface:- ServletContext getServletContext():- Gives the servlet context. String getInitParameter(String param):- Returns the value of the initialization parameter named param. Enumeration getInitParameterNames() :- Returns an enumeration of all initialization parameter names.
String getServletName( ) :- Returns the name of the invoking servlet. .


Questions : 6
What’s the use of ServletContext?
Answers : 6
ServletContext Interface
It gives information about the environment. It represents a Servlet's view of the Web Application.Using this interface servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an application scope for binding objects.


Questions : 7
What's the difference between GenericServlet and HttpServlet?
Answers : 7
HttpServlet class extends GenericServlet class which is an abstract class to provide HTTP protocol-specific functionalities. Most of the java application developers extend HttpServlet class as it provides more HTTP protocol-specific functionalities. You can see in HttpServlet class doGet (), doPOst () methods which are more targeted towards HTTP protocol specific functionalities. For instance we can inherit from GenericServlet class to make something like MobileServlet. So GenericServlet class should be used when we want to write protocol specific implementation which is not available. But when we know we are making an internet application where HTTP is the major protocol its better to use HttpServlet.


Questions : 8
What’s the architecture of a Servlet package?
Answers : 8
At the top of all is the main servlet interface which is implemented by the generic servlet. But generic servlet does not provide implementation specific to any protocol. HTTP servlet further inherits from the generic servlet and provides HTTP implementation like “Get” and “Post”. Finally comes our custom servlet which inherits from HTTP Servlet.


Questions : 9
Why is HTTP protocol called as a stateless protocol?
Answers : 9
A protocol is stateless if it can remember difference between one client request and the other. HTTP is a stateless protocol because each request is executed independently without any knowledge of the requests that came before it.


Questions : 10
What are the different ways we can maintain state between requests?
Answers : 10
Following are the different ways of maintaining state’s between stateless requests:-
>>URL rewriting
>> Cookies
>>Hidden fields
>> Sessions


Questions : 11
What is URL rewriting?
Answers : 11
It’s based on the concept of attaching a unique ID (which is generated by the server) in the URL of response from the server. So the server attaches this unique ID in each URL.


Questions : 12
) What are cookies?
Answers : 12
Cookies are piece of data which are stored at the client’s browser to track information regarding the user usage and habits. Servlets sends cookies to the browser client using the HTTP response headers. When client gets the cookie information it’s stored by the browser in the client’s hard disk. Similarly client returns the cookie information using the HTTP request headers.


Questions : 13
What are sessions in Servlets?
Answers : 13
Session's can be considered as a series of related interactions between client and the server that take place over a period of time. Because HTTP is a stateless protocol these series of interactions are difficult to track. That’s where we can use HttpSession object to save in between of these interactions so that server can co-relate between interactions between clients.


Questions : 14
Which are the different ways you can communicate between servlets?
Answers : 14
Below are the different ways of communicating between servlets:-
>> Using RequestDispatcher object.
>> Sharing resource using “ServletContext ()” object.
>> Include response of the resource in the response of the servlet.
>> Calling public methods of the resource.
>> Servlet chaining.


Questions : 15
How do we share data using “getServletContext ()?
Answers : 15
Using the “getServletContext ()” we can make data available at application level. So servlets which lie in the same application can get the data. Below are important snippets which you will need to add, get and remove data which can be shared across servlets. Figure 4.10 : - Sharing data using “getServletContext ()” You can see in Step1 how “getServletContext().setAttribute()” method can be used add new objects to the “getServletContext” collection. Step2 shows how we can get the object back using “getAttribute()” and manipulate the same. Step3 shows how to remove an already shared application object from the collection. “getServletContext()” object is shared across servlets with in a application and thus can be used to share data between servlets.


Questions : 16
Explain the concept of SSI ?
Answers : 16
Server Side Includes (SSI) are commands and directives placed in Web pages that are evaluated by the Web server when the Web page is being served. SSI are not supported by all web servers. So before using SSI read the web server documentation for the support. SSI is useful when you want a small part of the page to be dynamically generated rather than loading the whole page again.


Questions : 17
what’s the difference between Authentication and authorization?
Answers : 17
Authentication is the process the application identifies that you are who. For example when a user logs into an application with a username and password, application checks that the entered credentials against its user data store and responds with success or failure. Authorization, on the other hand, is when the application checks to see if you're allowed to do something. For instance are you allowed to do delete or modify a resource.


Questions : 18
Explain in brief the directory structure of a web application?
Answers : 18
Below is the directory structure of a web application:-
webapp/
WEB-INF/web.xml
WEB-INF/classes
WEB-INF/lib

The webapp directory contains the JSP files, images, and HTML files. The webapp directory can also contain subdirectories such as images or html or can be organized by function, such as public or private.
The WEB-INF/web.xml file is called the deployment descriptor for the Web application. This file contains configuration information for the Web application, including the mappings of URLs to servlets and filters. The web.xml file also contains configuration information for security, MIME type mapping, error pages, and locale settings
The WEB-INF/classes directory contains the class files for the servlets, JSP files, tag libraries, and any other utility classes that are used in the Web application.
The WEB-INF/lib directory contains JAR files for libraries that are used by the Web application. These are generally third-party libraries or classes for any tag libraries used by the Web application.
What is Servlet?
A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request\/response paradigm.
Why is Servlet so popular? 
Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
What is servlet container? 
The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.
When a client request is sent to the servlet container, how does the container choose which servlet to invoke? 
The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
If a servlet is not properly initialized, what exception may be thrown? 
During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.
Given the request path below, which are context path, servlet path and path info? 
/bookstore/education/index.html 

context path: /bookstore
servlet path: /education
path info: /index.html
What is filter? Can filter be used as request or response? 
A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.
When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?
I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.
What is new in ServletRequest interface ? (Servlet 2.4) 
The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()
Request parameter How to find whether a parameter exists in the request object? 
1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)
How can I send user authentication information while making URL Connection? 
You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
Can we use the constructor, instead of init(), to initialize servlet? 
Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.
How can a servlet refresh automatically if some new data has entered the database? 
You can use a client-side Refresh or Server Push
The code in a finally clause will never fail to execute, right? 
Using System.exit(1); in try block will not allow finally code to execute.
What mechanisms are used by a Servlet Container to maintain session information?
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information
Difference between GET and POST 
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy. 
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.
What is session? 
The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.
What is servlet mapping? 
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.
What is servlet context ? 
The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial).
Which interface must be implemented by all servlets? 
Servlet interface.
Explain the life cycle of Servlet.
Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.
When is the servlet instance created in the life cycle of servlet? What is the importance of configuring a servlet? 
An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.
Why don't we write a constructor in a servlet? 
Container writes a no argument constructor for our servlet.
When we don't write any constructor for the servlet, how does container create an instance of servlet? 
Container creates instance of servlet by calling Class.forName(className).newInstance().
Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time? 
Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.
What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext? 
We can give relative URL when we use ServletRequest and not while using ServletContext.
Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()? 
Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.
(Q) What is a Servlet?
(A) Servlets are server side components used to develop server side web applications.
(Q) What was the technology used before Servlet?
(A) CGI was used for server side applications, but with drawbacks of CGI(more time for getting response) Servlet was replaced by SUN.
(Q) What is the difference between Servlet and Applet?
(A) As we know Servlets are server side components that executes at server side, Applet are client side components and these are executed on client`s browser.
(Q) What is the difference between doGet and doPost?
(A) doGet() and doPost() are HTTP request handled by servlet predefined classes. doGet() is used for sending data appended to a query string in the URL. In doPost(), the parameters are sent separately. doPost() is Idempotent i.e if the user requests for something & later he changes his decision & rerequests to make some changes in previous request.
(Q) Example for doGet() and doPost()?
(A) public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
doPost(req, res);
}
(Q) What is directory structure of a web application?
(A) Any web application consists of mainly two parts
WEB-INF – In this we have web.xml, classes directory, lib directory
Public resource folder
(Q) What is the difference between HttpServlet and GenericServlet?
(A) A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods.
(Q) Why to use Servlet?
(A) To develop a web application we need to handle multiple request and give the particular page, Servlet can handle multiple requests concurrently, and can synchronize requests.
(Q) How Can I communicate with two Servlets?
(A) Servlets can be collaborated in two ways Using Forward or redirect from one Servlet to other. Another way is to load Servlet from ServletContext and access methods.
(Q) Explain Servlet Life Cycle?
(A) The Web container instantiates and initializes the Servelt init() method, then Servlet will be in a ready state to service request from clients.
Web container then calls Servlet`s service() to respond to client`s request.
After completing the request web container will call destroy() to send to garbage collection.
- See more at: http://thestudentdaily.com/2011/11/java-servlets-interview-questions-and-answers-for-freshers/936/#sthash.HYKVe537.dpuf


No comments:

Post a Comment