Saturday, December 6, 2008

Servlet Interview Question And Answer

SERVLET

1.) What is the difference between GenericServlet and HttpServlet?

A GenericServlet has a service ( ) method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet (), doPost (), doHead () methods plus doPut (), doOptions (), doDelete (), doTrace () methods. Both these classes are abstract. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality like doGet and doPost methods.

2.) How you can destroy the session in Servlet?

It can call invalidate() method on the session object to destroy the session. e.g. session.invalidate();

3.) What are different types of Session Tracking?

Mechanism for Session Tracking are:

a) Cookies

b) URL rewriting

c) Hidden form fields

d) SSL Sessions

4.)What are the uses of Servlets?

* Servlets are used to process the client request.

* A Servlet can handle multiple request concurrently and be used to develop high performance system

A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.

5.) What must be implemented by all Servlets?

The Servlet Interface must be implemented by all servlets.

6.) What mechanisms are used by a Servlet Container to maintain session information?

Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.

7.) What are the advantages of Servlets over CGI programs?

Java Servlets have a number of advantages over CGI and other API’s. They are:

Platform Independence

Performance

Extensibility

Safety

Secure

8.) What are methods of HttpServlet?

The methods of HttpServlet class are :

* doGet() is used to handle the GET, conditional GET, and HEAD requests

* doPost() is used to handle POST requests

* doPut() is used to handle PUT requests

* doDelete() is used to handle DELETE requests

* doOptions() is used to handle the OPTIONS requests and

· doTrace() is used to handle the TRACE requests

9.) What are the types of Servlet?

There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality like doGet and doPost methods.

10.) When doGET() method will execute?

When we specified method=’GET’ in HTML Example : < name="'SSS'" method="'GET'">

11.) What is the use of ServletContext?

Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext.

12.) Which protocol will be used by browser and servlet to communicate?

HTTP is the protocol that will be used by browser and servlet to communicate.

14.) which code line must be set before any of the lines that use the PrintWriter?

setContentType() method must be set.

15.) What is the servlet life cycle?

When first request came in for the servlet , Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method.

16.) What are the uses of Servlets?

A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.

17.) What’s the difference between servlets and applets?

Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface.

18.) What is the servlet?

Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming, we will use java language. A servlet can handle multiple requests concurrently.

19) What are the classes and interfaces for servlets?

There are two packages in servlets and they are javax.servlet and javax.servlet.http.

Javax.servlet contains:

Interfaces Classes

Servlet Generic Servlet

ServletRequest ServletInputStream

ServletResponse ServletOutputStream

ServletConfig ServletException

ServletContext UnavailableException

SingleThreadModel

Javax.servlet.http contains:

Interfaces Classes

HttpServletRequest Cookie

HttpServletResponse HttpServlet

HttpSession HttpSessionBindingEvent

HttpSessionCintext HttpUtils

HttpSeesionBindingListener

20) What is the difference between doPost and doGet methods?

a) doGet() method is used to get information, while doPost( ) method is used for posting information.

b) doGet() requests can't send large amount of information and is limited to 240-255 characters. However, doPost( )requests passes all of its data, of unlimited length.

c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.

21) What is the life cycle of a servlet?

Each Servlet has the same life cycle:

a) A server loads and initializes the servlet by init () method.

b) The servlet handles zero or more client's requests through service( ) method.

c) The server removes the servlet through destroy() method.

22) Who is loading the init() method of servlet?

Web server

23)What are the different servers available for developing and deploying Servlets?

a) Java Web Server

b) JRun

g) Apache Server

h) Netscape Information Server

Web Logic

24) How many ways can we track client and what are they?

The servlet API provides two ways to track client state and they are:

Using Session tracking and Using Cookies.

25) What is session tracking and how do you track a user session in servlets?

Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are:

a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password

b) Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When the form containing the fields is submitted, the fields are sent back to the server

c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.

d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.

e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session.maxresidents property

26) What are cookies and how will you use them?

Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user.

Create a cookie with the Cookie constructor:

public Cookie(String name, String value)

A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse:

public void HttpServletResponse.addCookie(Cookie cookie)

A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest:

public Cookie[ ] HttpServletRequest.getCookie( ).

26) Is it possible to communicate from an applet to servlet and how many ways and how?

Yes, there are three ways to communicate from an applet to servlet and they are:

a) HTTP Communication(Text-based and object-based)

b) Socket Communication

c) RMI Communication

(You can say, by using URL object open the connection to server and get the InputStream from URLConnection object).

Steps involved for applet-servlet communication:

1) Get the server URL.

URL url = new URL();

2) Connect to the host

URLConnection Con = url.openConnection();

3) Initialize the connection

Con.setUseCatches(false):

Con.setDoOutput(true);

Con.setDoInput(true);

4) Data will be written to a byte array buffer so that we can tell the server the length of the data.

ByteArrayOutputStream byteout = new ByteArrayOutputStream();

5) Create the OutputStream to be used to write the data to the buffer.

DataOutputStream out = new DataOutputStream(byteout);

27) Why should we go for interservlet communication?

Servlets running together in the same server communicate with each other in several ways.

The three major reasons to use interservlet communication are:

a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object)

b) Servlet reuse - allows the servlet to reuse the public methods of another servlet.

c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)

28) Is it possible to call servlet with parameters in the URL?

Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).

29) What is Servlet chaining?

Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.

In servlet chaining, one servlet's output is piped to the next servlet's input. This process continues until the last servlet is reached. Its output is then sent back to the client.

30) How do servlets handle multiple simultaneous requests?

The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

31) Are servlets platform independent? If so Why? Also what is the most common application of servlets?

Yes, Because they are written in Java. The most common application of servlet is to access database and dynamically construct HTTP response

32). What is the three tier model?

It is the presentation, logic, backend

33) Describe 3-Tier Architecture in enterprise application development.?

In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business layer consists of the application or business logic, and the data layer contains the data that is needed for the application.

34) What's the advantages using servlets than using CGI?

In CGI,create separate process for every request.where as in servlet,not create separate process.

35) What's 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.

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

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

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

40) If you want a servlet to take the same action for both GET and POST request, what you should do?

Simply have doGet call doPost, or vice versa.

41) What is the servlet life cycle?

Each servlet has the same life cycle:

* A server loads and initializes the servlet (init())

* The servlet handles zero or more client requests (service())

* The server removes the servlet (destroy()) (some servers do this step only when they shut down)

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

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

44) 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.(http://validator.w3.org and http://www.htmlhelp.com/tools/validator/ are two major online validators)

45) What are the types of ServletEngines?

Standalone ServletEngine:A standalone engine is a server that includes built-in support for servlets.

Add-on ServletEngine:Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind.

46) What is a Session Id?

It is a unique id assigned by the server to the user when a user first accesses a site or an application ie. when a request is made.

47). List out Differences between CGI Perl and Servlet?

Servlet CGI

Platform independent Platform dependent.

Language dependent Language independent.

48) What is servlet tunnelling?.

Used in applet to servlet communications, a layer over http is built so as to enable object serialization.

49). What is a cookie?.

Cookies are a way for a server to send some information to a client to store and for the server to later retrieve its data from that client.Web browser supports 20 cookies/host of 4kb each.

50). What is the frontend in Java?.Also what is Backend?.

Frontend: Applet

Backend : Oracle, Ms-Access(Using JDBC).

51) What is the default HttpRequest method?.

doGet().

52) Why do u use Session Tracking in HttpServlet ?

HTTP is a stateless protocol ;it provides no way for a server to recognize that a sequence of requests are all from the same client .

53) Can u use javaScript in Servlets ?

YES

54) What is the capacity the doGet can send to the server ?

Some servers limit the length of URL's and query strings to about 240 charcters

55).What are the type of protocols used in HttpServlet ?

HTTP,HTTPS

56)What is a Servlet?

A Servlet is a server side java program which processes client requests and generates dynamic web content.


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


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


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



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


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

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


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

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


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


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


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

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


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


70) Which code line must be set before any of the lines that use the PrintWriter?


setContentType() method must be set.


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


72) How can a servlet refresh automatically if some new data has entered the database?


You can use a client-side Refresh or Server Push


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


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

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


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


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


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


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


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

81) 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: