Tuesday, November 1, 2011

Servlet interview questions with answers

What is the servlet?
Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.
-Servlets are used to enhance and extend the functionality of Webserver.
Servlets handles Java and HTML separately.

What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task.

What are the characters of Servlet?
As Servlet are written in java, they can make use of extensive power of the JAVA API,such as networking and URL access,multithreading,databaseconnectivity,RMI object serialization.
Efficient : The initilazation code for a servlet is executed only once, when the servlet is executed for the first time.
Robest : provide all the powerfull features of JAVA, such as Exception handling and garbage collection.
Portable: This enables easy portability across Web Servers.
Persistance : Increase the performance of the system by executing features data access.

What is the difference between JSP and SERVLETS
Servlets : servlet tieup files to independitently handle the static presentation logic and dynamic business logic , due to this a changes made to any file requires recompilation of the servlet.
- The servlet is Pre-Compile.

JSP : Facilities segregation of work profiles to Web-Developer and Web-Designer , Automatically incorporates changes made to any file (PL & BL) , no need to recompile.
Web-Developer write the code for Bussiness logic whereas Web-Designer designs the layout for the WebPage by HTML & JSP.
- The JSP is Post-Compile.

What are the advantages using servlets than using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs. They are developed with Java Servlet API, a standard Java extension.

What is the difference between servlets and applets?
Servlets are to servers. Applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

What is the difference between GenericServlet and HttpServlet?
GenericServlet is for servlets that might not use HTTP, like for instance FTP service.As of only Http is implemented completely in HttpServlet. The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are.
GenericServlet belongs to javax.servlet package
GenericServlet is an abstract class which extends Object and implements Servlet, ServletConfig and java.io.Serializable interfaces.
The direct subclass to GenericServlet is HttpServlet.It is a protocol-independent servlet

What are the differences between GET and POST service methods?
Get Method : Uses Query String to send additional information to the server.
-Query String is displayed on the client Browser.
Query String : The additional sequence of characters that are appended to the URL ia called Query String. The length of the Query string is limited to 255 characters.
-The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.

POST Method : The Post Method sends the Data as packets through a separate socket connection. The complete transaction is invisible to the client. The post method is slower compared to the Get method because Data is sent to the server as separate packates.
--You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
What is the servlet life cycle?
In Servlet life cycles are,
init(),services(),destory().
Init( ) : Is called by the Servlet container after the servlet has ben Instantiated.
--Contains all information code for servlet and is invoked when the servlet is first loaded.
-The init( ) does not require any argument , returns a void and throws Servlet Exception.
-If init() executed at the time of servlet class loading.And init() executed only for first user.
-You can Override this method to write initialization code that needs to run only once, such as loading a driver , initializing values and soon, Inother case you can leave normally blank.
Public void init(ServletConfig Config) throws ServletException

Service( ) : is called by the Servlet container after the init method to allow the servlet to respond to a request.
-Receives the request from the client and identifies the type of request and deligates them to doGet( ) or doPost( ) for processing.
Public void service(ServletRequest request,ServletResponce response) throws ServletException, IOException

Destroy( ) : The Servlet Container calls the destroy( ) before removing a Servlet Instance from Sevice.
-Excutes only once when the Servlet is removed from Server.
Public void destroy( )

If services() are both for get and post methods.
-So if u want to use post method in html page,we use doPost() or services() in servlet class.
-if want to use get methods in html page,we can use doGet() or services() in servlet calss.
-Finally destory() is used to free the object.

What is the difference between ServletContext and ServletConfig?
Both are interfaces.
Servlet Config():The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.
A ServletConfig object passes configuration information from the server to a servlet. ServletConfig also includes ServletContext object.
getParameter( ) , getServletContext( ) , getServletConfig( ), GetServletName( )

Servlet Context(): The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.
ServletContext defines methods that allow a servlet to interact with the host server. This includes reading server-specific attributes, finding information about particular files located on the server, and writing to the server log files. I f there are several virtual servers running, each one may return a different ServletContext.
getMIMEType( ) , getResourse( ), getContext( ),getServerInfo( ),getServletContetName( )
11. Can I invoke a JSP error page from a servlet?
Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets.

Can I just abort processing a JSP?
Yes.Because your JSP is just a servlet method,you can just put (whereever necessary) a < % return; %>

What is a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

If you want a servlet to take the same action for both GET and POST request, what should you do?
Simply have doGet call doPost, or vice versa.

Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set before transmitting the actual document.

How HTTP Servlet handles client requests?
An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

What is the Servlet Interface?
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 such as HttpServlet.
Servlets-->Generic Servlet-->HttpServlet-->MyServlet.
The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

When a servlet accepts a call from a client, it receives two objects. What are they?
ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the
Client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

What information that the ServletRequest interface allows the servlet access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data
from clients that use application protocols such as the HTTP POST and PUT methods.

What information that the ServletResponse interface gives the servlet methods for replying to the client?
It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

Difference between single thread and multi thread model servlet
A servlet that implements SingleThreadModel means that for every request, a single servlet instance is created. This is not a very scalable solution as most web servers handle multitudes of requests. A multi-threaded servlet means that one servlet is capable of handling many requests which is the way most servlets should be implemented.
a. A single thread model for servlets is generally used to protect sensitive data ( bank account operations ).
b. Single thread model means instance of the servlet gets created for each request recieved. Its not thread safe whereas in multi threaded only single instance of the servlet exists for what ever # of requests recieved. Its thread safe and is taken care by the servlet container.
c. A servlet that implements SingleThreadModel means that for every request, a single servlet instance is created. This is not a very scalable solution as most web servers handle multitudes of requests. A multi-threaded servlet means that one servlet is capable of handling many requests which is the way most servlets should be implemented.

A single thread model for servlets is generally used to protect sensitive data ( bank account operations ).

What is servlet context and what it takes actually as parameters?
Servlet context is an object which is created as soon as the Servlet gets initialized.Servlet context object is contained in Servlet Config. With the context object u can get access to specific
resource (like file) in the server and pass it as a URL to be displayed as a next screen with the help of RequestDispatcher
eg :-
ServletContext app = getServletContext();
RequestDispatcher disp;
if(b==true)
disp = app.getRequestDispatcher
("jsp/login/updatepassword.jsp");
else
disp = app.getRequestDispatcher
("jsp/login/error.jsp");
this code will take user to the screen depending upon the value of b.
in ServletContext u can also get or set some variables which u would
like to retreive in next screen.
eg
context.setAttribute("supportAddress", "temp@temp.com");
Better yet, you could use the web.xml context-param element to
designate the address, then read it with the getInitParameter method
of ServletContext.

Can we call destroy() method on servlets from service method?
destroy() is a servlet life-cycle method called by servlet container to kill the instance of the servlet. "Yes". You can call destroy() from within the service(). It will do whatever logic you have in destroy() (cleanup, remove attributes, etc.) but it won't "unload" the servlet instance itself. That can only be done by the container
What is the use of ServletConfig and ServletContext..?
An interface that describes the configuration parameters for a servlet. This is passed to the servlet when the web server calls its init() method. Note that the servlet should save the reference to the ServletConfig object, and define a getServletConfig() method to return it when asked. This interface defines how to get the initialization parameters for the servlet and the context under which the servlet is running.
An interface that describes how a servlet can get information about the server in which it is running. It can be retrieved via the getServletContext() method of the ServletConfig object.

What is difference between forward() and sendRedirect().. ? Which one is faster then other and which works on server?
Forward( ) : javax.Servlet.RequestDispatcher interface.
-RequestDispatcher.forward( ) works on the Server.
-The forward( ) works inside the WebContainer.
-The forward( ) restricts you to redirect only to a resource in the same web-Application.
-After executing the forward( ), the control will return back to the same method from where the forward method was called.
-the forward( ) will redirect in the application server itself, it does’n come back to the client.
- The forward( ) is faster than Sendredirect( ) .
To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain RequestDispatcher Object. The Servlet technology provides in three ways.
1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a String containing the path of the other resources, path is relative to the root of the ServletContext.

RequestDispatcher rd=request.getRequestDispatcher(“secondServlet”);
Rd.forward(request, response);

2. getRequestDispatcher( ) of the javax.Servlet.Request interface , the path is relative to current HtpRequest.
RequestDispatcher rd=getServletContext( ).getRequestDispatcher(“servlet/secondServlet”);
Rd.forward(request, response);

3. By using the getNameDispatcher( ) of the javax.Servlet.ServletContext interface.
RequestDispatcher rd=getServletContext( ).getNameDispatcher(“secondServlet”);
Rd.forward(request, response);

Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface
-RequestDispatcher.SendRedirect( ) works on the browser.
-The SendRedirect( ) allows you to redirect trip to the Client.
-The SendRedirect( ) allows you to redirect to any URL.
-After executing the SendRedirect( ) the control will not return back to same method.
-The Client receives the Http response code 302 indicating that temporarly the client is being redirected to the specified location , if the specified location is relative , this method converts it into an absolute URL before redirecting.

-The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen.
Response. SendRedirect( “absolute path”);
Absolutepath – other than application , relative path - same application.

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

do we have a constructor in servlet ? can we explictly provide a constructor in servlet programme as in java program ?
We can have a constructor in servlet .

Session : A session is a group of activities that are performed by a user while accesing a particular website.
Session Tracking :The process of keeping track of settings across session is called session tracking.
Hidden Form Fields : Used to keep track of users by placing hidden fields in the form.
-The values that have been entered in these fields are sent to the server when the user submits the Form.
URL-rewriting : this is a technique by which the URL is modified to include the session ID of a particular user and is sent back to the Client.
-The session Id is used by the client for subsequent transactions with the server.
Cookies : Cookies are small text files that are used by a webserver to keep track the Users.
A cookie is created by the server and send back to the client , the value is in the form of Key-value pairs. Aclient can accept 20 cookies per host and the size of each cookie can be maximum of 4 bytes each.
HttpSession : Every user who logs on to the website is autometacally associated with an HttpSession Object.
-The Servlet can use this Object to store information about the users Session.
-HttpSession Object enables the user to maintain two types of Data.
ie State and Application.

How to communicate between two servlets?
Two ways:
a. Forward or redirect from one Servlet to another.
b. Load the Servlet from ServletContext and access methods.
29. How to get one Servlet's Context Information in another Servlet?
Access or load the Servlet from the Servlet Context and access the Context Information