Tuesday, September 25, 2012

Servlet Interview Questions - Part 2

As a continuation to the part 1 of questions on Servlets that we covered in this blog sometime ago, below are some more questions on Servlets. Hope you find them useful...

1. What are the new features added to Servlet 2.5?

Following are the new features introduced in Servlet 2.5:
• A new dependency on J2SE 5.0
• Support for annotations
• Loading the class
• Several web.xml conveniences
• A handful of removed restrictions
• Some edge case clarifications

2. What are the phases of the servlet life cycle?

The life cycle of a servlet consists of the following phases:
i. Servlet class loading - For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.
ii. Servlet instantiation - After loading, it instantiates one or more object instances of the servlet class to service the client requests.
iii. Initialization (call the init method) - After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.
iv. Request handling (call the service method) - After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
v. Removal from service (call the destroy method) - A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection

The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

3. Why do we need a constructor in a servlet if we use the init method?

Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet).

Let us say in a plain java class, you created an init method that gets invoked under some condition, will you be able to invoke it without actually instantiating your class? That is why we need a constructor even for a Servlet.

4. When is the servlet loaded?

A servlet can be loaded when:
First request is made.
Server starts up (auto-load).
There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
Administrator manually loads.

5. When is a Servlet unloaded?

A servlet is unloaded when:
Server shuts down.
Administrator manually unloads.

6. What is the GenericServlet class?

GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.

Note: This class is known as generic servlet, since it is not specific to any protocol whereas the HttpServlet is specific to the Http Protocol

7. Why is the HttpServlet class declared abstract?

The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. Just like any other abstract class, the HttpServlet is a partial skeleton which defines basic behavior and then gives the programmer the freedom to implement any of the other possible features he/she wants.

The simplest example here could be the fact that, any HttpServlet could handle multiple doXXX() methods as we call them which include doGet(), doPost() etc. So, in your applications, if you handle just the POST requests, then you need not implement a doGet() to override the default doGet() implementation.

8. Can a servlet have a constructor?

Sure Yes. Though we don’t explicitly call the constructor using the new() operator, the container internally invokes the Servlet class’ container when the servlet is initialized.

9. Should I override the service() method while using the HttpServlet?

We never override the service method, since the HTTP Servlets have already taken care of it. The default service function invokes the doXXX() method corresponding to the method of the HTTP request. For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method checks the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.

10. What are the differences between the ServletConfig interface and the ServletContext interface?

The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. There is only one ServletConfig parameter per servlet. The param-value pairs for ServletConfig object are specified in the < init-param > within the < servlet > tags in the web.xml file

A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container. There is one ServletContext for the entire webapp and all the servlets in a webapp share it. The param-value pairs for ServletContext object are specified in the < context-param > tags in the web.xml file.

11.What are the differences between forward() and sendRedirect() methods?

Some key differences between the two methods are:

a. A Forward is performed internally by the servlet whereas a redirect is a two-step process where the web application instructs the web browser to fetch a second/different URL
b. The browser and the user is completely unaware that a forward has taken place (The URL Remains intact) whereas in case of redirect, both the browser and the user will be made aware of the action including a change to the URL
c. The resource to which control is being forwarded has to be part of the same context as the one that is actually calling it whereas in case of redirect this is not a restriction.
d. Forwards are faster than redirects. Redirects are slower because it is actually handling two browser requests in place of forward’s one.

12. What are the difference between the include() and forward() methods?

The key differences between the two methods are:

a. The include() method inserts the contents of the specified resource directly into the flow of the servlet response, as if it were part of the calling servlet, whereas the forward() is used to show a different resource in place of the servlet that was originally called
b. The include() is often used to include common text or template markup that may be included in many servlets whereas forward() is often used where a servlet plays the role of a controller, processes some input and decides the outcome by returning a particular page response where control is transferred to a different resource

13. What is the use of the servlet wrapper classes?

The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behavior is to pass all method calls directly to the underlying objects.

14. What is a deployment descriptor?

A deployment descriptor is an XML document. It defines a component's deployment settings. It declares transaction attributes and security authorization for an enterprise bean. The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
The Java EE server reads the deployment descriptor at run time and acts upon the components accordingly.

15. What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root, whereas, the getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept relative paths. All path must start with a “/” and are interpreted as relative to current context root.

16. What is the < load-on-startup > element of the deployment descriptor?

The element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. This setting by which a servlet is loaded even before it gets its first request is called pre-initialization of a servlet. It is also used to specify the order in which the files are to be loaded. The container will load the servlets in the order specified in this element.

17. What is servlet lazy loading?

Lazy servlet loading means – the container does not initialize the servlets as soon as it starts up. Instead it initializes servlets when they receive their first ever request. This is the standard or default behavior. If you want the container to load your servlet at start-up then use pre-initialization using the load-on-startup element in the deployment descriptor.

18. What is Servlet Chaining?

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

19. What are filters?

Filters are Java components that are used to intercept an incoming request to a Web resource or the response that is sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are:
Security checks
Modifying the request or response
Data compression
Logging and auditing
Response compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.

20. What are the functions of the Servlet container?

The functions of the Servlet container are as follows:
a. Lifecycle management: It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
b. Communication support: It handles the communication between the servlet and the Web server.
c. Multithreading support: It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
d. Declarative security: It manages the security inside the XML deployment descriptor file.
e. JSP support: The container is responsible for converting JSPs to servlets and for maintaining them.

If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Servlets that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

Saturday, September 15, 2012

Struts Interview Questions


The following are some common questions that you may encounter about the Struts Framework in Java/J2EE Technical Interviews. Struts is one of the most commonly used and popular frameworks that organizations use to develop large enterprise class applications. So, it is easily possible that when you are attending a job interview as a Java/J2EE Programmer/Lead, questions about the Struts Framework invariably pops up...

The following are some questions that can help you refresh your memory about the Struts Framework.

1. What is Struts framework?

Struts framework is an open-source framework use for developing the web applications in Java EE, based on the MVC-2 architecture. It uses and extends the Java Servlet API. Struts is a robust architecture and can be used for the development of applications of any size. Struts framework makes it much easier to design scalable and reliable Web applications with Java.

2. What design patterns are used in Struts?

Struts is based on model 2 MVC (Model-View-Controller) architecture.

Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern.

Struts also implement the following J2EE design patterns.
a. Service to Worker
b. Dispatcher View
c. Composite View (Struts Tiles)
d. Front Controller
e. View Helper
f. Synchronizer Token

An important point to note here is that, not all of these patterns may be used in every Struts based application and you may not require to remember all of these patterns. If you know that Struts is based on the MVC Framework, that is more than sufficient.

3. What is the MVC Framework?

MVC Stands for Model View Controller Framework

Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.

Model - The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.

View - The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.

Controller - The controller reacts to the user input. It creates and sets the model.

4. What are the components of a Struts based application?

Struts components can be categorize into Model, View and Controller:

Model - Components like business logic /business processes and data are the part of model.

View - HTML, JSP are the view components.

Controller - Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

5. What is the ActionServlet?

The ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request.

It serves as an Action factory – creating specific Action classes based on user’s request.

6. What is the role of an ActionServlet?

ActionServlet performs the role of Controller. It does the following:

a. Process user requests
b. Determine what the user is trying to achieve according to the request
c. Pull data from the model (if necessary) to be given to the appropriate view,
d. Select the proper view to respond to the user
e. Delegates most of this grunt work to Action classes
f. Is responsible for initialization and clean-up of resources

7. What is the ActionForm?

ActionForm is a javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

8. What are the important methods of ActionForm?

The important methods of ActionForm are : validate() & reset().

9. Describe the validate() and reset() methods of the ActionForm?

The validate() method is used to validate properties after they have been populated (In the JSP). It is called before FormBean is handed over to the Action. It returns a collection of ActionError objects as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

The reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set. Following is the method signature of the reset() method.

public void reset() {}

10. What is ActionMapping?

The Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is over.

For ex: You enter your credentials in the login page of your bank's internet banking website and then hit the "Login" button. How would the system know what to do next? It refers to the ActionMappings to find out what to do next based on the action chosen by the user.


11. How is the Action Mapping specified ?

We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from configuration element of struts-config.xml file



< action-mappings >
< action path="/submit" type="submit.SubmitAction" name="submitForm" input="/submit.jsp" scope="request" validate="true" >
< forward name="success" path="/success.jsp" / >
< forward name="failure" path="/error.jsp" / >
< / action >
< / action-mappings >



12. What is role of Action Class?

An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

Practically speaking, this class contains all the logic of what to do in response to the user action. Remember the login to banks website example I gave a couple of questions back, the system actually goes to the Action class corresponding to your action (Login) to try to figure out what needs to be done next.

13. In which method of Action class the business logic is executed ?

In the execute() method of Action class the business logic is executed. It performs the processing required to deal with this request, updates the server-side objects (Scope variables) that will be used to create the next page of the user interface and returns an appropriate ActionForward object

14. Can you give me a sample code for this execute method's Signature?


public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;



15. Can we have more than one struts-config.xml file for a single Struts application?

A lot of people think that having multiple struts config files isnt possible for a single application but the truth is, it is very well possible. Unfortunately, in most real life scenarios, we would be using only one struts config file even though we can have many.

16. How would you configure your application to have multiple struts config files?

They can be configured as follows in your web.xml file:



< servlet >
< servlet-name > action < / servlet-name >
< servlet-class >
org.apache.struts.action.ActionServlet
< / servlet-class >
< init-param >
< param-name > config < / param-name > < param-value > /WEB-INF/struts-config.xml, /WEB-INF/struts-admin.xml, /WEB-INF/struts-config-forms.xml < / param-value > < / init-param >
.....
< servlet >



17. What is the difference between session scope and request scope when saving the formbean in struts?

