Tuesday 27 March 2007

Servlet Interview Questions 51-75

Q51. What is the difference between ServletContext and ServletConfig?
Ans: The servlet context is a single object for the entire application withing the container where as servlet config represents the single servlet configurations i.e. each servlet instance has its own servlet config.
If we want some configuration parameter at application level, they need to be set in Servlet context , however if we want a configuration parameter for a particular servlet, that should go to servlet config.
We should keep always in mind that servlet context objects are shared across the application and all the requests have the access to them. so these objects should be readonly as far as possible to avoid any potential synchronization problems. If we need to modify these objects they must be ensured be modified under sync blocks. though doing such things are never my favourites.

Q52. What are the common mechanisms used for session tracking?

Ans: There are 3 fundamental ways for session trackings. The primary requirement for session tracking is the server should be able to uniqly identify different browsers and the series of requests from them. The mechanism server relies upon in this case is the sessionID. In lay man's language. On recieving the first request from a client(browser) The server gives the client a unique Id (we call it sessionID) . Server expects the client to circulate this ID with all the subsequent requests and How does client ciculates this Id? There are 3 different ways :)
1) Cookies : client stores The session Id in a cookie called jsessionID and every request takes the valid cookies automatically. So sessionId is automatically sent to the server with each request and session is maintained.

2) URL Rewriting : what if cookies are disabled? so client won't be able be store the sessionId in a cookie. So first opion does not seems feasible and still we need to make sure "every request should carry the sessionId if client has the one". We know every request has URL agree? what if we append the sessionId somehow in each url from Client? this is what this technique is, but its not as straight forward as the first one where we need not do anything. In url rewriting the view writer has to make sure each and every link on the page carries the sessionId to the server.

3) Hidden form fields: What if I dont want to rely on the default session management behavoiur of the server and browser. what I can do is, I write my own piece of server side programs to create/manage the sessions and for all my applications I need a sessionId request parameter mechanism to share the sessionId with the browser and server. Incase of links, I would send the sessionId in query strings and in case of forms I would define a hidden field which would carry the session Id on submit. This mechanism is called Hidden form Fields.


Q53 What is the difference between the RequestDispatcher from Request and ServletContext?
Ans: The answer lies in the url-patterns. Simplest answer is the request dispatcher obtained from servlet context can dispatch the request anywhere in the application i.e. to any servlet/jsp/page. howerver the rd from request is not capable of doing so. its can only forward the request to resources which have the same base urls.
i.e. lets us say we have following servlets /bill/s1, /bill/s2, /bill/reciept/s3, /shop/a1, /shop/a2 now if we have request dispatcher from request then i can dispatch the request from s1 to s2, s3. However you can not dispatch the request from s3 to s1 or s2
you can not dispatch the request from s1 to a1 or a2 the reason being the base urls are different.

Q54. What is the difference between sendRedirect and Forward?
Ans: The forward is a request dispatch on server side itself and in sendRedirect from s1 to s2 takes place something like this. request processing for s1 halts where we say sendRedirect(s2) and server responds with the response code 302 (saying please send a new request to s2) and browser sends the new request to s2. i.e. It involves a new roundtrip.
The request in case of forward does not loose its identity. i.e. all the request parameters/objects avaliable in s1 are also available in s2. In case of sendRedirect the request to s2 is etirely a fresh request so earlier identity is lost.

Q55. If we use sendRedirect does the session expires?
Ans: This question is to confuse you. It has nothing to do with the session expiry :)
No, The session does not expire in this case. The session expires only in the following cases.

1) Some servlet explicitly expires the session for a request through session.invalidate()

2) The client does not send the request to server for long enough time. which is greater than the session timeout interval.

Q56. How can I pass on an object from servlet S1 to servlet S2 if I am using sendRedirect?
Ans: Use Session object, but make sure guys you clean up the session in S2 so that the object is not just sitting there in luxury and doing nothing after the request for S2 is finished.

Q57. How can I pass on a request parameter from servlet S1 to servlet S2 if I am using sendRedirect?
Ans: we append the request parameter in the Redirect URL as a part of query string.

Q58. Which one is faster sendRedirect or forward?
Ans: Let us not answer it straight away :D why dont you guys judge it, I give you hint.
Forward is a request dispatch on server side i.e. if I want to Forward from s1 to s2. Server takes the request/response from s1 and give to s2.
Redirect is something like when you want to redirect from s1 to s2. request processing for s1 is halted and then server asks the browser to please please send the request to s2 and browser sends altogether a fresh request to s2. i.e. request is routed through the browser?

Now answer please? :)

Q59. If forward is faster then why you would like to use sendRedirect?
Ans: Its a trap :). The one thing forward can not do is it can not forward the request to a different application context i.e. urls outside of your applications.

you also do redirects within your applications too. when you would require to redirect within your applications? you want answer? here we go.... when you don't want to forward :D.

Let us imagine a situation. Let us say you are wrote a servlet (s1) to send an email. you have to send a email when client submits the form and show him the status page (s2). Let us say when you send an email in s1 and then you forward the request to s2 and s2 shows the status page. everything working fine right?

Now let us consider this. I opened the browser and fill the email form and submit it and say becuase my network is slow, I could not see the status page. so i tried refresh 2-3 times. now what your implementation would do is, it would send the emails 3-4 times. do you think I really want to send the email 3-4 times? whats wrong then?

So you need to think such usability issues arising out of implementations as well.

Q60. If I redirect from servlet S1 to servlet S2, which method of S2 get called doGet() or doPost(), why?s

Ans: we were discussing in 58 that browser sends the fresh request to the S2 and you know guys the default method for any cleint to request a URL is GET. So if a redirect request is a GET request which method of S2 would be called? Not able to judge it still then you are in a wrong matrix :)

Q61. If I forward from doPost() method of servlet S1 to servlet S2, which method of S2 get called doGet() or doPost(), why?
Ans: We have discussed in 54 that in forward the request retains its identity. so if s1 recieved POST the s2 would also recieve the POST. so doPost() would be executed.

Q62. What is a query string?
Ans: In case of GET request the request parameters are passed as name value pairs in querystring. e.g. http://localhost:8080/shopping/login?user=neo&password=neo
here the query string is user=neo&password=neo
and we have 2 request parameters here user and password

Q63. Is the request parameter name case sensitive? What I mean is, Let us say request contains parameter "username=bob" if I fetch it like this request.getParameter("UserName"); would I get the value "bob"?
Ans: no its not. yes we would get the value bob.
But I think being a java technologists, for consistency purposes Its better to stick to a case sensitive perceptions. i.e. if we define the form field UserName , we should fetch it as UserName.

Q64. If I fetch a request parameter with a name which is not there in the request…do I get a null value or I get an exception?
Ans: We get the null

Q65. How you would fetch the request parameter which has more than one value?
Ans: String[] request.getParameterValues(String paramName)

Q66. The servlet element must occur before the servlet-mapping element in a web.xml file ?

Q67. The servlet-class element must specify the full package name of the servlet class?

Q68. The servlet configuration can change from request to request True/False?
Ans: Requests for same servlet False
Requests for different servlets True \

Q69. The servlet context can change from request to request True/False?
Ans: False (within the same webapplication :))

Q70. What are the methods defined in Servlet Interface?
Q71. Can you access the client side files from a servlet?
Ans: No servlets always executes on the server side and the underlying protocol for client/server communication is HTTP. which does not allow the access to client filesystems for security reasons. This is only possible through javascript and it works only to a very limited extent and its possible the security setting on browser does not allow the javascript to access any file on client side.

Servlet Interview Questions 26-50

Posting the second set of 25 questions on servlets. I would update the page with answers in day or 2 keep reading. Have fun.....

Q26: What are the type of protocols supported by HttpServlet?
Ans :
HTTP and HTTPS.

Q27: What is Session ID?
Ans :
A session ID is an unique identification alpha-numeric string, that is shared between the client and the server to maintain the session.

Q28: Why do u use Session Tracking in HttpServlet?
Ans :
To track the user state on server side.

Q29: What are the advantage of Cookies over URL rewriting?
Ans :
Sessions tracking using Cookies are more secure and fast.Url rewriting requires more development effort since we have rewrite each URL to contain the sessionId.

Q30: What is session hijacking?
Ans :
If any client program is able to generate a valid sessionId for a server it can take control of user session. this is a hijacking of some existing session, which belongs to some other client.

