Jul 5, 2008

SERVLETS FAQS

SERVLETS INTERVIEW QUESTIONS AND ANSWERS
1) What is a Servlet?
A Servlet is a server side java program which processes client requests and generates dynamic web content.

2) 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.

3) What is the difference between an Applet and a Servlet?
An Applet is a client side java program that runs within a Web browser on the client machine whereas a servlet is a server side component which runs on the web server. An applet can use the user interface classes like AWT or Swing while the servlet does not have a user interface. Servlet waits for client's HTTP requests from a browser and generates a response that is displayed in the browser.

4) 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().

5) 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.

6) 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).

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.

7) 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.

8) 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.

9) 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.

10) What is a Server Side Include ?
Server Side Include is a Web page with an embedded servlet tag. When the Web page is accessed by a browser, the web server pre-processes the Web page by replacing the servlet tag in the web page with the hyper text generated by that servlet.

11) 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.

12) 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.

13) 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.

14) What is a cookie?
A cookie is a bit of information that the Web server sends to the browser which then saves the cookie to a file. The browser sends the cookie back to the same server in every request that it makes. Cookies are often used to keep track of sessions.

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

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

17) 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.

18) How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push

19) 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.

20) 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.

21) 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.


22) 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).

23) 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.

25) 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")

26) 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.

27) 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.

28) 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")

No comments: