Interview Questions

  • Uploaded by: Gopinath
  • 0
  • 0
  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Interview Questions as PDF for free.

More details

  • Words: 31,850
  • Pages: 92
JSP Interview Questions 1.What are the advantages of JSP over Servlet? JSP is a serverside technology to make content generation a simple appear.The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development. 2.What is the life-cycle of JSP? When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests. A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence: • Translation • Compilation • Loading the class • Instantiating the class • jspInit() invocation • _jspService() invocation • jspDestroy() invocation 3.What is the jspInit() method? The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data. 4.What is the _jspService() method? The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container. 5.What is the jspDestroy() method? The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection. 6.What JSP lifecycle methods can I override? You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

7.How can I override the jspInit() and jspDestroy() methods within a JSP page? The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:

<%! public void jspInit() { . . . } %> <%! public void jspDestroy() { . . . } %> 8.What are implicit objects in JSP? Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects.The implicit objects available in JSP are as follows: • • • • • • • • •

request response pageContext session application out config page exception

The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration. 9.What are JSP directives?

• JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page • They are used to set global values such as a class declaration, method implementation, output content type, etc. • They do not produce any output to the client. • Directives are always enclosed within <%@ ….. %> tag. • Ex: page directive, include directive, etc. 10.What is page directive? • A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment. • Typically, the page directive is found at the top of almost all of our JSP pages. • There can be any number of page directives within a JSP page (although the attribute – value pair must be unique). • The syntax of the include directive is: <%@ page attribute="value">

• Example:<%@ include file="header.jsp" %>

11.What are the attributes of page directive? There are thirteen attributes defined for a page directive of which the important attributes are as follows:

• • • •

import: It specifies the packages that are to be imported. session: It specifies whether a session data is available to the JSP page. contentType: It allows a user to set the content-type for a page. isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.

12.What are the different types of JSP tags? The different types of JSP tags are as follows:

13.What is the include directive? There are thirteen attributes defined for a page directive of which the important attributes are as follows: • The include directive is used to statically insert the contents of a resource into the current JSP. • This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time. • The syntax of the include directive is as follows: <%@ include file = "FileName" %>

• This directive has only one attribute called file that specifies the name of the file to be included. 14.What are the JSP standard actions? • The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client. • They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc. • Ex: include, forward, useBean,etc. object

15.What are the standard actions available in JSP? The standard actions available in JSP are as follows:

• <jsp:include>: It includes a response from a servlet or a JSP page into the current page. It differs from • • • • • •

an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time. <jsp:forward>: It forwards a response from a servlet or a JSP page to another page. <jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean. <jsp:setProperty>: It sets the properties for a JavaBean. <jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the response. <jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs. <jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.

16.What is the <jsp:useBean> standard action? The <jsp:useBean> standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type. 17.What are the scopes available in <jsp:useBean>? The scopes available in <jsp:useBean> are as follows:

• page scope:: It specifies that the object will be available for the entire JSP page but not outside the • • •

page. request scope: It specifies that the object will be associated with a particular request and exist as long as the request exists. application scope: It specifies that the object will be available throughout the entire Web application but not outside the application. session scope: It specifies that the object will be available throughout the session with a particular client.

18.What is the <jsp:forward> standard action?

• The <jsp:forward> standard action forwards a response from a servlet or a JSP page to another page. • The execution of the current page is stopped and control is transferred to the forwarded page. • The syntax of the <jsp:forward> standard action is : <jsp:forward page="/targetPage" /> Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context.

• If anything is written to the output stream that is not buffered before <jsp:forward>, an IllegalStateException will be thrown. Note : Whenever we intend to use <jsp:forward> or <jsp:include> in a page, buffering should be enabled. By default buffer is enabled.

19.What is the <jsp:include> standard action? The <jsp:include> standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.The syntax of the <jsp:include> standard action is as follows: <jsp:include page="targetPage" flush="true"/> Here, targetPage is the page to be included in the current JSP. 20.What is the difference between include directive and include action?

Include directive The include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet.

Include action The include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user.

The include standard action enables the current The include directive is used to statically insert the JSP page to include a static or a dynamic contents of a resource into the current JSP. resource at runtime. Use the include action only for content that Use the include directive if the file changes rarely. changes often, and if which page to include It’s the fastest mechanism. cannot be decided until the main page is requested. 21.Differentiate between pageContext.include and jsp:include? The <jsp:include> standard action and the pageContext.include() method are both used to include resources at runtime. However, the pageContext.include()method always flushes the output of the current page before including the other components, whereas<jsp:include> flushes the output of the current page only if the value of flush is explicitly set to true as follows: <jsp:include page="/index.jsp" flush="true"/> 22.What is the jsp:setProperty action? You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:

<jsp:useBean id="myName" ... /> ... <jsp:setProperty name="myName" property="myProperty" ... /> In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found. A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below: <jsp:useBean id="myName" ... > ... <jsp:setProperty name="myNam" property="someProperty" ... />

Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.

23.What is the jsp:getProperty action? The <jsp:getProperty> action is used to access the properties of a bean that was set using the <jsp:getProperty> action. The container converts the property to a String as follows: • If it is an object, it uses the toString() method to convert it to a String. • If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class. • The syntax of the <jsp:getProperty> method is: <jsp:getProperty name="Name" property="Property" /> Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the <jsp:useBean> action before using the <jsp:getProperty> action. 24.What is the <jsp:param> standard action? The <jsp:param> standard action is used with <jsp:include> or <jsp:forward> to pass parameter names and values to the target resource. The syntax of the <jsp:param> standard action is as follows: <jsp:param name="paramName" value="paramValue"/> 25.What is the jsp:plugin action ? This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin. 26.What are scripting elements? JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:

1. Expressions of the form <%= expression %> that are evaluated and inserted into the output, 2. Scriptlets of the form <% code %> that are inserted into the servlet's service method, 3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods. 27.What is a scriptlet? A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a servlet, the scriptlet code goes into the service()method. Hence, methods and variables written in scriptlets are local to theservice() method. A scriptlet is written between the <% and %> tags and is executed by the container at request processing time. 28.What are JSP declarations? As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not included in the service()method when a JSP is translated to a servlet.

29.What is a JSP expression? A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the <%= and %> tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags. 30.How is scripting disabled? Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows: <jsp-property-group> *.jsp <scripting-invalid>true

Struts Interview Questions 1.What is MVC? 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.

2.What is a framework? A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement. 3.What is Struts framework? Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. 4.What are the components of Struts? 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 are the core classes of the Struts Framework? Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. • JavaBeans components for managing application state and behavior. • Event-driven development (via listeners as in traditional GUI development). • Pages that represent MVC-style views; pages reference view roots via the JSF component tree. 6.What is ActionServlet? 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. 7.What is role of ActionServlet? ActionServlet performs the role of Controller:

• Process user requests • • • • •

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

8.What is the ActionForm? ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean. 9.What are the important methods of ActionForm? The important methods of ActionForm are : validate() & reset(). 10.Describe validate() and reset() methods ? validate(): Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate()method.

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) reset(): 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.

public void reset() {} 11.What is ActionMapping? 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 complete. 12.How is the Action Mapping specified ?

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

13.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. 14.In which method of Action class the business logic is executed ? In the execute()method of Action class the business logic is executed.

public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception ; execute() method of Action class: • Perform the processing required to deal with this request • Update the server-side objects (Scope variables) that will be used to create the next page of the user interface • Return an appropriate ActionForward object 15.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. • Service to Worker • Dispatcher View

• • • •

Composite View (Struts Tiles) Front Controller View Helper Synchronizer Token

16.Can we have more than one struts-config.xml file for a single Struts application? Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:

<servlet> <servlet-name>action <servlet-class> org.apache.struts.action.ActionServlet <param-name>config <param-value> /WEB-INF/struts-config.xml, /WEB-INF/struts-admin.xml, /WEB-INF/struts-config-forms.xml ..... <servlet> 17.What is the directory structure of Struts application? The directory structure of Struts application :

18.What is the difference between session scope and request scope when saving formbean ? when the scope is request,the values of formbean would be available for the current request. when the scope is session,the values of formbean would be available throughout the session. 19.What are the important tags of struts-config.xml ? The five important sections are:

20.What are the different kinds of actions in Struts? The different kinds of actions in Struts are: • • • • •

ForwardAction IncludeAction DispatchAction LookupDispatchAction SwitchAction

21.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.

22.How to use DispatchAction? To use the DispatchAction, follow these steps : • Create a class that extends DispatchAction (instead of Action) • 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.

• Do not override execute()method – Because DispatchAction class itself provides execute()method. • Add an entry to struts-config.xml

23.What is the use of 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. 24.What is 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. 25.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. 26.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. 27.What is the use of 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. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.

28.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. 29.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. The SwitchAction class can be used as is, without extending. 30.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.

31.What is DynaActionForm? 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. 32.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:

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

• In your Action subclass that uses your form bean: • import org.apache.struts.action.DynaActionForm • downcast the ActionForm parameter in execute() to a DynaActionForm • access the form fields with get(field) rather than getField() import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.action.DynaActionForm; 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")); } 33.How to display validation errors on jsp page? tag displays all the errors.

iterates over ActionErrors request

attribute. 34.What are the various Struts tag libraries? The various Struts tag libraries are: • • • • • •

HTML Tags Bean Tags Logic Tags Template Tags Nested Tags Tiles Tags

35.What is the use of ? repeats the nested body content of this tag over a specified collection.

36.What are differences between and

: 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.

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

37.How the exceptions are handled in struts? Exceptions in Struts are handled in two ways:

• Programmatic exception handling :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.

• 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.

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

<exception key="some.key" type="package.SomeException" path="/WEB-INF/somepage.jsp"/> 38.What is difference between ActionForm and DynaActionForm?

• An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml

• The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

• 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. • ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

• ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).

• DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided. 39.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"/> 40.What is the life cycle of ActionForm? The lifecycle of ActionForm invoked by the RequestProcessor is as follows:

• Retrieve or Create Form Bean associated with Action • "Store" FormBean in appropriate scope (request or session) • Reset the properties of the FormBean • Populate the properties of the FormBean • Validate the properties of the FormBean • Pass FormBean to Action

Spring Framework Interview Questions 1) What is Spring? Spring is a lightweight inversion of control and aspect-oriented container framework.

2) Explain Spring? • Lightweight: Spring is lightweight when it comes to size and transparency. The basic

• • • •

version of spring framework is around 1MB. And the processing overhead is also very negligible. Inversion of control (IoC) : Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects. Aspect oriented (AOP) : Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services. Container: Spring contains and manages the life cycle and configuration of application objects. Framework: Spring provides most of the intra functionality leaving rest of the coding to the developer.

3) What are the different modules in Spring framework? • • • • • •



The Core container module Application context module AOP module (Aspect Oriented Programming) JDBC abstraction and DAO module O/R mapping integration module (Object/Relational) Web module MVC framework module

4) What is the Core container module? This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container.

5) What is Application context module? The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.

6) What is AOP module? The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring. Using Spring’s metadata support, we will be able to add annotations to our source code that instruct Spring on where and how to apply aspects.

7) What is JDBC abstraction and DAO module? Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a Spring application.

8) What are object/relational mapping integration module? Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.

9) What is web module? This module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.

10) What is web module? Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide for a clean separation of controller logic from business objects. It also allows you to declaratively bind request parameters to your business objects. It also can take advantage of any of Spring’s other services, such as I18N messaging and validation.

11) What is a BeanFactory? A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.

12) What is AOP Alliance? AOP Alliance is an open-source project whose goal is to promote adoption of AOP and interoperability among different AOP implementations by defining a common set of interfaces and components.

13) What is Spring configuration file? Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

14) What does a simple spring application contain? These applications are like any Java application. They are made up of several classes, each performing a specific purpose within the application. But these classes are configured and introduced to each other through an XML file. This XML file describes how to configure the classes, known as the Spring configuration file.

15) What is XMLBeanFactory? BeanFactory has many implementations in Spring. But one of the most useful one isorg.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. TheInputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory. BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml")); To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve. MyBean myBean = (MyBean) factory.getBean("myBean");

16) What are important ApplicationContext implementations in spring framework? • ClassPathXmlApplicationContext –This context loads a context definition from an XML file located in the class path, treating context definition files as class path resources.

• FileSystemXmlApplicationContext –This context loads a context definition from an XML •

file in the filesystem. XmlWebApplicationContext – This context loads the context definitions from an XML file contained within a web application.

17) Explain Bean lifecycle in Spring framework? 1. The spring container finds the bean’s definition from the XML file and instantiates the bean. 2. Using the dependency injection, spring populates all of the properties as specified in the bean definition. 3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID. 4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself. 5. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization()methods will be called. 6. If an init-method is specified for the bean, it will be called. 7. Finally, if there are any BeanPostProcessors associated with the bean, theirpostProcessAfterInitialization() methods will be called.

18) What is bean wiring? Combining together beans within the Spring container is known as bean wiring or wiring. When wiring beans, you should tell the container what beans are needed and how the container should use dependency injection to tie them together.

19) How do add a bean in spring application? In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully qualified class name.

20) What are singleton beans and how can you create prototype beans? Beans defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.

21) What are the important beans lifecycle methods? There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.

22) How can you override beans default lifecycle methods? The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods. Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.

23) What are Inner Beans? When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused anywhere else.

24) What are the different types of bean injections? There are two types of bean injections. 1. By setter 2. By constructor

24) What is Auto wiring? You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together. All you have to do is just set the autowire attribute of bean tag to an autowire type.

25) What are different types of Autowire types? There are four different types by which autowiring can be done. • • • •

byName byType constructor autodetect

26) What are the different types of events related to Listeners? There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses oforg.springframework.context.Application-Event. They are • ContextClosedEvent – This is fired when the context is closed. • ContextRefreshedEvent – This is fired when the context is initialized or refreshed. • RequestHandledEvent – This is fired when the web context handles any request.

27) What is an Aspect? An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, you can create a logging aspect and apply it throughout your application using AOP.

28) What is a Jointpoint? A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

29) What is an Advice? Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints.

30) What is a Pointcut? A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied.

31) What is an Introduction in AOP? An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing class without having to change the structure of the class, but give them the new behavior and state.

32) What is a Target? A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is being applied.

33) What is a Proxy? A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

34) What is meant by Weaving? The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into the target object at the specified joinpoints.

35) What are the different points where weaving can be applied? • Compile Time • Classload Time • Runtime

36) What are the different advice types in spring? • Around :Intercepts the calls to the target method • Before :This is called before the target method is invoked • After :This is called after the target method is returned • Throws :This is called when the target method throws and exception • • • •

Around : org.aopalliance.intercept.MethodInterceptor Before : org.springframework.aop.BeforeAdvice After : org.springframework.aop.AfterReturningAdvice Throws : org.springframework.aop.ThrowsAdvice

37) What are the different types of AutoProxying? • BeanNameAutoProxyCreator • DefaultAdvisorAutoProxyCreator • Metadata autoproxying

38) What is the Exception class related to all the exceptions that are thrown in spring applications? DataAccessException - org.springframework.dao.DataAccessException

39) What kind of exceptions those spring DAO classes throw? The spring’s DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which are subclasses of DataAccessException.

40) What is DataAccessException? DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of exceptions.

41) How can you configure a bean to get DataSource from JNDI? <property name="jndiName"> java:comp/env/jdbc/myDatasource

42) How can you create a DataSource connection pool? <property name="driver"> ${db.driver} <property name="url"> ${db.url} <property name="username"> ${db.username} <property name="password"> ${db.password}

43) How JDBC can be used more efficiently in spring framework? JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate.

44) How JdbcTemplate can be used? With use of Spring JDBC framework the burden of resource management and error handling is reduced a lot. So it leaves developers to write the statements and queries to get the data to and from the database. JdbcTemplate template = new JdbcTemplate(myDataSource); A simple DAO class looks like this. public class StudentDaoJdbc implements StudentDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } more.. } The configuration is shown below. <property name="dataSource">

<property name="jdbcTemplate">
<property name="jdbcTemplate">

45) How do you write data to backend in spring using JdbcTemplate? The JdbcTemplate uses several of these callbacks when writing data to the database. The usefulness you will find in each of these interfaces will vary. There are two simple interfaces. One is PreparedStatementCreator and the other interface is BatchPreparedStatementSetter.

46) Explain about PreparedStatementCreator? PreparedStatementCreator is one of the most common used interfaces for writing data to database. The interface has one method createPreparedStatement(). PreparedStatement createPreparedStatement(Connection conn) throws SQLException; When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.

47) Explain about BatchPreparedStatementSetter? If the user what to update more than one row at a shot then he can go for BatchPreparedStatementSetter. This interface provides two methods setValues(PreparedStatement ps, int i) throws SQLException; int getBatchSize(); The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times setValues() will be called.

48) Explain about RowCallbackHandler and why it is used? In order to navigate through the records we generally go for ResultSet. But spring provides an interface that handles this entire burden and leaves the user to decide what to do with each row. The interface provided by spring isRowCallbackHandler. There is a method processRow() which needs to be implemented so that it is applicable for each and everyrow. void processRow(java.sql.ResultSet rs);

Questions are downloaded from: http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php 1. What is IOC (or Dependency Injection)? The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects. 2. What are the different types of IOC (dependency injection) ? There are three types of dependency injection:

• Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor • •

parameters. Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods). Interface Injection (e.g. Avalon): Injection is done through an interface. Note: Spring supports only Constructor and Setter Injection

3. What are the benefits of IOC (Dependency Injection)? Benefits of IOC (Dependency Injection) are as follows: • Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration. • Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test. • Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own. • IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc. 4. What is Spring ? Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.

5. What are the advantages of Spring framework? The advantages of Spring are as follows: • Spring has layered architecture. Use what you need and leave you don't need now. • Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability. • Dependency Injection and Inversion of Control Simplifies JDBC • Open source and no vendor lock-in. 6. What are features of Spring ? • Lightweight:

spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible. • Inversion of control (IOC): Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects. • Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services. • Container: Spring contains and manages the life cycle and configuration of application objects. • MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework. • Transaction Management: Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments. • JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

7.How many modules are there in Spring? What are they?

Spring comprises of seven modules. They are.. • The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies theInversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code. • Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. • Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components. • Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy. • Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies. • Spring Web module: The Web context module builds on top of the application context module, providing contexts for Webbased applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects. • Spring MVC framework:

The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI. 8. What are the types of Dependency Injection Spring supports? • Setter Injection: Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. • Constructor Injection: Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator. 9. What is Bean Factory ? A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients. • BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. • BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

10. What is Application Context? A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides: • A means for resolving text messages, including support for internationalization. • A generic way to load file resources. • Events to beans that are registered as listeners. 11. What is the difference between Bean Factory and Application Context ? On the surface, an application context is same as a bean factory. But application context offers much more.. • Application contexts provide a means for resolving text messages, including support for i18n of those messages. • Application contexts provide a generic way to load file resources, such as images. • Application contexts can publish events to beans that are registered as listeners. • Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. • ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling lowlevel resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances. • MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable 12. What are the common implementations of the Application Context ? The three commonly used implementation of 'Application Context' are

• ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code . ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

• FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code . ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");

• XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

13. How is a typical spring implementation look like ? For a typical Spring Application we need the following files: • An interface that defines the functions. • An Implementation that contains properties, its setter and getter methods, functions etc., • Spring AOP (Aspect Oriented Programming) • A XML file called Spring configuration file. • Client program that uses the function. 14. What is the typical Bean life cycle in Spring Bean Factory Container ? Bean life cycle in Spring Bean Factory Container is as follows: • The spring container finds the bean’s definition from the XML file and instantiates the bean. • Using the dependency injection, spring populates all of the properties as specified in the bean definition

• If the bean implements the BeanNameAware interface, the factory calls setBeanName()passing the bean’s ID.

• If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.

• If

there

are

any

BeanPostProcessors

associated

with

the

bean,

their

post-

the

bean,

their

ProcessBeforeInitialization()methods will be called. • If an init-method is specified for the bean, it will be called.

• Finally,

if

there

are

any

BeanPostProcessors

associated

with

postProcessAfterInitialization()methods will be called. 15. What do you mean by Bean wiring ? The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring. 16. What do you mean by Auto Wiring? The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes. • no • byName • byType • constructor • autodirect

17. What is DelegatingVariableResolver? Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard Java Server Faces managed beans mechanism which lets you use JSF and Spring together. This variable resolver is called as DelegatingVariableResolver 18. How to integrate Java Server Faces (JSF) with Spring? JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By declaring JSF managed-beans in the faces-config.xml configuration file, you allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to these beans and all of their properties.We can integrate JSF and Spring in two ways:

• DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF and Spring together.

org.springframework.web.jsf.DelegatingVariableResolver

The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring's 'business context' WebApplicationContext. This allows one to easily inject dependencies into one's JSF-managed beans. • FacesContextUtils:custom VariableResolver works well when mapping one's properties to beans in faces-config.xml, but at times one may need to grab a bean explicitly. The FacesContextUtils class

makes this easy. It is similar to WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter. ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()) ; 19. What is Java Server Faces (JSF) - Spring integration mechanism? Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard JavaServer Faces managed beans mechanism. When asked to resolve a variable name, the following algorithm is performed: • Does a bean with the specified name already exist in some scope (request, session, application)? If so, return it • Is there a standard JavaServer Faces managed bean definition for this variable name? If so, invoke it in the usual way, and return the bean that was created. • Is there configuration information for this variable name in the Spring WebApplicationContext for this application? If so, use it to create and configure an instance, and return that instance to the caller. • If there is no managed bean or Spring definition for this variable name, return null instead. • BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods. As a result of this algorithm, you can transparently use either JavaServer Faces or Spring facilities to create beans on demand.

20. What is Significance of JSF- Spring integration ? Spring - JSF integration is useful when an event handler wishes to explicitly invoke the bean factory to create beans on demand, such as a bean that encapsulates the business logic to be performed when a submit button is pressed. 21. How to integrate your Struts application with Spring? To integrate your Struts application with Spring, we have two options: • Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.

• Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext()method. 22. What are ORM’s Spring supports ? Spring supports the following ORM’s: • • • • • •

Hibernate iBatis JPA (Java Persistence API) TopLink JDO (Java Data Objects) OJB

23. What are the ways to access Hibernate using Spring ? There are two approaches to Spring’s Hibernate integration: • Inversion of Control with a HibernateTemplate and Callback • Extending HibernateDaoSupport and Applying an AOP Interceptor

24. How to integrate Spring and Hibernate using HibernateDaoSupport? Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps. • Configure the Hibernate SessionFactory • Extend your DAO Implementation from HibernateDaoSupport • Wire in Transaction Support with AOP 25. What are Bean scopes in Spring Framework ? The Spring Framework supports exactly five scopes (of which three are available only if you are using a webaware ApplicationContext). The scopes supported are listed below: Scope

Description

singleton

Scopes a single bean definition to a single object instance per Spring IoC container.

prototype

Scopes a single bean definition to any number of object instances.

request

Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware SpringApplicationContext.

session

Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware SpringApplicationContext.

global session

Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

26. What is AOP? Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. 27. How the AOP used in Spring? AOP is used in the Spring Framework: To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on the Spring Framework's transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP. 29. What do you mean by JointPoint? A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. 30. What do you mean by Advice? Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point. 31. What are the types of Advice? Types of advice:

• Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).

• After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.

• After throwing advice: Advice to be executed if a method exits by throwing an exception. • After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).

• Around advice: Advice that surrounds a join point such as a method invocation. This is the most

powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception

32. What are the types of the transaction management Spring supports ? Spring Framework supports: • Programmatic transaction management. • Declarative transaction management. 33. What are the benefits of the Spring Framework transaction management ? The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits: • Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO. • Supports declarative transaction management. • Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA. • Integrates very well with Spring's various data access abstractions.

34. Why most users of the Spring Framework choose declarative transaction management ? Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container. 35. Explain the similarities and differences between EJB CMT and the Spring Framework's declarative transaction management ? The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to individual

method level. It is possible to make a setRollbackOnly() call within a transaction context if necessary. The differences are: • Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction management works in any environment. It can work with JDBC, JDO, Hibernate or other transactions under the covers, with configuration changes only. • The Spring Framework enables declarative transaction management to be applied to any class, not merely special classes such as EJBs. • The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent. Both programmatic and declarative support for rollback rules is provided. • The Spring Framework gives you an opportunity to customize transactional behavior, using AOP. With EJB CMT, you have no way to influence the container's transaction management other than setRollbackOnly().

• The Spring Framework does not support propagation of transaction contexts across remote calls, as do high-end application servers.

37. When to use programmatic and declarative transaction management ? Programmatic transaction management is usually a good idea only if you have a small number of transactional operations. On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.

38. Explain about the Spring DAO support ? The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.

39. What are the exceptions thrown by the Spring DAO classes ? Spring DAO classes throw exceptions which

are

subclasses

DataAccessException(org.springframework.dao.DataAccessException).Spring

provides

of a

convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with theDataAccessException as the root exception. These exceptions wrap the original exception.

40. What is SQLExceptionTranslator ? SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions

and

Spring's

own

data-access-strategy-agnostic

org.springframework.dao.DataAccessException. 41. What is Spring's JdbcTemplate ? Spring's JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.

JdbcTemplate template = new JdbcTemplate(myDataSource); 42. What is PreparedStatementCreator ? PreparedStatementCreator: • Is one of the most common used interfaces for writing data to database. • Has one method – createPreparedStatement(Connection)

• Responsible for creating a PreparedStatement. • Does not need to handle SQLExceptions. 43. What is SQLProvider ? SQLProvider:

• Has one method – getSql()

• Typically implemented by PreparedStatementCreator implementers. • Useful for debugging. 44. What is RowCallbackHandler ? The RowCallbackHandler interface extracts values from each row of a ResultSet.

• Has one method – processRow(ResultSet) • Called for each row in ResultSet. • Typically stateful. 45. What are the differences between EJB and Spring ? Spring and EJB feature comparison.

Feature Transaction management

Declarative transaction support

Persistence

Declarative security

Distributed computing

EJB

Spring

• Must use a JTA transaction manager. • Supports transactions that span remote method calls.

• Supports multiple transaction environments

• Can define transactions declaratively through the deployment descriptor. • Can define transaction behavior per method or per class by using the wildcard character *. • Cannot declaratively define rollback behavior— this must be done programmatically.

• Can define transactions declaratively through the Spring configuration file or through class metadata. • Can define which methods to apply transaction behavior explicitly or by using regular expressions. • Can declaratively define rollback behavior per method and per exception type.

Supports programmatic beanmanaged persistence and declarative container managed persistence. • Supports declarative security through users and roles. The management and implementation of users and roles is container specific. • Declarative security is configured in the deployment descriptor.

Provides container-managed remote method calls.

through its PlatformTransactionManager interface, including JTA, Hibernate, JDO, and JDBC. • Does not natively support distributed transactions —it must be used with a JTA transaction manager.

Provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS. • No security implementation out-of-the box. • Acegi, an open source security framework built on top of Spring, provides declarative security through the Spring configuration file or class metadata.

Provides proxying for remote calls via RMI, JAXRPC, and web services.

J2EE Interview Questions 1) What is J2EE? J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multi tiered, and web-based applications.

2) What is the J2EE module? A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.

3) What are the components of J2EE application? A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: • Application clients and applets are client components. • Java Servlets and Java Server PagesTM (JSPTM) technology components are web components. • Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components. • Resource adapter components provided by EIS and tool vendors.

4) What are the four types of J2EE modules? • • • •

Application client module Web module Enterprise JavaBeans module Resource adapter module

5) What does application client module contain? The application client module contains: • class files, • an application client deployment descriptor. Application client modules are packaged as JAR files with a .jar extension.

6) What does Enterprise JavaBeans module contain? The Enterprise JavaBeans module contains: 8. class files for enterprise beans 9. An EJB deployment descriptor. EJB modules are packaged as JAR files with a .jar extension.

7) What does resource adapt module contain? The resource adapt module contains: 3. 4. 5. 6. 7.

all Java interfaces, classes, native libraries, other documentation, A resource adapter deployment descriptor.

Resource adapter modules are packages as JAR files with a .rar (Resource adapter Archive) extension.

8) How many development roles are involved in J2EE application? There are at least 5 roles involved: • Enterprise Bean Developer • Writes and compiles the source code • Specifies the deployment descriptor • Bundles the .class files and deployment descriptor into an EJB JAR file • Web Component Developer • Writes and compiles Servlets source code • Writes JSP and HTML files • Specifies the deployment descriptor for the Web component • Bundles the .class, .jsp, .html, and deployment descriptor files in the WAR file • J2EE Application Client Developer • Writes and compiles the source code • Specifies the deployment descriptor for the client • Bundles the .class files and deployment descriptor into the JAR file • Application Assembler The application assembler is the company or person who receives application component JAR files from component providers and assembles them into a J2EE application EAR file. The assembler or deployer can edit the deployment descriptor directly or use tools that correctly add XML tags according to interactive selections. A software developer performs the following tasks to deliver an EAR file containing the J2EE application: • Assembles EJB JAR and WAR files created in the previous phases into a J2EE application (EAR) file • Specifies the deployment descriptor for the J2EE application • Verifies that the contents of the EAR file are well formed and comply with the J2EE specification • Application Deployer and Administrator • Configures and deploys the J2EE application • Resolves external dependencies • Specifies security settings & attributes • Assigns transaction attributes and sets transaction controls • Specifies connections to databases • Deploys or installs the J2EE application EAR file into the J2EE server • Administers the computing and networking infrastructure where J2EE applications run • Oversees the runtime environment But a developer role depends on the job assignment. For a small company, one developer may take these 5 roles altogether.

9) What is difference between J2EE 1.3 and J2EE 1.4? J2EE 1.4 is an enhancement version of J2EE 1.3. It is the most complete Web services platform ever. J2EE 1.4 includes: • • • • • • • • • • • • •

Java API for XML-Based RPC (JAX-RPC 1.1) SOAP with Attachments API for Java (SAAJ), Web Services for J2EE(JSR 921) J2EE Management Model(1.0) J2EE Deployment API(1.1) Java Management Extensions (JMX), Java Authorization Contract for Containers(JavaACC) Java API for XML Registries (JAXR) Servlet 2.4 JSP 2.0 EJB 2.1 JMS 1.1 J2EE Connector 1.5

The J2EE 1.4 features complete Web services support through the new JAX-RPC 1.1 API, which supports service endpoints based on Servlets and enterprise beans. JAX-RPC 1.1 provides interoperability with Web services based on the WSDL and SOAP protocols. The J2EE 1.4 platform also supports the Web Services for J2EE specification (JSR 921), which defines deployment requirements for Web services and utilizes the JAX-RPC programming model. In addition to numerous Web services APIs, J2EE 1.4 platform also features support for the WS-I Basic Profile 1.0. This means that in addition to platform independence and complete Web services support, J2EE 1.4 offers platform Web services interoperability. The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information model for J2EE management, including the standard Management EJB (MEJB). The J2EE Management 1.0 API uses the Java Management Extensions API (JMX). The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which provides a standard API for deployment of J2EE applications. The J2EE 1.4 platform includes security enhancements via the introduction of the Java Authorization Contract for Containers (JavaACC). The JavaACC API improves security by standardizing how authentication mechanisms are integrated into J2EE containers. The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet and JavaServer Pages (JSP) technologies. Servlets now support request listeners and enhanced filters. JSP technology has simplified the page and extension development models with the introduction of a simple expression language, tag files, and a simpler tag extension API, among other features. This makes it easier than ever for developers to build JSP-enabled pages, especially those who are familiar with scripting languages. Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides incoming resource adapter and Java Message Service (JMS) plug ability. New features in Enterprise JavaBeans (EJB) technology include Web service endpoints, a timer service, and enhancements to EJB QL and message-driven beans. The J2EE 1.4 platform also includes enhancements to deployment descriptors. They are now defined using XML Schema which can also be used by developers to validate their XML structures. Note: The above information comes from SUN released notes.

10) Is J2EE application only a web-based? NO. A J2EE application can be web-based or non-web-based. If an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a Servlet running in the web tier.

11) Are JavaBeans J2EE components? NO. JavaBeans components are not considered J2EE components by the J2EE specification. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.

12) Is HTML page a web component? NO. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.

13) What is the container? A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.

14) What is the web container? Servlet and JSP containers are collectively referred to as Web containers.

15) What is the thin client? A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications.

16) What are types of J2EE clients? • • • •

Applets Application clients Java Web Start-enabled rich clients, powered by Java Web Start technology. Wireless clients, based on Mobile Information Device Profile (MIDP) technology.

17) What is deployment descriptor? A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component's deployment settings. A J2EE application and each of its modules has its own deployment descriptor.

18)What is the EAR file? An EAR file is a standard JAR file with an .ear extension, named from Enterprise Archive file. A J2EE application with all of its modules is delivered in EAR file.

19) What are JTA and JTS? JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Java Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn't call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. And JTS is a low level transaction interface and EJBs uses behind the scenes (client code doesn't directly interact with JTS. It is based on object transaction service (OTS) which is part of CORBA.

20) What is JAXP? JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs.

21) What is J2EE Connector? The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter.

22) What is JAAP? The Java Authentication and Authorization Service (JAAS) provide a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.

23) What is Model 1? Using JSP technology alone to develop Web page. Such term is used in the earlier JSP specification. Model 1 architecture is suitable for applications that have very simple page flow, have little need for centralized security control or logging, and change little over time. Model 1 applications can often be refactored to Model 2 when application requirements change.

24) What is Model 2? Using JSP and Servlet together to develop Web page. Model 2 applications are easier to maintain and extend, because views do not refer to each other directly.

25) What is Struts? A Web page development framework. Struts combine Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.

26) How is the MVC design pattern used in Struts framework? In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application's business logic or state. Control is usually then forwarded back through the Controller

to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the screen, a JSP page and presentation components; Model --- System state and a business logic JavaBeans.

27) Do you have to use design pattern in J2EE project? Yes. If I do it, I will use it. Learning design pattern will boost my coding skill.

28) Is J2EE a super set of J2SE? Yes

29) What does web module contain? The web module contains: • • • •

JSP files, class files for Servlets, GIF and HTML files, and A Web deployment descriptor.

Web modules are packaged as JAR files with a .war (Web Archive) extension.

30) What APIs are available for developing a J2EE application? • Enterprise JavaBeans Technology(3 beans: Session Beans, Entity Beans and MessageDriven Beans) • JDBC API(application level interface and service provider interface or driver) • Java Servlets Technology(Servlet) • Java ServerPage Technology(JSP) • Java Message Service(JMS) • Java Naming and Directory Interface(JNDI) • Java Transaction API(JTA) • JavaMail API • JavaBeans Activation Framework(JAF used by JavaMail) • Java API for XML Processing(JAXP,SAX, DOM, XSLT) • Java API for XML Registries(JAXR) • Java API for XML-Based RPC(JAX-RPC)-SOAP standard and HTTP • SOAP with Attachments API for Java(SAAJ)-- low-level API upon which JAX-RPC depends • J2EE Connector Architecture • Java Authentication and Authorization Service(JAAS)

Hibernate Interview Questions 1) What is Hibernate? Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users to develop persistent classes following object-oriented principles such as association, inheritance, polymorphism, composition, and collections.

2) What is ORM? ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

3) What does an ORM solution comprises of? • It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes • Should have a language or an API for specifying queries that refer to the classes and the properties of classes • An ability for specifying mapping metadata • It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions

4) What are the different levels of ORM quality? There are four levels defined for ORM quality. • • • •

Pure relational Light object mapping Medium object mapping Full object mapping

5) What is a pure relational ORM? The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

6) What is a meant by light object mapping? The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

7) What is a meant by medium object mapping? The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

8) What is meant by full object mapping? Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.

9) What are the benefits of ORM and Hibernate? There are many benefits from these. Out of which the following are the most important one.

• Productivity –Hibernate reduces the burden of developer by providing much of the • •



functionality and let the developer to concentrate on business logic. Maintainability –As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC. Performance –Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance. Vendor independence –Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

10) How does hibernate code looks like? Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); MyPersistanceClass mpc = new MyPersistanceClass ("Sample App"); session.save(mpc); tx.commit(); session.close(); The Session and Transaction are the interfaces provided by hibernate. There are many other interfaces besides this.

11) What is a hibernate xml mapping document and how does it look like? In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database. <property name="text" column="Persistance_message"/> <many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>

Everything should be included under tag. This is the main tag for an xml mapping document.

13) What the Core interfaces are of hibernate framework? There are many benefits from these. Out of which the following are the most important one.

10.

Session Interface –This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe. 11. SessionFactory Interface –This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads. 12. Configuration Interface –This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents. 13. Transaction Interface –This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction. 14. Query and Criteria Interface –This interface allows the user to perform queries and also control the flow of the query execution.

14) What are Callback interfaces? These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.

15) What are Extension interfaces? When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.

16) What are the Extension interfaces that are there in hibernate? There are many extension interfaces provided by hibernate.

8. ProxyFactory interface - used to create proxies 9. ConnectionProvider interface – used for JDBC connection management 10. TransactionFactory interface – Used for transaction management 11. Transaction interface – Used for transaction management 12. TransactionManagementLookup interface – Used in transaction management. 13. Cahce interface – provides caching techniques and strategies 14. CacheProvider interface – same as Cache interface 15. ClassPersister interface – provides ORM strategies 16. IdentifierGenerator interface – used for primary key generation 17. Dialect abstract class – provides SQL support

17) What are different environments to configure hibernate? There are mainly two types of environments in which the configuration of hibernate application differs.

• Managed environment –In this kind of environment everything from database



connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere. Non-managed environment –This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.

18) What is the file extension you use for hibernate mapping file? The name of the file should be like this : filenam.hbm.xml The filename varies here. The extension of these files should be “.hbm.xml”. This is just a convention and it’s not mandatory. But this is the best practice to follow this extension.

19) What do you create a SessionFactory? Configuration cfg = new Configuration(); cfg.addResource("myinstance/MyConfig.hbm.xml"); cfg.setProperties( System.getProperties() ); SessionFactory sessions = cfg.buildSessionFactory(); First, we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory().

20) What is meant by Method chaining? Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining. SessionFactory sessions = new Configuration() .addResource("myinstance/MyConfig.hbm.xml") .setProperties( System.getProperties() ) .buildSessionFactory();

21) What does hibernate.properties file consist of? This is a property file that should be placed in application class path. So when the Configuration object is created, hibernate is first initialized. At this moment the application will automatically detect and read this hibernate.properties file. hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB hibernate.transaction.factory_class = net.sf.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class = net.sf.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

22) What should SessionFactory be placed so that it can be easily accessed? As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.

23) What are POJOs? POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes.

24) What is object/relational mapping metadata? ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations.

25) What is HQL? HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.

26) What are the different types of property and class mappings? • Typical and most common property mapping <property name="description" column="DESCRIPTION" type="string"/> Or <property name="description" type="string"> • Derived properties <property name="averageBidAmount" formula="( select AVG(b.AMOUNT) from BID b where b.ITEM_ID = ITEM_ID )" type="big_decimal"/> • Typical and most common property mapping <property name="description" column="DESCRIPTION" type="string"/> • Controlling inserts and updates <property name="name" column="NAME" type="string" insert="false" update="false"/>

27) What is Attribute Oriented Programming? XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are

used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called as Attribute Oriented Programming.

28) What are the different methods of identifying an object? There are three methods by which an object can be identified.

• Object identity –Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator.

• Object equality –Objects are equal if they have the same value, as defined by the equals( •

) method. Classes that don’t explicitly override this method inherit the implementation defined by java.lang.Object, which compares object identity. Database identity –Objects stored in a relational database are identical if they represent the same row or, equivalently, share the same table and primary key value.

29) What are the different approaches to represent an inheritance hierarchy? • Table per concrete class. • Table per class hierarchy. • Table per subclass.

30) What are managed associations and hibernate associations? Associations that are related to container management persistence are called managed associations. These are bi-directional associations. Coming to hibernate associations, these are unidirectional.

Questions downloaded from : http://www.developersbook.com/hibernate/interview-questions/hibernate-interview-questions-faqs.php 1.What is ORM ? ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database. 2.What does ORM consists of ? An ORM solution consists of the followig four pieces: • API for performing basic CRUD operations • API to express queries refering to classes • Facilities to specify metadata • Optimization facilities : dirty checking,lazy associations fetching 3.What are the ORM levels ? The ORM levels are: • • • •

Pure relational (stored procedure.) Light objects mapping (JDBC) Medium object mapping Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate? Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5.Why do you need ORM tools like hibernate? The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

• Improved productivity



• •

• High-level object-oriented API • Less Java code to write • No SQL to write Improved performance • Sophisticated caching • Lazy loading • Eager loading Improved maintainability • A lot less code to write Improved portability • ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify? Hibernate simplifies: • • • • •

Saving and retrieving your domain objects Making database column and table name changes Centralizing pre save and post retrieve logic Complex joins for retrieving related items Schema creation from object model

7.What is the need for Hibernate xml mapping file? Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:

8.What are the most common methods of Hibernate configuration? The most common methods of Hibernate configuration are: • Programmatic configuration • XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml? Following are the important tags of hibernate.cfg.xml:

10.What are the Core interfaces are of Hibernate framework? The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions. • • • • •

Session interface SessionFactory interface Configuration interface Transaction interface Query and Criteria interfaces

11.What role does the Session interface play in Hibernate? The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, shortlived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. Session session = sessionFactory.openSession(); Session interface role: • Wraps a JDBC connection • Factory for Transaction • Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate? The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.buildSessionFactory(); 13.What is the general flow of Hibernate communication with RDBMS? The general flow of Hibernate communication with RDBMS is : • Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files • Create session factory from configuration object • Get one session from this session factory • Create HQL Query • Execute query to get list containing Java objects 14.What is Hibernate Query Language (HQL)? Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL. 15.How do you map Java Objects with Database tables? • First we need to write Java domain objects (beans with setter and getter). • Write hbm.xml, where we map java class to table and database columns to Java class variables. Example:

<property column="USER_NAME" length="255" name="userName" not-null="true" type="java.lang.String"/> <property column="USER_PASSWORD" length="255" name="userPassword" not-null="true" type="java.lang.String"/> 16.What’s the difference between load() and get()? load() vs. get() :-

load()

get()

Only use the load()method if you are sure that the

If you are not sure that the object exists, then

object exists.

use one of the get()methods.

load()method will throw an exception if the unique

get()method will return null if the unique

id is not found in the database. load()just returns a proxy by default and database won’t be hit until the proxy is first invoked.

id is not found in the database. get()will hit the database immediately.

17.What is the difference between and merge and update ? Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge()if you want to merge your modifications at any time without consideration of the state of the session. 18.How do you define sequence generated primary key in hibernate? Using tag. Example:-

<param name="table">SEQUENCE_NAME 19.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? 20.What do you mean by Named – SQL query? Named SQL queries are defined in the mapping xml document and called wherever required. Example:

<sql-query name = "empdetails"> SELECT emp.EMP_ID AS {emp.empid}, emp.EMP_ADDRESS AS {emp.address}, emp.EMP_NAME AS {emp.name} FROM Employee EMP WHERE emp.NAME LIKE :name Invoke Named Query :

List people = session.getNamedQuery("empdetails")

.setString("TomBrady", name) .setMaxResults(50) .list(); 21.How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true"> { ? = call selectAllEmployees() } 22.Explain Criteria API Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. Example:

List employees = session.createCriteria(Employee.class) .add(Restrictions.like("name", "a%") ) .add(Restrictions.like("address", "Boston")) .addOrder(Order.asc("name") ) .list(); 23.Define HibernateTemplate? org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions. 24.What are the benefits does HibernateTemplate provide? The benefits of HibernateTemplate are :

• HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session. • Common functions are simplified to single method calls. • Sessions are automatically closed. • Exceptions are automatically caught and converted to runtime exceptions. 25.How do you switch between relational databases without code changes?

Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined. 26.If you want to see the Hibernate generated SQL statements on console, what should we do? In Hibernate configuration file set as follows: <property name="show_sql">true 27.What are derived properties? The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element. 28.What is component mapping in Hibernate? • A component is an object saved as a value, not as a reference • A component can be saved directly without needing to declare interfaces or identifier properties • Required to define an empty constructor • Shared references not supported Example:

29.What is the difference between sorted and ordered collection in hibernate? sorted collection vs. order collection:-

sorted collection A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after

order collection Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.

the data being read from database using java comparator. If your collection is not large, it will be more efficient way to sort it.

If your collection is very large, it will be more efficient way to sort it .

31.What is the advantage of Hibernate over jdbc? Hibernate Vs. JDBC :-

JDBC

Hibernate

With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.

Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.

Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.

JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.

Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table.

Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.

Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

With JDBC, caching is maintained by handcoding.

Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic

Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.

In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

32.What are the Collection types in Hibernate ? • • • • •

Bag Set List Array Map

33.What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:-

• An implicit association join

• An ordinary join in the FROM clause • A fetch join in the FROM clause. • A theta-style join in the WHERE clause. 34.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? 35.What is Hibernate proxy? The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked. 36.How can Hibernate be configured to access an instance variable directly and not through a setter method ?

By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

37.How can a whole class be mapped as immutable? Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application. 38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

• Dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed

• dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

39.What do you mean by fetching strategy ? A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query. 40.What is automatic dirty checking? Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction. 41.What is transactional write-behind? Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional writebehind. 42.What are Callback interfaces? Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality. 43.What are the types of Hibernate instance states ? Three types of instance states: • Transient -The instance is not associated with any persistence context • Persistent -The instance is associated with a persistence context • Detached -The instance was associated with a persistence context which has been closed – currently not associated

44.What are the differences between EJB 3.0 & Hibernate Hibernate Vs EJB 3.0 :-

Hibernate

EJB 3.0

Session–Cache or collection of loaded objects relating to a single unit of work

Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit

XDoclet Annotations used to support Attribute Oriented Programming

Java 5.0 Annotations used to support Attribute Oriented Programming

Defines HQL for expressing queries to the database

Defines EJB QL for expressing queries

Supports Entity Relationships through mapping files and annotations in JavaDoc

Support Entity Relationships through Java 5.0 annotations

Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API

Provides and Entity Manager Interface for managing CRUD operations for an Entity

Provides callback support through lifecycle, interceptor, and validatable interfaces

Provides callback support through Entity Listener and Callback methods

Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships

Entity Relationships are bidirectional or unidirectional

45.What are the types of inheritance models in Hibernate? There are three types of inheritance models in Hibernate: • Table per class hierarchy • Table per subclass • Table per concrete class

EJB Interview Questions 1. What is EJB? EJB stands for Enterprise JavaBeans and is widely-adopted server side component architecture for J2EE. It enables rapid development of ission-critical application that are versatile, reusable and portable across middleware while protecting IT investment and preventing vendor lock-in.

2. What is session Facade? Session Facade is a design pattern to access the Entity bean through local interface than accessing directly. It increases the performance over the network. In this case we call session bean which on turn call entity bean.

3. What is EJB role in J2EE? EJB technology is the core of J2EE. It enables developers to write reusable and portable serverside business logic for the J2EE platform.

4. What is the difference between EJB and Java beans? EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE.

5. What are the key features of the EJB technology? • EJB components are server-side components written entirely in the Java programming language • EJB components contain business logic only - no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server. • EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure. • EJB components are fully portable across any EJB server and any OS. • EJB architecture is wire-protocol neutral--any protocol can be utilized like IIOP, JRMP, HTTP, DCOM, etc.

6. What are the key benefits of the EJB technology? • • • •

Rapid application development Broad industry adoption Application portability Protection of IT investment

7. How many enterprise beans? There are three kinds of enterprise beans: • session beans, • entity beans, and • message-driven beans.

8. What is message-driven bean?

A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients to access the business logic in the EJB tier.

9. What are Entity Bean and Session Bean? Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence (CMP) and Bean-Managed Persistence (BMP). Session Bean is used to represent a workflow on behalf of a client. There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn't maintain any conversational state with clients between method invocations. Stateful bean maintains state between invocations.

10. How EJB Invocation happens? Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client. Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to Bean (Enterprise Bean).

11. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be considering as passed-by-value that means that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container. The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it.

12. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. While referring the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is, again, up to the implementer.

13. Can the primary key in the entity bean be a Java primitive type such as int? The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive).

14. Can you control when passivation occurs? The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA Weblogic, provide the ability to tune the container to minimize passivation calls. Taken from the Weblogic 6.0 DTD -The passivation-strategy can be either default or transaction. With the default setting the container will attempt to keep a working set of beans in the cache. With the transaction setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).

15. What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other? Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Managed. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistence storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection, retrieve values, assign them to the objects in the ejbLoad() which will be called by the container when it instantiates a bean object. Similarly in the ejbStore() the container saves the object values back the persistence storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you don’t need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container.

16. What is EJB QL? EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistence and is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.

17. Brief description about local interfaces? EEJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also

provide the foundation for container-managed relationships among entity beans with containermanaged persistence.

18. What are the special design cares that must be taken when you work with local interfaces? It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.

19. What happens if remove( ) is never invoked on a session bean? In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of Stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.

20. What is the difference between Message Driven Beans and Stateless Session beans? In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.

21. How can I call one EJB from inside of another EJB? EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.

22. What is an EJB Context? EJBContext is an interface that is implemented by the container, and it is also a part of the beancontainer contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.

23. Is it possible for an EJB client to marshal an object of class java.lang.Class to an EJB? Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.

24. Is it legal to have static initializer blocks in EJB? Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods.

25. Is it possible to stop the execution of a method before completion in a SessionBean? Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB.

26. What is the default transaction attribute for an EJB? There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for those methods having container managed transaction. In Weblogic, the default transaction attribute for EJB is SUPPORTS.

27. What is the difference between session and entity beans? When should I use one or the other? An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw)

28. Is there any default cache management system with Entity beans? In other words whether a cache of the data in database will be maintained in EJB? - Caching data from a database inside the Application Server are what Entity EJBs are used for. The ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the persistent storage(database). Transactions also play an important role in this scenario. If data is removed from the database, via an external application - your Entity Bean can still be alive the EJB container. When the transaction commits, ejbStore() is called and the row will not be found, and the transaction rolled back.

29. Why is ejbFindByPrimaryKey mandatory? An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB.

30. Why do we have a remove method in both EJBHome and EJBObject? With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it (you can provide a PrimaryKey object as a parameter to the remove method). The home version only works for entity beans. On the other hand, the Remote interface version works on an entity bean that you have already instantiated. In addition, the remote version also works on session beans (stateless and Stateful) to inform the container of your loss of interest in this bean.

31. How can I call one EJB from inside of another EJB? EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.

32. What is the difference between a Server, a Container, and a Connector? An EJB server is an application, usually a product such as BEA Weblogic, that provides (or should provide) for concurrent client connections and manages system resources such as threads, processes, memory, database connections, network connections, etc. An EJB container runs inside (or within) an EJB server, and provides deployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean and its container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJB server which supports the Connector architecture. See Sun’s J2EE Connectors for more in-depth information on Connectors.

33. How is persistence implemented in enterprise beans? Persistence in EJB is taken care of in two ways, depending on how you implement your beans: container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container. For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being looked up, when the create() method is called on the Home interface, then the container is responsible for calling the ejbCreate() method in the bean, which should have functionality inside for going to the database and looking up the data.

34. What is an EJB Context? EJBContext is an interface that is implemented by the container, and it is also a part of the beancontainer contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.

35. Is method overloading allowed in EJB? Yes you can overload methods should synchronization primitives be used on bean methods? - No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime.

36. Are we allowed to change the transaction isolation property in middle of a transaction? No. You cannot change the transaction isolation level in the middle of transaction.

37. For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the bean is passivated? The specification infers that the container never serializes an instance of an Entity bean (unlike Stateful session beans). Thus passivation simply involves moving the bean from the ready to the pooled bin. So what happens to the contents of an instance variable is controlled by the programmer. Remember that when an entity bean is passivated the instance gets logically disassociated from its remote object. Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior to reuse or for dereference.

38. What is a Message Driven Bean, what functions does a message driven bean have and how do they work in collaboration with JMS? Message driven beans are the latest addition to the family of component bean types defined by the EJB specification. The original bean types include session beans, which contain business logic and maintain a state associated with client sessions, and entity beans, which map objects to persistent data. Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and session beans, message beans do not have home or remote interfaces. Instead, message driven beans are instantiated by the container as required. Like stateless session beans, message beans maintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances. Clients send JMS messages to message beans in exactly the same manner as they would send messages to any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the new specification. To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, which defines a single onMessage() method. When a message arrives, the container ensures that a message bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the client’s message as the single argument. The message bean’s implementation of this method contains the business logic required to process the message. Note that session beans and entity beans are not allowed to function as message beans.

39. Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in the same way as RMI does across a JRMP connection? Yes. The JDK 1.2 supports the dynamic class loading. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client,

40. Does the container create a separate instance of the generated EJBHome and EJBObject classes? The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. While referring the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container

providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer.

41. What is the advantage of putting an Entity Bean instance from the Ready State to Pooled State? The idea of the Pooled State is to allow a container to maintain a pool of entity beans that has been created, but has not been yet synchronized or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using an entity bean of a particular type there is no need for cachig it (the data is persisted in the database). Therefore, in such cases, the container will, after some time, move the entity bean from the Ready State to the Pooled state to save memory. Then, to save additional memory, the container may begin moving entity beans from the Pooled State to the Does Not Exist State, because even though the bean’s cache has been cleared, the bean still takes up some memory just being in the Pooled State.

42. What is the need of Remote and Home interface. Why can’t it be in one? The main reason is because there is a clear division of roles and responsibilities between the two interfaces. The home interface is your way to communicate with the container, that is that is responsible of creating, locating even removing one or more beans. The remote interface is your link to the bean that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and the beans) and you need two different interfaces for accessing to both of them.

43. Can I develop an Entity Bean without implementing the create() method in the home interface? As per the specifications, there can be 'ZERO' or 'MORE' create() methods defined in an Entity Bean. In cases where create() method is not provided, the only way to access the bean is by knowing its primary key, and by acquiring a handle to it by using its corresponding finder method. In those cases, you can create an instance of a bean based on the data present in the table. All one needs to know is the primary key of that table. I.e. a set a columns that uniquely identify a single row in that table. Once this is known, one can use the 'getPrimaryKey()' to get a remote reference to that bean, which can further be used to invoke business methods. What is the difference between Context, InitialContext and Session Context? How they are used? javax.naming.Context is an interface that provides methods for binding a name to an object. It's much like the RMI Naming.bind() method. javax.naming.InitialContext is a Context and provides implementation for methods available in the Context interface. Where as SessionContext is an EJBContext objects that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container. There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean for the purpose of the EntityBean accessing the container details. In general, the EJBContext (SessionContext and EntityContext), AppletContext and ServletContext help the corresponding Java objects in knowing about its 'context' [environment in which they run], and to access particular information and/or service. Whereas, the javax.naming.Context is for the purpose of 'NAMING' [by the way of referring to] an object.

44. Why an onMessage call in Message-driven bean is always a separate transaction? EJB 2.0 specification: "An onMessage call is always a separate transaction, because there is never a transaction in progress when the method is called." When a message arrives, it is passed to the Message Driven Bean through the onMessage() method, that is where the business logic goes. Since there is no guarantee when the method is called and when the message will be processed, is the container that is responsible of managing the environment, including transactions.

45. Why are ejbActivate() and ejbPassivate() included for stateless session bean even though they are never required as it is a no conversational bean? To have a consistent interface, so that there is no different interface that you need to implement for Stateful Session Bean and Stateless Session Bean. Both Stateless and Stateful Session Bean implement javax.ejb.SessionBean and this would not be possible if stateless session bean is to remove ejbActivate and ejbPassivate from the interface.

46. Static variables in EJB should not be relied upon as they may break in clusters. Why? Static variables are only ok if they are final. If they are not final, they will break the cluster. What that means is that if you cluster your application server (spread it across several machines) each part of the cluster will run in its own JVM. Say a method on the EJB is invoked on cluster 1 (we will have two clusters - 1 and 2) that causes value of the static variable to be increased to 101. On the subsequent call to the same EJB from the same client, a cluster 2 may be invoked to handle the request. A value of the static variable in cluster 2 is still 100 because it was not increased yet and therefore your application ceases to be consistent. Therefore, static non-final variables are strongly discouraged in EJBs.

47. If I throw a custom ApplicationException from a business method in Entity bean which is participating in a transaction, would the transaction be rolled back by container? EJB Transaction is automatically rolled back only when a SystemException (or a subtype of it) is thrown. Your ApplicationException can extend from javax.ejb.EJBException, which is a sub class of RuntimeException. When an EJBException is encountered the container rolls back the transaction. EJB Specification does not mention anything about Application exceptions being sub-classes of EJBException. You can tell container to rollback the transaction, by using setRollBackOnly on SessionContext/EJBContext object as per type of bean you are using.

48. Does Stateful Session bean support instance pooling? Stateful Session Bean conceptually doesn't have instance pooling.

49. Can I map more than one table in a CMP? No, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in fact, designed to map a single table.

50. Can a Session Bean be defined without ejbCreate() method? The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method.

However, the J2EE spec is explicit: 18. the home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments. 19. Stateful Session Beans can have arguments (more than one create method)

51. How to implement an entity bean which the PrimaryKey is an auto numeric field? The EJB 2 Spec (10.8.3 - Special case: Unknown primary key class) says that in cases where the Primary Keys are generated automatically by the underlying database, the bean provider must declare the findByPrimaryKey method to return java.lang.Object and specify the Primary Key Class as java.lang.Object in the Deployment Descriptor.

52. When defining the Primary Key for the Enterprise Bean, the Deployer using the Container Provider's tools will typically add additional container-managed fields to the concrete subclass of the entity bean class. In this case, the Container must generate the Primary Key value when the entity bean instance is created (and before ejbPostCreate is invoked on the instance.)

53. What is clustering? Clustering is grouping machines together to transparently provide enterprise services. Clustering is an essential piece to solving the needs for today's large websites. The client does not know the difference between approaching one server and approaching a cluster of servers.

54. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable. This has to be consider as "passed-by-value", that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.

55. If my session bean with single method insert record into 2 entity beans, how can know that the process is done in same transaction (the attributes for these beans are Required)? If your session bean is using bean-managed transactions, you can ensure that the calls are handled in the same transaction by : javax.transaction.UserTransaction tran= null; try{ tran=ctx.getUserTransaction(); tran.begin(); myBeanHome1.create(....); myBeanHome2.create(...); tran.commit(); }catch(...){}

You may want to check if you're already running in a transaction by calling tran.getStatus().

56. When should I adopt BMP and when I should use CMP? You can use CMP and BMP beans in the same application... obviously, a bean can be BMP or CMP, not both at the same time (they are mutually exclusive). There is a common approach that is normally used and considered a good one. You should start developing CMP beans, unless you require some kind of special bean, like multi-tables, that cannot be completely realized with a single bean. Then, when you realize that you need something more or that you would prefer handling the persistence (performance issue are the most common reason), you can change the bean from a CMP to a BMP.

57. What's different in Enterprise JavaBeans 1.1? The most significant changes are listed below: • Entity bean support, both container- and bean-managed persistence, is required. • Java RMI-IIOP argument and reference types must be supported, but any protocol can still be used including IIOP, JRMP, HTTP, or a proprietary protocol. In other words, the client API must support the Java RMI-IIOP programming model for portability, but the underlying protocol can be anything. • The javax.ejb.depoyment package has been dropped in favor of a XML based deployment descriptor • Declarative security authorization (access control) has changed to be more role driven. Also the runAs declarations have been eliminated. • Declarative isolation levels are no longer available. Isolation levels are now managed explicitly through JDBC (BMP), the database or other vendor specific mechanisms. • The bean-container contract as been enhanced to include a default JNDI context for accessing properties, resources, (JDBC, JMS, etc), and other beans. • The basic EJB roles have been expanded and redefined to better separate responsibilities involved in the development, deployment, and hosting of enterprise beans.

58. What is Enterprise JavaBeans? Enterprise JavaBeans (EJB) is Sun Microsystems' specification for a distributed object system similar to CORBA and Microsoft Transaction Server, but based on the Java platform. EJB specifies how developers should build components that can be accessed remotely and how EJB vendors should support those components. EJB components, called enterprise beans, automatically handle transactions, persistence, and authorization security, so that the developer can focus on the business logic.

59. What is an enterprise bean? An enterprise bean is a server-side component -- defined in the Java technology -- which adheres to the Enterprise JavaBeans server-side component model. A server-side component is business object that can be accessed remotely. Many server-side component models exist: CORBA specifies CORBA objects; Microsoft Transaction Server (MTS) defines COM/DCOM; and EJB specifies enterprise beans. Enterprise beans can be developed to represent business concepts like Employee, Order, Travel Agent, etc. Enterprise beans can be assembled into applications that solve enterprise business problems. EJB has two basic types of enterprise beans: Session and Entity. Depending on the type of enterprise bean used, features like persistence, transactions, security, and multiple concurrent access can be managed automatically.

60. Are Enterprise JavaBeans and JavaBeans the same thing? Enterprise JavaBeans and JavaBeans are not the same thing; nor is one an extension of the other. They are both component models, based on Java, and created by Sun Microsystems, but their purpose and packages (base types and interfaces) are completely different. JavaBeans The original JavaBeans specification is based on the java.beans package which is a standard package in the JDK. Components built on the JavaBeans specification are intraprocess components that live in one address space and are typically used for Graphical User Interface (GUI) as visual widgets like buttons, tables, HTML viewers, etc. Enterprise JavaBeans The EJB specification is based on the javax.ejb package, which is a standard extension package. Components built on the EJB specification are intraprocess components that live in multiple address spaces as distributed object. These components are used as transactional business objects that are accessed as remote objects.

61. How does passivation work in stateful session beans? Unlike entity beans and stateless session beans, stateful session bean are usually evicted from memory when they are passivated. This is not true of all vendors but this view serves as good model for understanding the concepts of passivation in session beans. When a stateful bean experiences a lull in use -- between client invocations and transactions -the container may choose to passivate the stateful bean instance. To conserve resources the bean instance is evicted from memory (dereferenced and garbage collected). When the EJB object receives a new client request, a new stateful instance is instantiated and associate with the EJB object to handle the request. Stateful beans maintain a conversational state, which must be preserved before the bean instance is evicted from memory. To accomplish this, the container will write the conversational state of the bean instance to a secondary storage (usually disk). Only the non-transient serializable instance fields are preserved. When the bean is activated the new instance is populated with the preserved state. References to live resources like the EJBContext, DataSource, JNDI ENC, and other beans must also be maintained somehow -- usually in memory -- by the container. The javax.ejb.SessionBean interface provides two callback methods that notify the bean instance it is about to passivated or was just activated. The ejbPassivate( ) method notifies the bean instance that it is about have its conversational state written to disk and be evicted from memory. Within this method the bean developer can perform operations just prior to passivation like closing open resources. The ejbActivate( ) method is executed just after a new bean instance has been instantiated and populated with conversational state from disk. The bean developer can use the ejbActivate( ) method to perform operations just prior to servicing client request, like opening resources.

