Friday, December 28, 2012

Struts Interview Questions


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" />

No comments:

Post a Comment