Wednesday, February 4, 2009

Servlet interview questions

<-Pre HomeNext->
Best Sevlet Interview questions.

What is a Servlet?
A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model.
OR
A Servlet is a server side java program which processes client requests and generates dynamic web content.

Explain the architechture of a Servlet?
javax.servlet.Servlet interface is the core abstraction which has to be implemented by all servlets either directly or indirectly. Servlet run on a server side JVM ie the servlet container.Most servlets implement the interface by extending either javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet.A single servlet object serves multiple requests using multithreading.

What is the difference between GenericServlet and HttpServlet?
GenericServlet is a generalised and protocol independent servlet which defined in javax.servlet package. Servlets extending GenericServlet should override service() method.
javax.servlet.http.HTTPServlet extends GenericServlet. HTTPServlet is http protocol specific ie it services only those requests thats coming through http.A subclass of HttpServlet must override at least one method of doGet(), doPost(),doPut(), doDelete(), init(), destroy() or getServletInfo().

Explain life cycle of a Servlet?
On client's initial request, Servlet Engine loads the servlet and invokes the init() methods to initialize the servlet. The servlet object then handles subsequent client requests by invoking the service() method. The server removes the servlet by calling destry() method.

What is the difference between doGet() and doPost()?
doGET Method : Using get method we can able to pass 2K data from HTML
All data we are passing to Server will be displayed in URL (request string).
A request string for doGet() looks like the following: http://www.google.com/name?Test=check&Parm=parameter&…&Pass=yes.
doPOST Method : In this method we does not have any size limitation.
All data passed to server will be hidden, User cannot able to see this info
on the browser.

How do I support both GET and POST protocol from the same Servlet?
Support POST, then have your doGet method call your doPost method:
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doPost(req, res);
}

How to call one servlet from another servlet?
there are several ways to do this, including :
. use a RequestDispatcher
· send a redirect
· use a URLConnection or HTTPClient

Whats the advantages using servlets over using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.

What is the difference between ServletConfig and ServletContext?
ServletConfig is a servlet configuration object used by a servlet container to pass information to a servlet during initialization. All of its initialization parameters can only be set in deployment descriptor. The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.
ServletContext is an interface which defines a set of methods which the servlet uses to interact with its servlet container. ServletContext is common to all servlets within the same web application. Hence, servlets use ServletContext to share context information.

What is the difference between using getSession(true) and getSession(false) methods?
getSession(true) method will check whether already a session is existing for the user. If a session is existing, it will return the same session object, Otherwise it will create a new session object and return taht object.

getSession(false) method will check for the existence of a session. If a session exists, then it will return the reference of that session object, if not, it will return null.

What is meant by a Web Application?
A Web Application is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.

What is Servlet Chaining?
Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

How do you find out what client machine is making a request to your servlet?
The ServletRequest class has functions for finding out the IP address or host name of the client machine. getRemoteAddr() gets the IP address of the client machine and getRemoteHost()gets the host name of the client machine.

What is the structure of the HTTP response?
The response can have 3 parts:

1) Status Code - describes the status of the response. For example, it could indicate that the request was successful, or that the request failed because the resource was not available. If your servlet does not return a status code, the success status code, HttpServletResponse.SC_OK, is returned by default.

2) HTTP Headers - contains more information about the response. For example, the header could specify the method used to compress the response body.

3) Body - contents of the response. The body could contain HTML code, an image, etc.

^Back to top

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

Which protocol will be used by browser and servlet to communicate ?
HTTP

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.

What is the Max amount of information that can be saved in a Session Object?
As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier) , which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on hard disk.

What is HTTP Tunneling?
HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intra-network of an organization is blocked by a firewall and the network is exposed to the outer world only through a specific web server port , that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and sent as HttpRequest. The masking of other protocol requests as http requests is HTTP Tunneling.

What's the difference between sendRedirect( ) and forward( ) methods?
A sendRedirect method creates a new request (it's also reflected in browser's URL ) where as forward method forwards the same request to the new target(hence the change is NOT reflected in browser's URL). The previous request scope objects are no longer available after a redirect because it results in a new request, but it's available in forward. sendRedirect is slower compared to forward.

Is there some sort of event that happens when a session object gets bound or unbound to the session?

HttpSessionBindingListener will hear the events When an object is added and/or remove from the session object, or when the session is invalidated, in which case the objects are first removed from the session, whether the session is invalidated manually or automatically (timeout).

Is it true that servlet containers service each request by creating a new thread? If that is true, how does a container handle a sudden dramatic surge in incoming requests without significant performance degradation?

The implementation depends on the Servlet engine. For each request generally, a new Thread is created. But to give performance boost, most containers, create and maintain a thread pool at the server startup time. To service a request, they simply borrow a thread from the pool and when they are done, return it to the pool.
For this thread pool, upper bound and lower bound is maintained. Upper bound prevents the resource exhaustion problem associated with unlimited thread allocation. The lower bound can instruct the pool not to keep too many idle threads, freeing them if needed.

What is URL Encoding and URL Decoding?
URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and Decoding is the reverse process converting all Hex Characters back their normal form.
For Example consider this URL,
/ServletsDirectory/Hello'servlet/

When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is

http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F

This can be decoded back using

URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F")


Do objects stored in a HTTP Session need to be serializable? Or can it store any object?
Yes, the objects need to be serializable, but only if your servlet container supports persistent sessions. Most lightweight servlet engines (like Tomcat) do not support this. However, many EJB-enabled servlet engines do. Even if your engine does support persistent sessions, it is usually possible to disable this feature.

What is the difference between session and cookie?
The difference between session and a cookie is two-fold.

1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. There is no way to disable sessions from the client browser.

2) session and cookies differ in type and amount of information they are capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. Javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects.

^Back to top

How to determine the client browser version?
Another name for "browser" is "user agent." You can read the User-Agent header using request.getUserAgent() or request.getHeader("User-Agent").




Pre->JSP

Next->JavaScript

*****Please feel free to give feedback at shrawan.iitg@gmail.com and comments below *****

No comments:

Post a Comment