Q31: What is Session Migration?
Ans :
Session Migration is a mechanism of moving the session from one server to another in case of server failure or clustering.
This can be done in 2 ways :
a) Saving the session state on database
b) In-momeory Session objects replication to different servers.

Q32: How do we track a user session in Servlets?
Ans :
HttpSession session = request.getSession() returns the current request's session.

Q33: How you can destroy the session in Servlet?
Ans :
session.invalidate(); destroy the current session.

Q34: Difference between forward and redirect?
Ans :
The forward method would dispatch the request to the path specified in getRequestDispatcher(String path). The request is dispatched from one servlet to another on the server side itself, The response will not be sent back to the client, so the client will not know that request has been dispatched to another servlet. All the request parameters are maintained and available in another servlet as well. if the request was in doGet in first servlet, the second servlet's doGet() would be executed, if it was doPost() then doPost() would be executed.
Since the client does not know about this forward on the server side, no history will be stored on the client/browser, so using the back will not take you to first servlet.

An example using forward:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
rd.forward(request, response);
}

The HttpServletResponse.sendRedirect(String path) method of tell the client to send a new request to the specified path. So the client will send a new request to the server, all previous parameters stored in the request will be unavailable, unless we specify them manually in path. The client's history will be updated so the forward and back buttons will work. This method is useful for redirecting to pages on other servers and domains.

An example using sendRedirect:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("pathToResource");
}

Forward() method is faster than using sendRedirect, becuase no network round trip to the server and back is required.

Q35. What is <load-on-startup> parameter in servlets?

Ans : We provide an integer value in this element. this value tells in what order the servlet's init() method will be executed. If there are multiple servlets the order in which the init is called the the ascending order of this value.

Q36. What if I write <load-on-startup></load-on-startup> for a servlets, I mean no value is provided? Would this give exception? Or it won't intialize the servlets?

Ans:
This is not an error. The servlet would still intialize with the container startup but this servlets would be last to intialize in the intialization sequence.

Q37. What would happen if 2 servlets have same value for <load-on-startup> ?Is this an error? Which one would intialize first?

Ans :
This is not an error. both the servlets would be intialized along with the containner.
The servlet defined first in order in web.xml would intialized first.

Q38. What if I give the same name to 2 servlets <servlet-name> would this be error?
Ans : Yes this is a container start-up time error. The servlet container wont start the webapplication if web.xml has duplication name for 2 or more servlets.

Q39. What is the difference between HttpServlet and GenericServlet?
Ans: Generic servlet represents the servlets are generic level independent of any protocol.
HttpServlet add the additional features of HTTP to the servlets.

Q40. If servlet raised some exception in init() what do think going to happen when it receives request?
Ans: All the request to the servlet are going to get runtime exception.

Q41. I have not defined any doGet() method in servlet, still I call the servlet with GET request what is going to happen? Would I get 404 file not found or I would get exception?
Ans : you get an exception at runtime.

Q42. I defined the servlet only with init () method only, no doGet (), no doPost (), would the servlet compile?
Ans: Yes.

Q43. HttpServletRequest, HttpServletResponse are Interfaces or classes?
Ans:
Interfaces. Only GenericServlet and HttpServlet are classes (they are abstract ones).

Q44. What is Servlet Config?
Ans: This object models/represents the servlet level configurations.

Q45. What is Servlet Context?
Ans:
This object models/represents your application context. The containment in this object are at application level or global level.

Q47. What are Context-Params? Why you would require them?
Ans: The context parameters are also the servlets initialization parameters. The context parameters are available in every servlet. So if some init parametrs is required in multiple servlets we define them at context level as context params.

Q47. Where do I define Context-Params and how I would fetch them in servlets?
Ans:
The Context param are defined within the <web-app> element as follows

<context-param>

<param-name>counter</param-name>
<param-value>100</param-value>
</context-param>


Q48. Can I define a param with multiple values? If not, how can I do that?
Ans: No one init paramtere can have only one string value, if we want multiple values, we can specify say( "," ) comma separted list of values and split them into multiple values in my servlets. If you define the same init parameter multple times the last in the order would be picked by the servlet.

Q49. How would I know the IP Address of the current request?
Ans:
request.getRemoteAddr().

Q50. Can I find out which browser the request is coming from?
Ans: request.getRemoteUser() or request.getRemoteAddr()

Wednesday 21 March 2007

Servlet Interview Questions 1-25

I would post a series of servlets questions in coming days, I think its very important for any guy to have a glance who is going for J2EE technical discussion. These set of questions would help you find out, if there are any grey areas left in your preparation. I would post the answers some time later, Till then try to find if you can answer them.
Here goes the first list.

Q1. Define the webapplication directory structure.
Ans:

Table 1. The Web Application Directory Structure

Directory

Contains

/MyApp

This is the root directory of the web application. All JSP, images, js and XHTML files are stored here or in its subdirectories. Files other than in WEB-INF can be directly accessed through URL or are the Universal scope files.

/MyApp/WEB-INF

This directory contains all resources related to the application This is where your web application deployment descriptor is located. Note that the WEB-INF directory is not in the public/universal scope. No files contained in this directory can be directly accessed from url/browsers.

/MyApp/WEB-INF/classes

This directory is where servlets, utility classes and packages are located.

/MyApp/WEB-INF/lib

This directory contains Java Archive files that the web application depends upon. For example, this is where you would place a JAR file that contained a JDBC driver.


Q2. What is web.xml and whats its purpose? Is it mandatory to have it in your web application?

Ans:
Web.xml is called the web application deployment descriptor. We define/configure
the web application related settings/configurations in this file. e.g. Servlet definitions
and configurations.

Q3. Can a web application have more than one web.xml?

Ans:
No, one webapplication have one web.xml in WEB-INF/

Q4. What is a war file?

Ans:
Archived form of a web application.

Q5. What is <welcome-file-list>?

Ans:
<welcome-file-list> element in web.xml configures the web application's entry point or welcome page.e.g. Following example defines the Home.jsp to be default home page of the application
<welcome-file-list>
<welcome-file>Home.jsp</welcome-file>
</welcome-file-list>

Q6. What is the difference between Webserver and Application Server?

Ans:
Webserver is capable of handling requests and responses over HTTP where as Application Server is capable of executing/serving the application logic of an application. So whenever there is runtime application logic execution is involved, this would be done by the application server. Some people think that if a server has EJB container only then its application server, Just think guys EJB container is just an another way of defining the application logic, If I am not using EJB does that mean I don't have application logic? Funny isn't it?

Q7. Tomcat is a pure web server? True | False or the question can be asked in number of ways also... Tomcat is also an application server True | False? Is tomcat s application server?

Ans:
Tomcat is not a pure Web server. It can also execute the application logics through servltes/Jsps so it's also an application server.


Q8. How do you define the servlet element and servlet-mapping element in web.xml file?
Ans:

The servlet element contains the declarative data of a servlet. The following table describes the elements you can define within a servlet element.

Element

Required?

Description


Required

Defines the canonical name of the servlet, used to reference the servlet definition elsewhere in the deployment descriptor.


Required

The fully-qualified class name of the servlet.


Optional

Contains a name/value pair as an initialization attribute of the servlet.

Use a separate set of tags for each attribute.


Optional

Server initializes this servlet when Server starts up. The optional content of this element must be a positive integer indicating the order in which the servlet should be loaded. Lower integers are loaded before higher integers. If no value is specified, or if the value specified is not a positive integer, Server can load the servlet in any order during application startup.

The servlet-mapping element defines a mapping between a servlet and a URL pattern.

Element

Required?

Description


Required

The name of the servlet to which you are mapping a URL pattern. This name corresponds to the name you assigned a servlet in a declaration tag.


Required

Describes a pattern used to resolve URLs. The portion of the URL after the http://host:port + WebAppName is compared to the by Server. If the patterns match, the servlet mapped in this element will be called.


Q9. If we call the destroy() from service(), does that mean the servlet would be destroyed?

Ans: No, Its just like a any other method call from within service(). However your Servlet
may not function as expected if we do this.

Q10. doGet () and doPost () are overridden from HttpServlet true | false?

Ans:
True.

Q11. If the same URL point to 2 servlets which one would be called? OR both would be called? Tell me the order?

Ans: Only one Servlet would be called. The servlet which is mapped last would be called.

Q12. Is it mandatory that servlet should have default argument constructor, why?

Ans:
Yes, because container uses that to instantiate a servlet.

Q13. If you can define servlet constructor then why would you override init() method?

Ans:
You can not access the ServletContext and ServletConfig objects within the constructor. If you need some init parameter and some context parameter, you need to override init.

Q14. What is singlethread model in servlets?

Ans: Single thread model enables one request at a time to execute the servlet. It's up to the servlet container, which strategy it would use to do so. E.g. container can make one servlet instance per request or it can synchronize the access to service method. Whichever strategy the server follows, We simply do this by implementing the SingleThreadModel interface to our Servlet.

Q15. Can you synchronize the service() method?

Ans:
Yes we can.

Q16. If you can synchronize the service() method then would you do that or implement single thread model? Why?

Ans: Implement single thread model, this would help us to achieve the most optimum approach doing this the servlet container way.

Q17. Are servlets multi-threaded?

Ans:
Yes, Servlets are multithreaded. Each request executes the service method of the same instance.

Q18. Why we use SingleThreadedModel then if servlets are multi-threaded?

Ans: If the servlets have thread safety issues, because of some instance level variables/shared objects being used and updated by the parallel requests, we would use the single thread model to achieve the thread safety across multiple parallel requests.

Q19. We always say that request executes the service() method of servlet, however we always implement doGet() or doPost(). Then how do these methods get called?

Ans:
The container always invokes the service() method of a servlet.
depending upon the request method doGet or doPost are called from within service() method.

Q20. Difference between Get and Post

Ans:
Get request is throught URL the parametes are passed in a query string,
the URL size can not exceed 1K whereas there is no such limitation on POST.
Default request method is GET. There is no difference between the 2 in terms of performance.


Q21. What are init parameters? Where do you define them?
Ans: Init parameters are used to pass default initializations/configurations values to the servlet.
e.g. you may want to pass the database username and password information to a servlet or a file name and path etc.
We define them in web.xml. They are of 2 types. Servlet Init Parameters and context parameters. Servlet Init Parameters are available only to the servlet for which they have been defined.context init paramters are available to all the servlets.
If we want to use the same set of parmeters for 2 or more servlets we define them as context init parameters.


Q22. What if I give the same name to 2 init parameters would this be error?

Ans:
No this is not an error, we would get the value of the init parameter defined last in the order.

Q23. How would you fetch init parameters in servlets?

Ans: We fetch the Servlet specific init parameters through ServletConfig.getInitParameter(String paramname) and context init paramters through ServletContext.getInitParameter(String paramname)
The init parameter name should be unique in the Servlets. If 2 init parameter names are not unique, the servlet would pick the value of the init parameter defined last in web.xml.

Q24. Can I fetch Init parameters in servlet constructor?

Ans:
No, we don't have the Servlet config reference in servlet constructor.

Q25. What is servlets pre-initialization?

Ans:
Before any request can hit the service method, We may require some setup/initializations in the servlet. e.g. you may want to open the database connection, some datafile or load some cache before the servlet is ready for request handling. To do this we override the init() method of the servlet. The servlet container would call the init before the servlet go into service ready state.
By default the servlet life cycle kicks in when first request is recieved by the servlet, Servlet instantiates and then init is called. untill init is not successfull, each request for the servlet will have to wait.
You may want to intialize the servlet as soon as the webapplication starts or the servle container starts, This can be done if we define the <load-on-startup> for <servlet> in web.xml.
Preinitializing the servlet along with the container is called servlet the pre-intialization.

My Favourite Books :

Core Java: Programmer's Guide to Java Certification : A Comprehensive Primer (Second Edition) by Mughal and Rasmussen

I am very big fan of this book, this is a must have book if you want to explore the core of java in detail.

I recently discovered that the Authors are coming up with their next book called Java Actually : A first course in programming

Table of Contents can been seen at http://www.ii.uib.no/~khalid/jact/toc.html
The TOC looks very good.

Servlets: Java Servlet Programming by Jason Hunter and Head First Servlets & JSP are my all time favourite for servlets.


Monday 19 March 2007

Eclipse Tutorial

This is a very good Eclipse Tutorial.

http://jonah.cs.elon.edu/dpowell2/Courses/EclipseTutorial/EclipseTutorial.htm


I was constantly looking for a decent tutorial which could demonstrate me the basic things step by step and brief me the details.

You would find so many screen shot demonstrations in html pages

But video tutorials are generally paid. This link is absolutely free and very good.

Enjoy it n have Fun J