62. How does a client application create a transaction object? How you gain access to UserTransaction objects varies depending on the type of client. Enterprise JavaBeans provides two types of transaction management: • Container-managed transactions. As the name implies, the EJB container makes the decisions (based on the deployment descriptor's trans-attribute setting) regarding how to bundle operations into transactions and then works with the transaction manager, which manages the transaction processing. • Bean-managed transactions. In this case, a session bean obtains the UserTransaction object via the EJBContext using the getUserTransaction() method.

JMS clients can bundle several messages in a transaction simply by using a transactional session-a UserTransaction object is not required. To create a transactional session, use either QueueConnection.createQueueSession() or TopicConnection.createTopicSession() with true as the first argument. (Some JMS implementations support JTA, so that it's also possible to obtain a UserTransaction object from the JMS server.) In other environments, for example, a web server that supports servlets and/or JavaServer Pages (JSP), a JMS server, and others, you obtain a UserTransaction object via JNDI. Of course, for a servlet to obtain a UserTransaction object, there must be a JTS-capable server to deliver the object. Typically, the server provides the JNDI look-up name either directly or via a system or server property. For example, with the WebLogic server, you would use a code segment similar to the following: ... Context c = new InitialContext(); UserTransaction ut = (UserTransaction) c.lookup("javax.jts.UserTransaction"); ut.begin(); // perform multiple operations... ut.commit() ... With J2EE implementations, you obtain the UserTransaction object with a code segment similar to the following: ... Context c = new InitialContext(); UserTransaction ut = (UserTransaction) c.lookup("java:comp/UserTransaction"); ut.begin(); // perform multiple operations... ut.commit() ... If the environment provides the UserTransaction object via a system property, you would use a code segment similar to the following: ... String transName = System.getProperty("jta.UserTransaction"); Context c = new InitialContext(); UserTransaction ut = (UserTransaction) c.lookup(transName); ut.begin(); // perform multiple operations... ut.commit() ... JNDI remote look-up names and property names vary, of course, across servers/environment.

63. Do JTS implementations support nested transactions? A JTS transaction manager must support flat transactions; support of nested transactions is optional. If a client begins a transaction, and within that transaction begins another transaction, the latter operation will throw a NotSupportedException if the JTS implementation does not support nested transactions.

Keep in mind that even if the JTS implementation supports nested transactions, this transaction manager-level support does not guarantee support for nested transactions in an application. For example, the EJB 1.1 specification does not support nested transactions.

64. Why would a client application use JTA transactions? One possible example would be a scenario in which a client needs to employ two (or more) session beans, where each session bean is deployed on a different EJB server and each bean performs operations against external resources (for example, a database) and/or is managing one or more entity beans. In this scenario, the client's logic could required an all-or-nothing guarantee for the operations performed by the session beans; hence, the session bean usage could be bundled together with a JTA UserTransaction object. In the previous scenario, however, the client application developer should address the question of whether or not it would be better to encapsulate these operations in yet another session bean, and allow the session bean to handle the transactions via the EJB container. In general, lightweight clients are easier to maintain than heavyweight clients. Also, EJB environments are ideally suited for transaction management.

65. How does a session bean obtain a JTA UserTransaction object? If it's necessary to engage in explicit transaction management, a session bean can be designed for bean-managed transactions and obtain a UserTransaction object via the EJBContext using the getUserTransaction() method. (It may also use JNDI directly, but it's simpler to use this convenience method.)

66. Why would a session bean use bean-managed transactions? In some situations, it's necessary for a (stateful) session bean to selectively control which methods participate in transactions, and then take over the bundling of operations that form a logical unit of work.

67. How does an enterprise bean that uses container-managed transactions obtain a JTA UserTransaction object? It doesn't! By definition, container-managed transaction processing implies that the EJB container is responsible for transaction processing. The session bean has only limited control of transaction handling via the transaction attribute.

68. Is it possible for a stateless session bean to employ a JTA UserTransaction object? Yes, but with restrictions. By definition, a stateless session bean has no state; hence, each method invocation must be independent. (The bean can be "swapped out" between method invocations.) Thus, a stateless session bean can obtain a UserTransaction object via the EJBContext using the getUserTransaction() method, but it must start and finish each transaction within the scope of a method invocation.

69. How do you configure a session bean for bean-managed transactions? You must set transaction-type in the deployment descriptor.

70. How does an entity bean obtain a JTA UserTransaction object? It doesn't. Entity beans do not employ JTA transactions; that is, entity beans always employ declarative, container-managed transaction demarcation. Entity beans, by definition, are somewhat tightly coupled (via the EJB container and server) to a datastore; hence, the EJB container is in the best position to manage transaction processing.

71. Is it necessary for an entity bean to protect itself against concurrent access from multiple transactions? No. One of the motivations for using a distributed component architecture such as Enterprise JavaBeans is to free the business logic programmer from the burdens that arise in multiprogramming scenarios.

72. What are the constraints or drawbacks of container managed EJB's? CMP in beans depends a lot on the EJB vendor implementation and utilities. With some implementations container-managed entity beans can only by mapped to one table, while other implemenations offer Multiple table mappings to a single bean. The bottom line,It depends on the container provider being used.

73. Is entity data persisted at the end of a transaction or at any time? Depends on what you mean by "persisted". Data that is part of a transaction like database rows are persisted depending on the success of the transaction. If the transaction manager determines that the transaction was successful or there were no problems during any of the steps invoved in it, the data is committed, or otherwise rolled back. The container, on the other hand, invokes certain state transition lifecycle methods to conserve resources. This involves passivation and activation of the bean or instance swapping. This happens independent of the transaction since the client never interacts directly with the bean instance but with the server's implementation of the EJBObject.

74. How do enterprise beans access native libraries? In short, they don't. The EJB 1.1 Specification, section 18.1.2 (Programming Restrictions) lists some things that enterprise beans cannot do. In particular: · The enterprise bean must not attempt to load a native library. This function is reserved for the EJB Container. Allowing the enterprise bean to load

JSF Interview Questions 1) What is JSF? JSF stands for Java Server Faces. JSF has set of pre-assembled User Interface (UI). By this it means complex components are pre-coded and can be used with ease. It is event-driven programming model. By that it means that JSF has all necessary code for event handling and component organization. Application programmers can concentrate on application logic rather sending effort on these issues. It has component model that enables third-party components to be added like AJAX.

2) What is required for JSF to get started? Following things required for JSF: • • • •

JDK (Java SE Development Kit) JSF 1.2 Application Server (Tomcat or any standard application server) Integrated Development Environment (IDE) Ex. Netbeans 5.5, Eclipse 3.2.x, etc.

Once JDK and Application Server is downloaded and configured, one can copy the JSF jar files to JSF project and could just start coding. :-) If IDE is used, it will make things very smooth and will save your time.

3) What is JSF architecture? JSF was developed using MVC (a.k.a Model View Controller) design pattern so that applications can be scaled better with greater maintainability. It is driven by Java Community Process (JCP) and has become a standard. The advantage of JSF is that it’s both a Java Web user – interface and a framework that fits well with the MVC. It provides clean separation between presentation and behavior. UI (a.k.a User Interface) can be created by page author using reusable UI components and business logic part can be implemented using managed beans.

4) How JSF different from conventional JSP / Servlet Model? JSF much more plumbing that JSP developers have to implement by hand, such as page navigation and validation. One can think of JSP and servlets as the “assembly language� under the hood of the high-level JSF framework.

5) How the components of JSF are rendered? An Example In an application add the JSF libraries. Further in the .jsp page one has to add the tag library like: <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> Or one can try XML style as well: <jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> Once this is done, one can access the JSF components using the prefix attached. If working with

an IDE (a.k.a Integrated Development Environment) one can easily add JSF but when working without them one also has to update/make the faces-config.xml and have to populate the file with classes i.e. Managed Beans between tags

6) How to declare the Navigation Rules for JSF? Navigation rules tells JSF implementation which page to send back to the browser after a form has been submitted. For ex. for a login page, after the login gets successful, it should go to Main page, else to return on the same login page, for that we have to code as: /login.jsp login /main.jsp fail /login.jsp from-outcome to be match with action attribute of the command button of the login.jsp as: Secondly, it should also match with the navigation rule in face-config.xml as <managed-bean> <managed-bean-name>user <managed-bean-class>core.jsf.LoginBean <managed-bean-scope>session In the UI component, to be declared / used as: value attribute refers to name property of the user bean.

7) How do I configure the configuration file? The configuration file used is our old web.xml, if we use some IDE it will be pretty simple to generate but the contents will be something like below: <web-app version="e;2.4"e; xmlns="e;http://java.sun.com/xml/ns/j2ee"e; xmlns:xsi="e;http://www.w3.org/2001/XMLSchema-instance"e; xsi:schemaLocation="e;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"e;> <param-name>com.sun.faces.verifyObjects <param-value>false

<param-name>com.sun.faces.validateXml <param-value>true <param-name>javax.faces.STATE_SAVING_METHOD <param-value>client <servlet> <servlet-name>Faces Servlet <servlet-class>javax.faces.webapp.FacesServlet 1 <servlet-mapping> <servlet-name>Faces Servlet /faces/* <session-config> <session-timeout> 30 <welcome-file-list> <welcome-file> index.jsp The unique thing about this file is ?servlet mapping?. JSF pages are processed by a servlet known to be part of JSF implementation code. In the example above, it has extension of .faces. It would be wrong to point your browser to http://localhost:8080/MyJSF/login.jsp, but it has to be http://localhost:8080/MyJSF/login.faces. If you want that your pages to be with .jsf, it can be done with small modification :-), <servlet-mapping> <servlet-name>Faces Servlet *.jsf <servlet-mapping>

8) What is JSF framework? JSF framework can be explained with the following diagram: As can be seen in Figure 1, JSF interacts with Client Devices which ties together with presentation, navigation and event handling and business logic of web tier model. Hence JSF is

limited to presentation logic / tier. For Database tier i.e. Database and Web services one has to rely on other services.

9) How does JSF depict the MVC (a.k.a Model View Controller) model? The data that is manipulated in form or the other is done by model. The data presented to user in one form or the other is done by view. JSF is connects the view and the model. View can be depicted as shown by: JSF acts as controller by way of action processing done by the user or triggering of an event. For ex. , this button event will triggered by the user on Button press, which will invoke the login Bean as stated in the faces-config.xml file. Hence, it could be summarized as below: User Button Click -> form submission to server -> invocation of Bean class -> result thrown by Bean class caught be navigation rule -> navigation rule based on action directs to specific page.

10) What does it mean by rendering of page in JSF? Every JSF page as described has various components made with the help of JSF library. JSF may contain h:form, h:inputText, h:commandButton, etc. Each of these are rendered (translated) to HTML output. This process is called encoding. The encoding procedure also assigns each component with a unique ID assigned by framework. The ID generated is random.

11) What is JavaServer Faces? JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-of-use in the following ways: • • • • •

Makes it easy to construct a UI from a set of reusable UI components Simplifies migration of application data to and from the UI Helps manage UI state across server requests Provides a simple model for wiring client-generated events to server-side application code Allows custom UI components to be easily built and re-used

Most importantly, JSF establishes standards which are designed to be leveraged by tools to provide a developer experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems programmers. A "corporate developer" is characterized as an individual who is proficient in writing procedural code and business logic, but is not necessarily skilled in object-oriented programming. A "systems programmer" understands object-oriented fundamentals, including abstraction and designing for re-use. A corporate developer typically relies on tools for development, while a system programmer may define his or her tool as a text editor for writing code. Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can be used outside of tools, as is sometimes required by systems programmers.

12) How to pass a parameter to the JSF application using the URL string? if you have the following URL: http://your_server/your_app/product.jsf?id=777, you access the passing parameter id with the following lines of java code:

FacesContext fc = FacesContext.getCurrentInstance(); String id = (String) fc.getExternalContext().getRequestParameterMap().get("id"); From the page, you can access the same parameter using the predefined variable with name param. For example, Note: You have to call the jsf page directly and using the servlet mapping.

13) How to add context path to URL for outputLink? Current JSF implementation does not add the context path for outputLink if the defined path starts with '/'. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example:

14) How to get current page URL from backing bean? You can get a reference to the HTTP request object via FacesContext like this: FacesContext fc = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest(); and then use the normal request methods to obtain path information. Alternatively, context.getViewRoot().getViewId(); will return you the name of the current JSP (JSF view IDs are basically just JSP path names).

15) How to access web.xml init parameters from java code? You can get it using externalContext getInitParameter method. For example, if you have: <param-name>connectionString <param-value>jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB You can access this connection string with: FacesContext fc = FacesContext.getCurrentInstance(); String connection = fc.getExternalContext().getInitParameter("connectionString");

16) How to access web.xml init parameters from jsp page? You can get it using initParam pre-defined JSF EL valiable. For example, if you have: <param-name>productId <param-value>2004Q4

You can access this parameter with #{initParam['productId']} . For example: Product Id:

17) How to terminate the session? In order to terminate the session you can use session invalidate method. This is an example how to terminate the session from the action method of a backing bean: public String logout() { FacesContext fc = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) fc.getExternalContext().getSession(false); session.invalidate(); return "login_page"; } The following code snippet allows to terminate the session from the jsp page: <% session.invalidate(); %>

18) How to implement "Please, Wait..." page? The client-side solution might be very simple. You can wrap the jsp page (or part of it you want to hide) into the DIV, then you can add one more DIV that appears when user clicks the submit button. This DIV can contain the animated gif you speak about or any other content. Scenario: when user clicks the button, the JavaScript function is called. This function hides the page and shows the "Wait" DIV. You can customize the look-n-fill with CSS if you like. This is a working example: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> Input Name Page <script> function gowait() { document.getElementById("main").style.visibility="hidden"; document.getElementById("wait").style.visibility="visible"; }


required="true">

If you want to have an animated gif of the "Wait" Page, the gif should be reloaded after the form is just submitted. So, assign the id for your image and then add reload code that will be called after some short delay. For the example above, it might be: <script> function gowait() { document.getElementById("main").style.visibility="hidden"; document.getElementById("wait").style.visibility="visible"; window.setTimeout('showProgress()', 500); } function showProgress(){ var wg = document.getElementById("waitgif"); wg.src=wg.src; } .... .... ....

19) How to reload the page after ValueChangeListener is invoked? At the end of the ValueChangeListener, call FacesContext.getCurrentInstance().renderResponse()

20) How to download PDF file with JSF? This is an code example how it can be done with action listener of the backing bean. Add the following method to the backing bean: public void viewPdf(ActionEvent event) { String filename = "filename.pdf"; // use your own method that reads file to the byte array byte[] pdf = getTheContentOfTheFile(filename);

FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); response.setContentType("application/pdf"); response.setContentLength(pdf.length); response.setHeader( "Content-disposition", "inline; filename=\""+fileName+"\""); try { ServletOutputStream out; out = response.getOutputStream(); out.write(pdf); } catch (IOException e) { e.printStackTrace(); } faces.responseComplete(); } This is a jsp file snippet:

21) How to show Confirmation Dialog when user Click the Command Link? h:commandLink assign the onclick attribute for internal use. So, you cannot use it to write your own code. This problem will fixed in the JSF 1.2. For the current JSF version you can use onmousedown event that occurs before onclick. <script language="javascript"> function ConfirmDelete(link) { var delete = confirm('Do you want to Delete?'); if (delete == true) { link.onclick(); } } . . . .

22) What is the different between getRequestParameterMap() and getRequestParameterValuesMap()? getRequestParameterValuesMap() similar to getRequestParameterMap(), but contains multiple values for for the parameters with the same name. It is important if you one of the components such as .

23) Is it possible to have more than one Faces Configuration file? Yes. You can define the list of the configuration files in the web.xml. This is an example: <param-name>javax.faces.CONFIG_FILES <param-value>/WEB-INF/faces-config-navigation.xml,/WEB-INF/facesbeans.xml Note: Do not register /WEB-INF/faces-config.xml file in the web.xml . Otherwise, the JSF implementation will process it twice. Hi there, I guess the Note: column should have been meant or intended for "faces-config.xml" file as thats the default configuration file for JSF (which is similar to struts-config.xml for Struts!!). faces-context.xml file sounds like the user defined config file similar to the

aforementioned two xml files.

24) How to mask actual URL to the JSF page? You'll need to implement your own version of javax.faces.ViewHandler which does what you need. Then, you register your own view handler in faces-config.xml. Here's a simple abstract ViewHandler you can extend and then implement the 3 abstract methods for. The abstract methods you override here are where you'll do your conversions to/from URI to physical paths on the file system. This information is just passed right along to the default ViewHandler for JSF to deal with in the usual way. For example, you could override these methods to add and remove the file extension of an incoming view id (like in your example), for extension-less view URIs. import java.io.IOException; import java.util.Locale; import import import import

javax.faces.FacesException; javax.faces.application.ViewHandler; javax.faces.component.UIViewRoot; javax.faces.context.FacesContext;

import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A facade view handler which maps URIs into actual physical views that the * underlying implementation can deal with regularly. * Therefore, all internal references to view ids, for example in faces-config, * will use the path to the physical files. Everything publicized, however, will * see a "converted" / facade url. */ public abstract class SimpleConverterViewHandler extends ViewHandler { private static final Log LOG = LogFactory.getLog(SimpleConverterViewHandler.class); private final ViewHandler base; public SimpleConverterViewHandler(ViewHandler base) { this.base = base; } /** * Distinguishes a URI from a physical file view. * Tests if a view id is in the expected format -- the format corresponding * to the physical file views, as opposed to the URIs. * This test is necessary because JSF takes the view ID from the * faces-config navigation, and calls renderView() on it, etc. */ public abstract boolean isViewFormat(FacesContext context, String viewId); /** * Convert a private file path (view id) into a public URI. */ public abstract String convertViewToURI(FacesContext context, String viewId); /**

* Convert a public URI into a private file path (view id) * note: uri always starts with "/"; */ public abstract String convertURIToView(FacesContext context, String uri); public String getActionURL(FacesContext context, String viewId) { // NOTE: this is used for FORM actions.

}

String newViewId = convertViewToURI(context, viewId); LOG.debug("getViewIdPath: " + viewId + "->" + newViewId); return base.getActionURL(context, newViewId);

private String doConvertURIToView(FacesContext context, String requestURI) { if (isViewFormat(context, requestURI)) { return requestURI; } else { return convertURIToView(context, requestURI); } } public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesException { if (null == context || null == viewToRender) throw new NullPointerException("null context or view"); String requestURI = viewToRender.getViewId(); String newViewId = doConvertURIToView(context, requestURI); LOG.debug("renderView: " + requestURI + "->" + newViewId); viewToRender.setViewId(newViewId); base.renderView(context, viewToRender); } public UIViewRoot restoreView(FacesContext context, String viewId) { String newViewId = doConvertURIToView(context, viewId); LOG.debug("restoreView: " + viewId + "->" + newViewId); return base.restoreView(context, newViewId); } public Locale calculateLocale(FacesContext arg0) { return base.calculateLocale(arg0); } public String calculateRenderKitId(FacesContext arg0) { return base.calculateRenderKitId(arg0); } public UIViewRoot createView(FacesContext arg0, String arg1) { return base.createView(arg0, arg1); } public String getResourceURL(FacesContext arg0, String arg1) { return base.getResourceURL(arg0, arg1); }

public void writeState(FacesContext arg0) throws IOException { base.writeState(arg0); } }

25) How to print out html markup with h:outputText? The h:outputText has attribute escape that allows to escape the html markup. By default, it equals to "true". It means all the special symbols will be replaced with '&' codes. If you set it to "false", the text will be printed out without ecsaping. For example, will be printed out like: This is a text In case of you will get: This is a text

26) h:inputSecret field becomes empty when page is reloaded. How to fix this? Set redisplay=true, it is false by default.

Design Patterns Interview Questions 1) What is a software design pattern? A design pattern is a solution to a general software problem within a particular context.

• Context : A recurring set of situations where the pattern applies. • Problem : A system of forces (goals and constraints) that occur repeatedly in this •

context. Solution : A description of communicating objects and classes (collaboration) that can be applied to resolve those forces.

Design patterns capture solutions that have evolved over time as developers strive for greater flexibility in their software. Whereas class libraries are reusable source code, and components are reusable packaged objects, patterns are generic, reusable design descriptions that are customized to solve a specific problem. The study of design patterns provides a common vocabulary for communication and documentation, and it provides a framework for evolution and improvement of existing patterns.

2) Why is the study of patterns important? As initial software designs are implemented and deployed, programmers often discover improvements which make the designs more adaptable to change. Design patterns capture solutions that have evolved over time as developers strive for greater flexibility in their software, and they document the solutions in a way which facilitates their reuse in other, possibly unrelated

systems. Design patterns allow us to reuse the knowledge of experienced software designers. Moreover, the study of design patterns provides a common vocabulary for communication and documentation, and it provides a framework for evolution and improvement of existing patterns. As an analogy, consider that during a discussion among programmers, the words “stack” and “tree” can be used freely without explanation. Software developers understand fundamental data structures such as a “stack” because these data structures are well-documented in textbooks and are taught in computer science courses. The study of design patterns will have a similar (but more profound) effect by allowing designers to say “composite pattern” or “observer pattern” in a particular design context, without having to describe all classes, relationships, and collaborations which make up the pattern. Patterns raise the level of abstraction when discussing and documenting software designs.

3) How do I document a design pattern? A pattern description must address the following major points:

• Pattern Name and Classification : A short, meaningful name for the pattern, usually





• •

only one or two words. Names provide a vocabulary for patterns, and they have implied semantics – choose names carefully. Following the GoF book, we can also group patterns into higher level classifications such as creational, structural, and behavioral patterns. Problem : A general description of the problem context and the goals and constraints that occur repeatedly in that context. A concrete motivational scenario can be used to help describe the problem. The problem description should provide guidance to assist others in recognizing situations where the pattern can be applied. Solution : The classes and/or objects that participate in the design pattern, their structure (e.g., in terms of a UML class diagram), their responsibilities, and their collaborations. The solution provides an abstract description that can be applied in many different situations. Sample Code in an object-oriented language can be used to illustrate a concrete realization of the pattern. Consequences : A discussion of the results and tradeoffs of applying the pattern. Variations and language-dependent alternatives should also be addressed. Known Uses : Examples of the pattern in real systems. Look for applications of the pattern in language libraries and frameworks, published system descriptions, text books, etc. Not every good solution represents a pattern. A general rule of thumb is that a candidate pattern (also called a “proto-pattern”) should be discovered in a minimum of three existing systems before it can rightfully be called a pattern.

The following quote by Robert Martin highlights the importance of providing pattern descriptions: “The revolutionary concept of the GoF book is not the fact that there are patterns; it is the way in which those patterns are documented. ... Prior to the GoF book, the only good way to learn patterns was to discover them in design documentation, or (more probably) code.”

4) Where can I learn more about design patterns? The best place to start is the seminal work by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (collectively known as the “Gang of Four” or simply “GoF”) entitled Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995). Warning: This book is not light reading. From the Preface: “Don't worry if you don't understand this book completely on the first reading. We didn't understand it all on the first writing.” It is, however, a book which wears well over time, and it is definitely worth the effort required to work through it. Beyond the GoF book, consider the list of references in the Design Patterns section of this

bibliography on object technology, plus the following web links:

• • • •

Design Patterns Home Page Huston Design Patterns Brad Appleton's Software Patterns Links Cetus Patterns Links

5) What is an example of a design pattern? Following the lead of the “Gang of Four” (GoF), design pattern descriptions usually contain multiple sections including 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.

Intent Motivation Applicability Structure Participants Collaborations Consequences Implementation Sample Code Known Uses Related Patterns

A complete discussion of even a small pattern is beyond the scope of a simple FAQ entry, but it is possible to get the idea by examining an abbreviated discussion of one of the simplest and most easily understood patterns. Consider the Singleton pattern, whose intent reads as follows: Intent: Ensure that a class has one instance, and provide a global point of access to it. Almost every programmer has encountered this problem and formulated an approach for solving it in a general way – some solutions are better than others. The solution offered by the GoF would look something like the following when coded in Java. public class Singleton { private static Singleton instance = null; public static Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } protected Singleton() { ... } // possibly another constructor form public void someMethod() { ... } }

//... other methods

The programmer would access the single instance of this class by writing something similar to Singleton.getInstance().someMethod() or similar to

Singleton s = Singleton.getInstance(); s.method1(); ... s.method2(); ... For a more complete discussion of the Singleton pattern, see the chapter “Singleton” in the book Design Patterns: Elements of Reusable Object-Oriented Software by the “Gang of Four” (AddisonWesley, 1995), or the chapter “Singleton” in the book Patterns in Java, Volume 1 by Mark Grand (John Wiley & Sons, 1998). For information about variations on the Singleton Pattern, see the chapter entitled “To Kill a Singleton” in the book Pattern Hatching: Design Patterns Applied by John Vlissides or the article “Implementing the Singleton Pattern in Java” by Rod Waldhoff.

6) Calendar is an abstract class. The getInstance() method tries to instantiate GregorianCalendar() i.e., parent instantiating a derived class. This looks Non-OO? Ex: Calendar a=Calendar.getInstance(); Can somebody explain why is it so? The Calender class is an abstact class, true, however,the point you missed is that the getInstance() returns the " Calendar using the default timezone and locale. " , in your case, the GregorianCalender a class that IS a Calender (a Suzuki IS a car, a 747 IS a plane..the standard OO terminology. So what you get is a class that does some specialized work based on the default locale. Other methods public static synchronized Calendar getInstance(TimeZone zone,Locale aLocale) public static synchronized Calendar getInstance(TimeZone zone) return Calenders for specific timezones and locales. The closest parallel is possibly the Factory Method design pattern.

7) What major patterns do the Java APIs utilize? Design patterns are used and supported extensively throughout the Java APIs. Here are some examples: 20. The Model-View-Controller design pattern is used extensively throughout the Swing API. 21. The getInstance() method in java.util.Calendar is an example of a simple form of the Factory Method design pattern. 22. The classes java.lang.System and java.sql.DriverManager are examples of the Singleton pattern, although they are not implemented using the approach recommended in the GoF book but with static methods. 23. The Prototype pattern is supported in Java through the clone() method defined in class Object and the use of java.lang.Cloneable interface to grant permission for cloning. 24. The Java Swing classes support the Command pattern by providing an Action interface and an AbstractAction class. 25. The Java 1.1 event model is based on the observer pattern. In addition, the interface java.util.Observable and the class java.util.Observer provide support for this pattern. 26. The Adapter pattern is used extensively by the adapter classes in java.awt.event. 27. The Proxy pattern is used extensively in the implementation of Java's Remote Method Invocation (RMI) and Interface Definition Language (IDL) features. 28. The structure of Component and Container classes in java.awt provide a good example of the Composite pattern. 29. The Bridge pattern can be found in the separation of the components in java.awt

(e.g., Button and List), and their counterparts in java.awt.peer.

8) How can I make sure at most one instance of my class is ever created? This is an instance where the Singleton design pattern would be used. You need to make the constructor private (so nobody can create an instance) and provide a static method to get the sole instance, where the first time the instance is retrieved it is created: public class Mine { private static Mine singleton; private Mine() { } public static synchronized Mine getInstance() { if (singleton == null) { singleton = new Mine(); } return singleton; } // other stuff... }

9) When would I use the delegation pattern instead of inheritence to extend a class's behavior? Both delegation and inheritance are important concepts in object-oriented software design, but not everyone would label them as patterns. In particular, the seminal book on design patterns by the “Gang of Four” contains a discussion of inheritance and delegation, but the authors do not treat these topics as specific patterns. It is reasonable to think of them as design concepts which are more general than specific design patterns. Inheritance is a relationship between two classes where one class, called a subclass in this context, inherits the attributes and operations of another class, called its superclass. Inheritance can be a powerful design/reuse technique, especially when it is used in the context of the Liskov Substitution Principle. (The article by Robert Martin at http://www.objectmentor.com/publications/lsp.pdf provides an excellent explanation of the ideas behind Barbara Liskov’s original paper on using inheritance correctly.) The primary advantages of inheritance are • it is directly supported by object-oriented languages, and • it provides the context for polymorphism in strongly-typed object-oriented languages such as C++ and Java. But since the inheritance relationship is defined at compile-time, a class can’t change its superclass dynamically during program execution. Moreover, modifications to a superclass automatically propagate to the subclass, providing a two-edged sword for software maintenance and reuse. In summary, inheritance creates a strong, static coupling between a superclass and its subclasses. Delegation can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation can also a powerful design/reuse technique. The primary advantage of delegation is run-time flexibility – the delegate can easily be changed at run-time. But unlike inheritance, delegation is not directly supported by most popular object-oriented languages, and it doesn’t facilitate dynamic polymorphism. As a simple example, consider the relationship between a Rectangle class and a Window class. With inheritance, a Window class would inherit its rectangular properties from class Rectangle. With delegation, a Window object would maintain a reference or pointer to a Rectangle object,

and calls to rectangle-like methods of the Window object would be delegated to corresponding methods of the Rectangle object. Now let’s consider a slightly more complex example. Suppose employees can classified based on how they are paid; e.g., hourly or salaried. Using inheritance, we might design three classes: an Employee class which encapsulates the functionality common to all employees, and two subclasses HourlyEmployee and SalariedEmployee which encapsulates pay-specific details. While this design might be suitable for some applications, we would encounter problems in a scenario where a person changes, say from hourly to salaried. The class of an object and the inheritance relationship are both static, and objects can’t change their class easily (but see the State pattern for tips on how to fake it). A more flexible design would involve delegation – an Employee object could delegate pay-related method calls to an object whose responsibilities focused solely on how the employee is paid. In fact, we might still use inheritance here in a slightly different manner by creating an abstract class (or interface) called PayClassification with two subclasses HourlyPayClassification and SalariedPayClassification which implement classification-specific computations. Using delegation as shown, it would be much easier to change the pay classification of an existing Employee object. This second example illustrates an important point: In implementing delegation, we often want the capability to replace the delegate with another object, possibly of a different class. Therefore delegation will often use inheritance and polymorphism, with classes of potential delegates being subclasses of an abstract class which encapsulates general delegate responsibilities. One final point. Sometimes, the choice between delegation and inheritance is driven by external factors such as programming language support for multiple inheritance or design constraints requiring polymorphism. Consider threads in Java. You can associate a class with a thread in one of two ways: either by extending (inheriting) directly from class Thread, or by implementing the Runnable interface and then delegating to a Thread object. Often the approach taken is based on the restriction in Java that a class can only extend one class (i.e., Java does not support multiple inheritance). If the class you want to associate with a thread already extends some other class in the design, then you would have to use delegation; otherwise, extending class Thread would usually be the simpler approach.

10) Which patterns were used by Sun in designing the Enterprise JavaBeans model? Many design patterns were used in EJB, and some of them are clearly identifiable by their naming convention. Here are several:

• Factory Method: Define a interface for creating classes, let a subclass (or a helper class) decide which class to instantiate.

This is used in EJB creation model. EJBHome defines an interface for creating the EJBObject implementations. They are actually created by a generated container class. See InitialContextFactory interface that returns an InitialContext based on a properties hashtable.

• Singleton: Ensure a class has only one instance, and provide a global point of access to it.

There are many such classes. One example is javax.naming.NamingManager

• Abstract Factory: Provide an interface for creating families of relegated or dependent objects without specifying their concrete classes.

We have interfaces called InitialContext, InitialContextFactory. InitialContextFactory has methods to get InitialContext.

• Builder: Separate the construction of a complex factory from its representation so that the same construction process can create different representations. InitialContextFactoryBuilder can create a InitialContextFactory.

• Adapter: Convert the interface of a class into another interface clients expect. In the EJB implementation model, we implement an EJB in a class that extends SessionBean or a EntityBean. We don't directly implement the EJBObject/home interfaces. EJB container generates a class that adapts the EJBObject interface by forwarding the calls to the enterprise bean class and provides declarative transaction, persistence support.

• Proxy: Provide a surrogate for other object to control access to it. We have remote RMI-CORBA proxies for the EJB's.

• Memento: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

Certainly this pattern is used in activating/passivating the enterprise beans by the container/server.

11) What is an analysis pattern? An analysis pattern is a software pattern not related to a language or implementation problem, but to a business domain, such as accounting or health care. For example, in health care, the patient visit activity would be subject to a number of patterns. There is a good overview from an OOPSLA '96 presentation at http://www.jeffsutherland.org/oopsla96/fowler.html A good text would be: Martin Fowler's Martin Analysis Patterns : Reusable Object Models, ISBN: 0201895420, published by Addison-Wesley. In summary, analysis patterns are useful for discovering and capturing business processes.

12) What are the differences between analysis patterns and design patterns? Analysis pattern are for domain architecture, and design pattern are for implementation mechanism for some aspect of the domain architecture. In brief, analysis pattern are more high level and more (end-user) functional oriented.

13) How does "Extreme Programming" (XP) fit with patterns? Extreme Programming has a large emphasis on the concept of refactoring: Writing code once and only once. Patterns, particularly the structural patterns mentioned by the Gang of Four, can give good pointers about how to acheive that goal. (XP states when and where factoring should happen, patterns can show you how.)

14) What is the disadvantage of using the Singleton pattern? It is enticing to use this pattern for all the classes as it makes it easy to get the reference of the singleton object. The intent of the Singleton pattern is to ensure a class has only one instance and to provide a global point of access to it. True, the second part about providing a global point of access is

enticing, but the primary disadvantage of using the Singleton pattern for all classes is related to the first part of the intent; i.e., that it allows only one instance of the class. For most classes in an application, you will need to create multiple instances. What purpose would a Customer class serve if you could create only one Customer object?

15) How do you write a Thread-Safe Singleton? I have written plenty of non-thread-safe Singletons but it wasn't until recently when I tracked it down that I realized that thread-safety could be a big problem. The problem is that in the typical Singleton implementation (at least the ones I've seen) there is the ability to create multiple versions of the single instance...I know, "But How?". Well, in the getInstance() call the instance is checked for null, and then immediately constructed if it is null, and then the instance is returned. The problem is that the thread (Ta) making the call could swap-out immediately after checking for a null. A subsequent thread (Tb) could then make a call to get the instance and construct an instance of the Singleton. When the original thread (Ta) is then swapped back in, it would construct and return a completely separate object. BAD KITTY! The following code snippet shows an example of a thread-safe Singleton. package com.jgk.patterns.singleton; public class JGKSingleton { /* Here is the instance of the Singleton */ private static JGKSingleton instance_; /* Need the following object to synchronize */ /* a block */ private static Object syncObject_; /* Prevent direct access to the constructor private JGKSingleton() { super(); }

}

public static JGKSingleton getInstance() { /* in a non-thread-safe version of a Singleton */ /* the following line could be executed, and the */ /* thread could be immediately swapped out */ if (instance_ == null) { synchronized(syncObject_) { if (instance_ == null) { instance_ = new JGKSingleton(); } } } return instance_; }

NOTE: The 2nd check for if (instance_ == null) is needed to avoid making another unnecessary construct. Don't let this byte you! ;-)

16) What is the Reactor pattern? The new book "Pattern-oriented Software Architecture Volume 2" ISBN 0471606952 has a chapter on the Reactor pattern. It falls under the general category of "Event Handling Patterns". To quote the leading bit of the chapter, "The Reactor architectural pattern allows event-driven applications to demultiplex and dispatch service requests that are delivered to an application from one or more clients" It is used in a synchronous manner, so that if the callback you delegate the event to takes a while to complete you will run into problems with scalability.

17) What are Process Patterns? Basically process patterns define a collection of best practices, techniques, methods for developing object-oriented software. A good reference site is by Scott Ambler. He also has two books on the topic plus a white paper on the subject you can download. http://www.ambysoft.com/processPatternsPage.html.

18) How and where did the concept of design patterns get started? Work on patterns has been influenced by the works of Christopher Alexander who published on topics related to urban planning and building architecture in the late 1970s. The history of patterns for software design began in the late 1980s and reached an important milestone with the publishing of the first book fully dedicated to this subject by the "Gang of Four", Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns - Elements of Reusable Object-Oriented Software). In conjunction, the emergence of object-oriented software development fostered the work on other topics related to design patterns such as application frameworks, analysis patterns, language idioms, and so on.

19) Where can I find good examples of the Prototype pattern? The prototype pattern is actually quite simple to implement in Java. Recall that the idea of prototype is that you are passed an object and use that object as a template to create a new object. Because you might not know the implementation details of the object, you cannot create a new instance of the object and copy all of its data. (Some of the data may not be accessible via methods). So you ask the objectitself to give you a copy of itself. Java provides a simple interface named Cloneable that provides an implementation of the Prototype pattern. If you have an object that is Cloneable, you can call its clone() method to create a new instance of the object with the same values. The trick here is that you must override the clone() method to increase its visibility, and just call super.clone(). This is because the implementation of clone(), defined in java.lang.object, is protected. For example: public class CopyMe implements Cloneable { public Object clone() { return super.clone(); } } Note that Cloneable is an empty interface! It merely acts as a tag to state that you really want instance of the class to be cloned. If you don't implement Cloneable, the super.clone() implementation will throw a CloneNotSupportedException.

Related Documents

Interview Questions
May 2020 25
Interview Questions
October 2019 24
Interview Questions
November 2019 24
Interview Questions
November 2019 20
Interview Questions
November 2019 27
Interview Questions
November 2019 21

More Documents from ""