When the scope is request,the values of formbean would be available for the current request. Whereas, when the scope is session, the values of formbean would be available throughout the session.


18. What are the different kinds of actions in Struts?

The different kinds of actions in Struts are:
ForwardAction
IncludeAction
DispatchAction
LookupDispatchAction
SwitchAction

19. What is DispatchAction?

The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

20. How will you use the DispatchAction?

To use the DispatchAction, follow these steps :
1. Create a class that extends DispatchAction (instead of Action)
2. In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
3. Do not override execute() method – Because DispatchAction class itself provides execute() method.
4. Add an entry to struts-config.xml


21. When would you use the ForwardAction?

The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.


22. When would you use the IncludeAction?

The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

23. What is the difference between ForwardAction and IncludeAction?

The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page.

24. What is LookupDispatchAction?

The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.

25. When would you use LookupDispatchAction?

LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. This is typically useful when you create something that will be shared across different locales. For ex: The login page of an international banks website would look surprisingly similar in almost all countries. It does the same thing in all countries but what exactly happens after you finish the login depends on the country you are. So, this is the kind if scenario where LookupDispatchAction would come in handy.

26. What is difference between LookupDispatchAction and DispatchAction?

The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

27. What is SwitchAction?

The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application.

28. What if element has declaration with same name as global forward?

In this case the global forward is not used. Instead the element’s takes precendence.

29. What is DynaActionForm?

DynaActionForm is a specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean. Since the developer need not create actual bean java classes, a lot of developers prefer DynaActionForms.

30. What are the steps need to use DynaActionForm?

Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places:

First in the struts-config.xml: change your to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm.

Example:


< form-bean name="loginForm"type="org.apache.struts.action.DynaActionForm" >
< form-property name="userName" type="java.lang.String" / >
< form-property name="password" type="java.lang.String" / >
< / form-bean >


Second - In your Action subclass that uses your form bean:

1. import org.apache.struts.action.DynaActionForm
2. downcast the ActionForm parameter in execute() to a DynaActionForm
3. access the form fields with get(field) rather than getField()

Example:


......

public class DynaActionFormExample extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
ActionMessages errors = new ActionMessages();
if (((String) loginForm.get("userName")).equals("")) {
errors.add("userName", new ActionMessage(
"error.userName.required"));
}
if (((String) loginForm.get("password")).equals("")) {
errors.add("password", new ActionMessage(
"error.password.required"));
}
...........


31. How would you display validation errors on jsp page in a Struts Application?

tag displays all the errors. iterates over ActionErrors request attribute. Remember the ActionErrors that get created while using the validate() method? See Question No. 9 if you dont remember...


32. What are the various Struts tag libraries?

The various Struts tag libraries are:
1. HTML Tags
2. Bean Tags
3. Logic Tags
4. Template Tags
5. Nested Tags
6. Tiles Tags

33. What is the use of ?

repeats the nested body content of this tag over a specified collection.

example:



< table border=1 >
< logic:iterate id="customer" name="customers" >
< tr >
< td > < bean:write name="customer" property="firstName" / > < / td >
< td > < bean:write name="customer" property="lastName" / > < / td >
< td > < bean:write name="customer" property="address" / > < / td>
< / tr >
< / logic:iterate >
< / table>



34. What are differences between < bean:message > and < bean:write >?

< bean:message >: is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string.

< bean:message key="prompt.customer.firstname" / >


< bean:write >: is used to retrieve and print the value of the bean property. < bean:write > has no body.

< bean:write name="customer" property="firstName" / >


35. How the exceptions are handled in struts?

Exceptions in Struts are handled in two ways:
1. Programmatic exception handling - Using explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed when error occurs.

2. Declarative exception handling - You can either define handling tags in your struts-config.xml or define the exception handling tags within tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.

36. Can you give an example of Programmatic Exception Handling?


< global-exceptions >
< exception key="some.key" type="java.lang.NullPointerException" path="/WEB-INF/errors/null.jsp" / >
< / global-exceptions >


37. Can you give an example of declarative exception handling?


< exception key="some.key" type="package.SomeException" path="/WEB-INF/somepage.jsp" / >



38. What are some benefits of using DynaActionForm?

The biggest advantage is that - we need not create multiple classes to hold form information. We can just declare forms as and when required inside the struts-config.xml file and we are good to go.

39. Can you think of any drawbacks of the DynaActionForm?

Of Course. Every coin has two sides. Some drawbacks of using DynaActionForm could be:

1. The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger and the config file in itself could become unmanageable
2. The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
3. ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.


40. How can we make message resources definitions file available to the Struts framework environment?

We can make message resources definitions file (properties file) available to Struts framework environment by adding this file to struts-config.xml.

< message-resources parameter="com.login.struts.ApplicationResources" / >

If you want to add more questions to this list or if you wish to have any question answered, leave a comment in this page or drop a note to anandvijayakumar007@gmail.com
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers