Thursday 3 May 2007

Struts 1.3 Tutorial.

The previous article gave you the brief outline over how the request is processed within the struts framework. I demonstrated the 5 basic steps. I would now elaborate the entire process with more in-depth details.

The ActionServlet (Our controller)

ActionServlet is the only servlet in entire Struts framework, and is responsible for handling all of the requests. It delegates most of this grunt work to the Request Processor and Action classes. When the controller initializes, it first loads the application config corresponding to the "config" init-param.

<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>

we generally keep the name struts-config.xml and place it within folder WEB-INF. however you may change its name or location .e.g in my application i may
keep the xml within WEB-INF/config folder with the name app-config.xml in that case the path would be like

<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/config/app-config.xml</param-value>
</init-param>


If there are multiple modules then each is identified by the init-param config/modulename e.g. config/foo. For each of these elements, the framework loads the configuration file specified by the value of that init-param. e.g in this case the controller would load /WEB-INF/foo/struts-config.xml for module foo.

<init-param>
<param-name>config/foo</param-name>
<param-value>/WEB-INF/foo/struts-config.xml</param-value>
</init-param>

Let us say there are 3 different modules in your application foo, zoo and hey. When a request is recieved, How the controller determines which module out of 3 will be given the control of processing the request.

To access the module foo, you would use a URL like: http://localhost:8080/myApp/foo/someAction.do
To access the module zoo, you would use a URL like: http://localhost:8080/myApp/zoo/someAction.do etc.

As soon as the request is received by the controller it analyses the the URL to figure out the module once thats done. the controller invokes that module's RequestProcessor. it calls invokes process method of the RequestProcessor. We would discuss the RequestProcessor next in detail.

One last thing about ActionServlet, what do you think about the <load-on-startup> property ? don't you think it should be there?

Yes!!! we define the <load-on-startup>1</load-on-startup> (some valid int value) so that the ActionServlet is initialized along with the container.

Monday 30 April 2007

Struts Request Processing illustration, the first sight...

The following Figure shows how a request flows through the Struts framework. Follow step by step....

Step 1. The request calls the ActionServlet with a certain logical input form name.

Step 2. This logical form name is then resolved according to mapping entries defined in action.xml. This file contains the mapping that defines which Struts components are associated with which logical form.

Once the mapping is resolved, the ActionServlet will look in the session for the ActionForm class associated with the request. If such a class is located in the session, the ActionForm attributes are populated by calling the corresponding setter methods. However, if the ActionForm is not located in the session, a new instance is created and added to the user’s session. Subsequently, the reset method is called on the action form and the ActionForm attributes are populated.

Step 3/4. Next, the ActionServlet calls the validate method on the ActionForm. The validate method returns either null (indicating success) or an array of errors (indicating an error condition). If the ActionForm’s validate method returns an array of errors, the ActionServlet populates the requesting input form and displays the errors to the user. we can disable the call to this method if we define validate=false in struts config file. we can disable the validate for all the action forms if we define init parameter validate with value false in web.xml for ActionServlet(Controller).

Step 5. Once the validate method returns null, the ActionServlet will instantiate an instance of ActionClass (if one does not already exist) as indicated by the mapping in action.xml. The ActionClass execute method is then invoked by ActionServlet. The execute method is responsible for processing the request.

Step 6. The execute method is required to return an ActionForward instance. This instance indicates to the ActionServlet which JSP (if any) to forward the request off to for rendering of the presentation.

Step 7. The JSP is responsible for generating the appropriate response based on the results of executing the execute method. In Struts, an ActionForm bean has only one purpose -- to represent the last input state of all the user's entries on a particular form. the ActionForms are also called the transfer objects between the controller and the Views because they carry the values from controller (Action) to the Views (Jsp).
That way, the framework can easily redisplay the last input screen (plus some error messages) pre-populated with what the user last entered, which is what anyone who has ever used a GUI application expects.

May be the request processing seems to be complex at first sight, but once you are acquinted with it...it would put you one the drive!!!!. Enjoy Struts!!!!!

Struts 2 : features and short summary

The strut-2 framework is designed for the compilation of the entire development cycle including of building, developing and maintaining the whole application. It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own. The basic platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.

Some of the general features of the current Apache Strut 2 framework are given below.

Architecture – First the web browser request a resource for which the Filter Dispatcher decides the suitable action. Then the Interceptors use the required functions and after that the Action method executes all the function like storing and retrieving data from a database. Then the result can be seen on the output of the browser in HTML, PDF, images or any other.

Tags - Tags in Strut 2 allow creating dynamic web application with less number of coding. Not only these tags contain output data but also provide style sheet driven markup that in turn helps in creating pages with less code. Here the tags also support validation and localization of coding that in turn offer more utilization. The less number of codes also makes it easy to read and maintain.

MVC – The Model View Controller in Strut 2 framework acts as a co-coordinator between application’s model and web view. Its Controller and View components can come together with other technology to develop the model. The framework has its library and markup tags to present the data dynamically.

Configuration – Provides a deployment descriptor to initialize resources and is in XML format. The initialization is taken place by scanning all the classes using Java packages or you can use an application configuration file to control the entire configuration. Its general-purpose defaults allow using struts directly Out of the box.

Configuration files are reloadable that allows changes without restarting a web container.

Other Features:

  • All framework classes are based on interfaces and core interfaces are independent from HTTP.
  • Check boxes do not require any kind of special application for false values.
  • Any class can be used as an action class and one can input properties by using any JavaBean directly to the action class.
  • Strut 2 actions are Spring friendly and so easy to Spring integration.
  • AZAX theme enables to make the application more dynamic.
  • Portal and servlet deployment are easy due to automatic portlet support without altering code.
  • The request handling in every action makes it easy to customize, when required.

Struts 2 History

Apache Struts is an open-source framework that is used for developing Java web application. Originally developed by the programmer and author Craig R. McClanahan this was later taken over by the Apache Software Foundation in 2002. Struts have provided an excellent framework for developing application easily by organizing JSP and Servlet basically based on HTML formats and Java code. Strut1 with all standard Java technologies and packages of Jakarta assists to create an extensible development environment. However, with the growing demand of web application, Strut 1 does not stand firm and needs to be changed with demand. This led to the creation of Strut2, which is more developer friendly with features like Ajax, rapid development and extensibility.

Strut is a well-organized framework based on MVC architecture. In Model-View-Architecture, Model stands for the business or database code, the View represents the page design code and the Controller for navigational code. All these together makes Struts an essential framework for building Java application. But with the development of new and lightweight MVC based frame works like Spring, Stripes and Tapestry, it becomes necessary to modify the Struts framework. So, the team of Apache Struts and another J2EE framework, WebWork of OpenSymphony joined hand together to develop an advanced frame works with all possible developing features that will make it developer and user friendly.

Strut2 is a combined features of Struts Ti and WebWork 2 projects that advocates higher level application by using the architecture of WebWork2 with features including a plugin framework, a new API, Ajax tags etc. So the Struts communities and the WebWork team brought together several special features in WebWork2 to make it more advance in the Open Source world. Later the name of WebWork2 has changed to Struts2. Hence, Apache Strut 2 is a dynamic, extensible framework for a complete application development from building, deploying and maintaining.

Struts 2 Architecture

Struts and webwork has joined together to develop the Struts 2 Framework. Struts 2 Framework is very extensible and elegant for the development of enterprise web application of any size. In this section we are going to explain you the architecture of Struts 2 Framework.

Request Lifecycle in Struts 2 applications

  1. User Sends request: User sends a request to the server for some resource.
  2. FilterDispatcher determines the appropriate action: The FilterDispatcher looks at the request and then determines the appropriate Action.
  3. Interceptors are applied: Interceptors configured for applying the common functionalities such as workflow, validation, file upload etc. are automatically applied to the request.
  4. Execution of Action: Then the action method is executed to perform the database related operations like storing or retrieving the data from database.
  5. Output rendering: Then the Result render the output.
  6. Return of Request: Then the request returns through the interceptors in the reverse order. The returning request allows us to perform the clean-up or additional processing.
Display the result to user: Finally the control is returned to the servlet container, which sends the output to the user browser.

Struts 2 Architecture

Struts 2 is very elegant and flexible front controller framework based on many standard technologies like Java Filters, Java Beans, ResourceBundles, XML etc.

For the Model, the framework can use any data access technologies like JDBC, EJB, Hibernate etc. and for the View, the framework can be integrated with JSP, JTL, JSF, Jakarta Velocity Engine, Templates, PDF, XSLT etc.

Exception Handling:

The Struts 2 Framework allows us to define exception handlers and inceptors.

  • Exception Handlers:
    Exception handlers allows us to define the exception handling procedure on global and local basis. Framework catches the exception and then displays the page of our choice with appropriate message and exception details.
  • Interceptors:
    The Interceptors are used to specify the "request-processing lifecycle" for an action. Interceptors are configured to apply the common functionalities like workflow, validation, etc.. to the request.

Struts 2 Architecture

The following diagram depicts the architecture of Struts 2 Framework. Following diagram shows the the initial request goes to the servlet container such as tomcat, which is then passed through standard filer chain.

Image: Struts 2 Architecture

The filter chain includes:

  • Action ContextCleanUp filter:
    The ActionContextCleanUp filter is optional and it is useful when integration has to be done with other technologies like SiteMash Plugin.
  • FilterDispatcher:
    Next the FilterDispatch is called, which in turn uses the ActionMapper to determine weather to invoke an Action. If the action is required to be invoked, the FilterDispatcher delegates the control to the ActionProxy.
  • ActionProxy:
    The ActionProxy takes the help from Configuration Files manager, which is initialized from the struts.xml. Then the ActionProxy creates an ActionInvocation, which implements the command pattern. The ActionInvocation process invokes the Interceptors (if configured) and then invokes the action. The the ActionInvocation looks for proper result. Then the result is executed, which involves the rendering of JSP or templates.

    Then the Interceptors are executed again in reverse order. Finally the response returns through the filters configured in web.xml file. If the ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.

In this section we have learned about the Architecture of Struts 2 Framework.

Download Struts 2.0

In this section we will download and install the Struts 2.0 on the latest version of Tomcat container. We will first download tomcat and configure it as our development server. Then we will download Struts 2.0 and install the struts-blank application on the tomcat server server to check the examples that comes with the struts-blank application.

Downloading Struts 2.0

Visit the Struts download site http://struts.apache.org/download.cgi and download the Struts 2.0 for this tutorial.

Download the Tomcat

Download the latest version of tomcat from http://tomcat.apache.org/download-55.cgi. We have downloaded apache-tomcat-5.5.20.zip for this tutorial Extract downloaded file and run the C:\apache-tomcat-5.5.20\bin\startup.bat to start the tomcat. Type http://localhost:8080/ in your browser, it should show the welcome page in the browser window Now we will install the struts-blank application on the tomcat container and test the application.

Extracting Struts 2.0 distribution and installing on tomcat

Extract the downloaded struts distribution struts-2.0.6-all.zip into your favorite directory. To install the struts blank application copy "struts2-blank-2.0.6" from "\struts-2.0.6-all\struts-2.0.6\apps" into the webapps directory of tomcat. Tomcat will automatically deploy the application



Feb 25, 2007 11:42:23 PM org.apache.coyote.http11.Http11BaseProtocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Feb 25, 2007 11:42:24 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Feb 25, 2007 11:42:24 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/141 config=null
Feb 25, 2007 11:42:24 PM org.apache.catalina.storeconfig.StoreLoader load
INFO: Find registry server-registry.xml at classpath resource
Feb 25, 2007 11:42:24 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 6672 ms
Feb 25, 2007 11:52:55 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive struts2-blank-2.0.6.war

To test the struts-blank application type http://localhost:8080/struts2-blank-2.0.6 in the browser and the struts-blank application get displayed in your browser window.


Click the English link and familiarize yourself with Struts Blank sample application.

Struts 2.0 distribution also contains the following samples applications that you can try:

  • struts2-mailreader-2.0.6.war
  • struts2-portlet-2.0.6.war
  • struts2-showcase-2.0.6.war

You can simply copy these files to the webapps directory of your tomcat server. Tomcat will automatically deploy these application and then you can test these applications.

Sunday 29 April 2007

Sun Certified Java Programmer (SCJP) Free Mock exams

List of 40+ Free sites, Where core java mock exams are free online. These sites can help individuals in preparing for Sun Certified Java Programmer (SCJP) exam and the core java interview questions.

If you want to revise your java skills before taking these mock exams , then go to jchq essentials first. Please follow the link.....

http://www.jchq.net/essentials/index.htm#full

And here goes the site lists..... cheers guys!!!!


  1. Sun's sample questions:
  2. Java Ranch Rules Round Up Game: 36 questions. Basic questions, but important for certification.
  3. Jaworski: Java quiz with answers. Very useful
  4. Robert and Heller's Online Self Test: 10 questions.
  5. Absolute Java's Test Your Java Knowledge: 17 questions on variety of topics
  6. Java Prepare Questions: 59 questions.
  7. John Hunt Mock exam: 65 questions, Simple
  8. Java Caps Mock exam: 60 questions with answers
  9. Marcus Green mock exam - 1: 60 questions.
  10. Marcus Green mock exam - 2: 60 questions. Highly recommended
  11. Marcus Green mock exam - 3: 60 questions.
  12. MindQ exam: Good one.
  13. Majji exam: 30 questions, Very good.
  14. Amit Poddar's questions: 42 questions, related to Strings, Components and Layouts and Math class
  15. IBM online exam tool: 30 questions
  16. Barry Boone Exam: 70 questions.
  17. Bill Brogden exam: Random 18 from 38 questions.
  18. Bill Brogden's Hardest questions: 19 questions, If you want to waste your time
  19. Jxam: 59 from 200 questions.
  20. Sarga's Jargon Exam: 60 questions from 140 questions.
  21. JQuest Exam simulator: 30 from 90 questions.
  22. JDcert: 66 questions, Simple
  23. Deepak exam site: 250 questions.
  24. Applied Reasoning Exam: 77 questions, generated from a pool of 200 questions.
  25. Boris's Exam Simulator: 40 questions from 64 questions.
  26. Abhilash's Quiz: 80 questions with answers.
  27. Java Exam Simulation - Test 1: 30 questions.
  28. Java Exam Simulation - Test 2: 59 questions.
  29. Java Exam Simulation - Test 3: 59 questions.
  30. Java Exam Simulation - Test 4: 59 questions.
  31. Java Exam Simulation - Test 5: 128 questions.
  32. Exam Cram Pratice Exam 34 questions.
  33. 4tests.com's Java Exam: 40 questions.
  34. JvalTest Exam Applet: 60 questions.
  35. Mughal Khalid's Exam Simulator: 60 questions,
    Tough in comparison to the actual certification exam.
  36. JWhizTrial Exam
    These are sample questions from the actual software. Need to download them to your computer.
  37. Java Exam Simulator .
  38. Rahul Raje's Mock Exam Simulator : 60 questions. Needs downloading and extracting jar files
  39. http://www.go4java.20m.com/mock1.htm : 2 mock exams with 59 questions each.
  40. Web Tech Frontier : 56 Questions.
  41. Voodoo Exam by Ashish Hareet : At the time of writing this page, the mock exam has 60 questions related to SCJP.
Selected Java certification related websites: (Sorted in Alphabetical order)
About.com Java certification links
Abhinav Gupta's Guide to Certification
Amit Verma's Certification Page
Ashok Kumar's Java section
Bill Brogden's Java Resources
Chitra Sridhar's Java Site
Certify in Java Resources
Deepak's Certification Page
Dave's Java Site
Dasari's Java Certification Page
Javaranch
Java Prepare
Jyothi Krishnan's Java Page
Java Caps
Jxam Homepage
Java China Page
Java Certified Programmer Resources
Valiveru's Homepage
Java Skinny
Kaan
Levteck Java site
Maha Anna's Java Home page
Marcus Green Certification Headquarter
Michael Thomas Java Certification and Training Page
Mukherjee's Java Page
Moogly-googly
Sun Certification Site
Tony Alicea's Java Page
Usha Kasiram SCJP Resources

I recently found the following site having similar SCJP Mock exams links. Have a look if you find some useful or new stuff.
http://www.javacertificationexams.com/scjp-mock-exams.php

Secrets Of The Masters: Core Java Job Interview Questions.
JDJ Enterprise Editor Yakov Fain Offers 30 Core Java Questions You Might Expect During Job Interviews. Good 20 ones in the list anyways.

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