J2EE Interview Faq Imp

download J2EE Interview Faq Imp

of 29

Transcript of J2EE Interview Faq Imp

  • 7/29/2019 J2EE Interview Faq Imp

    1/29

    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 theyare document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page cancontain Java program fragments that instantiate and execute Java classes, but these occur inside an HTMLtemplate 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 aframework 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 andcompiles 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. Thismethod is invoked by the container only once when a JSP page is initialized. It can be overridden by a pageauthor to initialize resources such as database and network connections, and to allow a JSP page to readpersistent configuration data.

    4.What is the _jspService() method?

    The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new requestcomes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as itsarguments. 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 JSPpage is about to be destroyed. This method is similar to the destroy() method of servlets. It can beoverridden 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 databaseconnections, network connections, and so forth for the JSP page. It is good programming practice to free anyallocated 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 andare typically declared as JSP declarations:

  • 7/29/2019 J2EE Interview Faq Imp

    2/29

    %>

    8.What are implicit objects in JSP?

    Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in eachpage. 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 implicitobjects.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 areavailable 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 JSPpage 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, outputcontent 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 fromthe 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: Example:

    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?

  • 7/29/2019 J2EE Interview Faq Imp

    3/29

    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:

    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 responsesent back to the client.

    They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward arequest 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:

    : 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. : It forwards a response from a servlet or a JSP page to another page.

    : It makes a JavaBean available to a page and instantiates the bean.

    : It sets the properties for a JavaBean.

    : It gets the value of a property from a JavaBean component and adds it to the

    response.

    : It is used in conjunction with ;, ; to add a parameter

    to a request. These parameters are provided using the name-value pairs.

  • 7/29/2019 J2EE Interview Faq Imp

    4/29

    : It is used to include a Java applet or a JavaBean in the current JSP page.

    16.What is the standard action?

    The standard action is used to locate an existing JavaBean or to create a JavaBean if it doesnot exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specifythe fully qualified classpath and type.

    17.What are the scopes available in ?

    The scopes available in 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 standard action?

    The 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 standard action is :

    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 , anIllegalStateException will be thrown.

    Note : Whenever we intend to use or in a page, buffering should be enabled.By default buffer is enabled.

    19.What is the standard action?

    The standard action enables the current JSP page to include a static or a dynamic resource atruntime. 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 standard action isas follows: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 Include action

    The include directive, includes the content of thespecified file during the translation phasewhen thepage is converted to a servlet.

    The include action, includes the response generatedby executing the specified page (a JSP page or aservlet) during the request processing phasewhenthe page is requested by a user.

    The include directive is used to statically insert thecontents of a resource into the current JSP.

    The include standard action enables the current JSPpage to include a static or a dynamic resource atruntime.

  • 7/29/2019 J2EE Interview Faq Imp

    5/29

    Use the include directive if the file changes rarely. Itsthe fastest mechanism.

    Use the include action only for content that changesoften, and if which page to include cannot bedecided until the main page is requested.

    21.Differentiate between pageContext.include and jsp:include?

    The 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 beforeincluding the other components, whereas flushes the output of the current page only if thevalue of flush is explicitly set to true as follows:

    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 dothis in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, asbelow: ...

    In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or anexisting bean was found.

    A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below: ...

    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 action is used to access the properties of a bean that was set using the 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 correspondingWrapper class. The syntax of the method is:

    Here, name is the id of the bean from which the property was set. The property attribute is the property toget. A user must create or locate a bean using the action before using the action.

    24.What is the standard action?

    The standard action is used with or to pass parameter namesand values to the target resource. The syntax of the standard action is as follows:

    25.What is the jsp:plugin action ?

    This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browserrun 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 JSPpage. There are three forms:

    1. Expressions of the form that are evaluated and inserted into the output,

  • 7/29/2019 J2EE Interview Faq Imp

    6/29

    2. Scriptlets of the form that are inserted into the servlet's service method,

    3. Declarations of the form that are inserted into the body of the servlet class, outside ofany 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 aservlet, 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 tags and is executed by thecontainer 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. Theyare initialized when the class is initialized. Anything defined in a declaration is available for the whole JSPpage. A declaration block is enclosed between the tags. A declaration is not included in theservice()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 ashorthand representation for scriptlets. An expression is written between the tags. It is not

    required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressionswithin 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 asubelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is asfollows:

    *.jsptrue

    Struts Interview Questions

    1.What is MVC?

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

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

    View: The view provides the presentation of the model. It is the lookof the application. The view canaccess the model getters, but it has no knowledge of the setters. In addition, it knows nothing aboutthe 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 aspecific requirement.

    3.What is Struts framework?

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

  • 7/29/2019 J2EE Interview Faq Imp

    7/29

    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 Controllercomponent that handles client requests and determines which Action will process each received request. Itserves as an Action factory creating specific Action classes based on users 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 Viewreferencing 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 handedto Action. Returns a collection ofActionError as ActionErrors. Following is the method signature for thevalidate()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 todetermine 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 frameworkcreatesActionMapping object from configuration element of struts-config.xml file

  • 7/29/2019 J2EE Interview Faq Imp

    8/29

    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 thecorresponding 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 theRequestProcessor uses the template method design pattern. Struts also implement the following J2EE designpatterns.

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

    org.apache.struts.action.ActionServlet

    config

    /WEB-INF/struts-config.xml,

  • 7/29/2019 J2EE Interview Faq Imp

    9/29

    /WEB-INF/struts-admin.xml, /WEB-INF/struts-config-forms.xml

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

    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 amethod for each logical action compared than a single execute method. The DispatchAction dispatches to oneof the logical actions represented by the methods. It picks a method to invoke based on an incoming requestparameter. The value of the incoming parameter is the name of the method that the DispatchAction willinvoke.

    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.

  • 7/29/2019 J2EE Interview Faq Imp

    10/29

    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 youre trying to integrate Struts into an existing application that usesServlets to perform business logic functions. You can use this class to take advantage of the Struts controllerand 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 evenanother JSP page. By using this predefined action, you dont have to write your own Action class. You justhave 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 anotheraction or jsp. Use ForwardAction to forward a request to another resource in your application, such as aServlet 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 toget 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, theLookupDispatchAction 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 calledin 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 adifferent module. SwitchAction is useful only if you have multiple modules in your Struts application. TheSwitchAction class can be used as is, without extending.

    30.What ifelement hasdeclaration with same name as global forward?

    In this case the global forward is not used. Instead the elements 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 formbean.

    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:

  • 7/29/2019 J2EE Interview Faq Imp

    11/29

    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 toinclude 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 wellwhen custom page needed when error occurs. This approach applies only to exceptions thrown byActions.

    or

    38.What is difference between ActionForm and DynaActionForm?

    An ActionForm represents an HTML form that the user interacts with over one or more pages. Youwill 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. Insteadthese 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.

  • 7/29/2019 J2EE Interview Faq Imp

    12/29

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

    ActionForm can be cleanly organized in packages as against the flat organization in the Struts Configfile.

    ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate andencapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, theproperty 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 environmentby adding this file to struts-config.xml.

    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

    J2EE Interview Questions

    1) What is J2EE?

    J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of aset of services, application programming interfaces (APIs), and protocols that provide the functionality fordeveloping 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 componentdeployment 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 withits related classes and files and communicates with other components. The J2EE specification defines thefollowing 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

  • 7/29/2019 J2EE Interview Faq Imp

    13/29

    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:

    1. class files for enterprise beans2. 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:

    1. all Java interfaces,2. classes,3. native libraries,4. other documentation,5. 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 applicationcomponent 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 addXML tags according to interactive selections. A software developer performs the following tasks todeliver 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

  • 7/29/2019 J2EE Interview Faq Imp

    14/29

    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 5roles 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 supportsservice endpoints based on Servlets and enterprise beans. JAX-RPC 1.1 provides interoperability with Webservices based on the WSDL and SOAP protocols.

    The J2EE 1.4 platform also supports the Web Services for J2EE specification (JSR 921), which definesdeployment 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 Profile1.0. This means that in addition to platform independence and complete Web services support, J2EE 1.4offers platform Web services interoperability.

    The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information modelfor J2EE management, including the standard Management EJB (MEJB). The J2EE Management 1.0 API usesthe Java Management Extensions API (JMX).

    The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which provides a standard API fordeployment of J2EE applications.

    The J2EE 1.4 platform includes security enhancements via the introduction of the Java Authorization Contractfor Containers (JavaACC). The JavaACC API improves security by standardizing how authenticationmechanisms are integrated into J2EE containers.

    The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet andJavaServer Pages (JSP) technologies. Servlets now support request listeners and enhanced filters. JSPtechnology has simplified the page and extension development models with the introduction of a simple

  • 7/29/2019 J2EE Interview Faq Imp

    15/29

    expression language, tag files, and a simpler tag extension API, among other features. This makes it easierthan ever for developers to build JSP-enabled pages, especially those who are familiar with scriptinglanguages.

    Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides incomingresource 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-drivenbeans.

    The J2EE 1.4 platform also includes enhancements to deployment descriptors. They are now defined usingXML 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 clientmachine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handletasks such as J2EE system or application administration. It typically has a graphical user interface createdfrom Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connectionto 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. JavaBeanscomponents written for the J2EE platform have instance variables and get and set methods for accessing thedata in the instance variables. JavaBeans components used in this way are typically simple in design andimplementation, but should conform to the naming and design conventions outlined in the JavaBeanscomponent architecture.

    12) Is HTML page a web component?

    NO. Static HTML pages and applets are bundled with web components during application assembly, but arenot considered web components by the J2EE specification. Even the server-side utility classes are notconsidered web components, either.

    13) What is the container?

    A container is a runtime support of a system-level entity. Containers provide components with services suchas 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 querydatabases, 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 thatdescribes a component's deployment settings. A J2EE application and each of its modules has its owndeployment descriptor.

  • 7/29/2019 J2EE Interview Faq Imp

    16/29

    18)What is the EAR file?

    An EAR file is a standard JAR file with an .ear extension, named from Enterprise Archive file. A J2EEapplication 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 thelower-level JTS routines.

    Therefore, JTA is a high level transaction interface that your application uses to control transaction. And JTSis a low level transaction interface and EJBs uses behind the scenes (client code doesn't directly interact withJTS. 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 whichcan 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 adaptersthat support access to enterprise information systems that can be plugged into any J2EE product. Each typeof 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 toauthenticate and authorize a specific user or group of users to run it. It is a standard PluggableAuthentication Module (PAM) framework that extends the Java 2 platform security architecture to supportuser-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 centralizedsecurity control or logging, and change little over time. Model 1 applications can often be refactored to Model2 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, andmessage resources into a unified framework. It is a cooperative, synergistic platform, suitable fordevelopment 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 delegatesrequests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapterbetween the request and the Model. The Model represents, or encapsulates, an application's business logic orstate. Control is usually then forwarded back through the Controller to the appropriate View. The forwardingcan be determined by consulting a set of mappings, usually loaded from a database or configuration file. Thisprovides a loose coupling between the View and Model, which can make an application significantly easier tocreate and maintain.

  • 7/29/2019 J2EE Interview Faq Imp

    17/29

    Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the screen, a JSPpage 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?

    Yes29) 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 Message-Driven 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)

    EJB Interview Questions

    1. What is EJB?

    EJB stands for Enterprise JavaBeans and is widely-adopted server side component architecture for J2EE. Itenables rapid development of ission-critical application that are versatile, reusable and portable acrossmiddleware 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. Itincreases 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 server-side businesslogic 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.

  • 7/29/2019 J2EE Interview Faq Imp

    18/29

    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 EJBcomponent 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) messagelistener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clientsto 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 implementationof 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 andStateful. Stateless bean is the simplest bean. It doesn't maintain any conversational state with clientsbetween 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. ReturnEJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request toBean (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 areserializable.This has to be considering as passed-by-value that means that its read-only in the EJB. Ifanything is altered from inside the EJB, it wont 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 itis possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice interms of object-oriented design. This is because you are creating an unnecessary coupling between back-endobjects (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 aclass that acts as a value object (or structure) that holds all the data you need to pass back and forth

  • 7/29/2019 J2EE Interview Faq Imp

    19/29

    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 separateinstance 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 theperformance 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 cant be a primitive type. Use the primitive wrapper classes, instead. For example, you canuse 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 forStateful Session Beans, the container cannot passivate an instance that is inside a transaction. So usingtransactions 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 optimizedlogic. Some EJB containers, such as BEA Weblogic, provide the ability to tune the container to minimizepassivation calls. Taken from the Weblogic 6.0 DTD -The passivation-strategy can be either default ortransaction. 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 fora 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. Thereare 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 theDB/Persistence storage and assigns to the object variables in bean for user to manipulate or use them. Forthis 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 makeconnection, retrieve values, assign them to the objects in the ejbLoad() which will be called by the containerwhen it instantiates a bean object. Similarly in the ejbStore() the container saves the object values back thepersistence storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container.Apart from this, when you use Entity beans you dont 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.0specification. The EJB QL query language defines finder methods for entity beans with container managedpersistence and is portable across containers and persistence managers. EJB QL is used for queries of twotypes of finder methods: Finder methods that are defined in the home interface of an entity bean and whichreturn entity objects. Select methods, which are not exposed to the client, but which are used by the BeanProvider to select persistent values that are maintained by the Persistence Manager or to select entity objectsthat are related to the entity bean on which the query is defined.

  • 7/29/2019 J2EE Interview Faq Imp

    20/29

    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. Thisdesign allowed for maximum flexibility in developing applications without consideration for the deploymentscenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers areusing EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With thisfeedback 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 samecontainer. This does not involve the overhead involved with RMI like marshalling etc. This facility will thusimprove the performance of applications in which co-location is planned. Local interfaces also provide thefoundation for container-managed relationships among entity beans with container-managed 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 remoteinterfaces. For example, remote interfaces pass parameters using call-by-value semantics, while localinterfaces use call-by-reference. This means that in order to use local interfaces safely, applicationdevelopers need to carefully consider potential deployment scenarios up front, then decide which interfacescan be local and which remote, and finally, develop the application code with these choices in mind. WhileEJB 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 factoredinto 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. Thenumber of beans in cache is managed by the container. In case of Stateful session bean, the bean may bekept in cache till either the session times out, in which case the bean is removed or when there is arequirement 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 behaviorof 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 severalsignificant ways: Message-driven beans process multiple JMS messages asynchronously, rather thanprocessing 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-drivenbeans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interactswith a message-driven bean by creating bean instances and passing JMS messages to those instances asnecessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot becreated 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 bean-containercontract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass calledSessionContext. These EJBContext objects provide the bean class with information about its container, theclient using the bean and the bean itself. They also provide other functions. See the API docs and the specfor more details.

  • 7/29/2019 J2EE Interview Faq Imp

    21/29

    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 obtaininformation about the declared members that are not otherwise accessible to the enterprise bean because ofthe 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 typicallyused to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achievedby 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 theSession 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 deployermust 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 transientuser-specific data that will die when the user disconnects (ends his session). Generally, the session beansimplement 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 adatabase 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 andthe 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. TheejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to aSELECT statement in SQL. By making this method mandatory, the client programmer can be assured that ifthey have the primary key of the Entity Bean, then they can retrieve the bean without having to create anew bean each time - which would mean creating duplications of persistent data and break the integrity ofEJB.

    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 worksfor entity beans. On the other hand, the Remote interface version works on an entity bean that you havealready instantiated. In addition, the remote version also works on session beans (stateless and Stateful) toinform 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.

  • 7/29/2019 J2EE Interview Faq Imp

    22/29

    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) forconcurrent client connections and manages system resources such as threads, processes, memory, databaseconnections, network connections, etc. An EJB container runs inside (or within) an EJB server, and providesdeployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB beanfrom the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean andits container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any

    EJB server which supports the Connector architecture. See Suns J2EE Connectors for more in-depthinformation 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: containermanaged persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which yourbeans run under takes care of the persistence of the fields you have declared to be persisted with thedatabase - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, assoon as the method you have executed is finished, the new data is persisted to the database by thecontainer. For BMP, the EJB bean developer is responsible for defining the persistence routines in the properplaces in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed bythe 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 onthe Home interface, then the container is responsible for calling the ejbCreate() method in the bean, whichshould 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 bean-containercontract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass calledSessionContext. These EJBContext objects provide the bean class with information about its container, theclient using the bean and the bean itself. They also provide other functions. See the API docs and the specfor more details.

    35. Is method overloading allowed in EJB?

    Yes you can overload methods should synchronization primitives be used on bean methods? - No. The EJBspecification specifically states that the enterprise bean is not allowed to use thread primitives. The containeris 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 Statefulsession beans). Thus passivation simply involves moving the bean from the ready to the pooled bin. So whathappens to the contents of an instance variable is controlled by the programmer. Remember that when anentity bean is passivated the instance gets logically disassociated from its remote object. Be careful here, asthe functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans iscompletely different. For entity beans the ejbPassivate method notifies the entity bean that it is beingdisassociated 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 EJBspecification. The original bean types include session beans, which contain business logic and maintain astate associated with client sessions, and entity beans, which map objects to persistent data. Message driven

  • 7/29/2019 J2EE Interview Faq Imp

    23/29

    beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A messagebean 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, messagebeans maintain no client-specific state, allowing the container to optimally manage a pool of message-beaninstances. Clients send JMS messages to message beans in exactly the same manner as they would sendmessages 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 thejavax.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 itif necessary), and calls its onMessage method passing the clients message as the single argument. Themessage beans 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 andEJBObject 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 referenceirrespective of the client request. While referring the EJB Object classes the container creates a separateinstance 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 theperformance 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 methodsdo not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they donot have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client isusing 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 tothe Pooled state to save memory. Then, to save additional memory, the container may begin moving entitybeans from the Pooled State to the Does Not Exist State, because even though the beans cache has beencleared, the bean still takes up some memory just being in the Pooled State.

    42. What is the need of Remote and Home interface. Why cant 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 youto remotely access to all its methods and members. As you can see there are two distinct elements (thecontainer 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 caseswhere create() method is not provided, the only way to access the bean is by knowing its primary key, andby acquiring a handle to it by using its corresponding finder method. In those cases, you can create aninstance of a bean based on the data present in the table. All one needs to know is the primary key of that

  • 7/29/2019 J2EE Interview Faq Imp

    24/29

    table. I.e. a set a columns that uniquely identify a single row in that table. Once this is known, one can usethe 'getPrimaryKey()' to get a remote reference to that bean, which can further be used to invoke businessmethods.

    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 likethe RMI Naming.bind() method.

    javax.naming.InitialContext is a Context and provides implementation for methods available in the Contextinterface.

    Where as SessionContext is an EJBContext objects that is provided by the EJB container to a SessionBean inorder 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 thepurpose of the EntityBean accessing the container details. In general, the EJBContext (SessionContext andEntityContext), 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 atransaction in progress when the method is called." When a message arrives, it is passed to the MessageDriven Bean through the onMessage() method, that is where the business logic goes. Since there is noguarantee when the method is called and when the message will be processed, is the container that isresponsible 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 StatefulSession 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 andejbPassivate 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 meansis that if you cluster your application server (spread it across several machines) each part of the cluster willrun 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 ofthe static variable to be increased to 101. On the subsequent call to the same EJB from the same client, acluster 2 may be invoked to handle the request. A value of the static variable in cluster 2 is still 100 becauseit was not increased yet and therefore your application ceases to be consistent. Therefore, static non-finalvariables 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. YourApplicationException 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 notmention anything about Application exceptions being sub-classes of EJBException. You can tell container torollback the transaction, by using setRollBackOnly on SessionContext/EJBContext object as per type of beanyou are using.

    48. Does Stateful Session bean support instance pooling?

    Stateful Session Bean conceptually doesn't have instance pooling.

  • 7/29/2019 J2EE Interview Faq Imp

    25/29

    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 tomap 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 becausethere is no ejbCreate() method.

    However, the J2EE spec is explicit:

    6. the home interface of a Stateless Session Bean must have a single create() method with noarguments, while the session bean class must contain exactly one ejbCreate() method, also withoutarguments.

    7. 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 PrimaryKeys are generated automatically by the underlying database, the bean provider must declare thefindByPrimaryKey method to return java.lang.Object and specify the Primary Key Class as java.lang.Object inthe 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 anessential 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 ofservers.

    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 HttpSessionas 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, itwon'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 thesame 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().

  • 7/29/2019 J2EE Interview Faq Imp

    26/29

    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 atthe same time (they are mutually exclusive).

    There is a common approach that is normally used and considered a good one. You should start developingCMP beans, unless you require some kind of special bean, like multi-tables, that cannot be completelyrealized 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 aCMP 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 theJava 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 toCORBA and Microsoft Transaction Server, but based on the Java platform. EJB specifies how developersshould build components that can be accessed remotely and how EJB vendors should support thosecomponents. 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 theEnterprise JavaBeans server-side component model. A server-side component is business object that can beaccessed remotely. Many server-side component models exist: CORBA specifies CORBA objects; MicrosoftTransaction 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 beanused, 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 areboth 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 theJDK. Components built on the JavaBeans specification are intraprocess components that live in one address

  • 7/29/2019 J2EE Interview Faq Imp

    27/29

    space and are typically used for Graphical User Interface (GUI) as visual widgets like buttons, tables, HTMLviewers, etc.

    Enterprise JavaBeans

    The EJB specification is based on the javax.ejb package, which is a standard extension package. Componentsbuilt on the EJB specification are intraprocess components that live in multiple address spaces asdistributed 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 whenthey are passivated. This is not true of all vendors but this view serves as good model for understanding theconcepts of passivation in session beans.

    When a stateful bean experiences a lull in use -- between client invocations and transactions -- the containermay choose to passivate the stateful bean instance. To conserve resources the bean instance is evicted frommemory (dereferenced and garbage collected). When the EJB object receives a new client request, a newstateful 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 evictedfrom memory. To accomplish this, the container will write the conversational state of the bean instance to asecondary storage (usually disk). Only the non-transient serializable instance fields are preserved. When thebean is activated the new instance is populated with the preserved state. References to live resources likethe EJBContext, DataSource, JNDI ENC, and other beans must also be maintained somehow -- usually inmemory -- by the container.

    The javax.ejb.SessionBean interface provides two callback methods that notify the bean instance it is aboutto passivated or was just activated. The ejbPassivate( ) method notifies the bean instance that it is abouthave its conversational state written to disk and be evicted from memory. Within this method the beandeveloper 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 conversationalstate from disk. The bean developer can use the ejbActivate( ) method to perform operations just prior toservicing client request, like opening resources.

    63. Do JTS implementations support nested transactions?

    A JTS transaction manager must support flat transactions; support of nested transactions is optional. If aclient begins a transaction, and within that transaction begins another transaction, the latter operation willthrow 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.1specification 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 sessionbeans; 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 ornot it would be better to encapsulate these operations in yet another session bean, and allow the sessionbean to handle the transactions via the EJB container. In general, lightweight clients are easier to maintainthan heavyweight clients. Also, EJB environments are ideally suited for transaction management.

  • 7/29/2019 J2EE Interview Faq Imp

    28/29

    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 isresponsible for transaction processing. The session bean has only limited control of transaction handling viathe 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 methodinvocation must be independent. (The bean can be "swapped out" between method invocations.) Thus, astateless 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 (viathe EJB container and server) to a datastore; hence, the EJB container is in the best position to managetransaction 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 tofree 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 implementationscontainer-managed entity beans can only by mapped to one table, while other implemenations offer Multipletable 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 persisteddepending on the success of the transaction. If the transaction manager determines that the transaction wassuccessful or there were no problems during any of the steps invoved in it, the data is committed, orotherwise 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 thetransaction since the client never interacts directly with the bean instance but with the server'simplementation of the EJBObject.

    74. How do enterprise beans access native libraries?

    In short, they don't.

  • 7/29/2019 J2EE Interview Faq Imp

    29/29

    The EJB 1.1 Specification, section 18.1.2 (Programming Restrictions) lists some things that enterprise beanscannot 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