+ All Categories
Home > Documents > Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0...

Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0...

Date post: 30-Sep-2020
Category:
Upload: others
View: 4 times
Download: 0 times
Share this document with a friend
28
Page 1 of 28 Table of Contents GENERAL .................................................................................................................................................................................2 J2EE PATTERNS/DESIGN PATTERNS...............................................................................................................................2 UML/DESIGN/ARCHITECTURE .........................................................................................................................................6 EJB .............................................................................................................................................................................................9 STRUTS ...................................................................................................................................................................................13 WEB/JSP/SERVLET ..............................................................................................................................................................16 JMS...........................................................................................................................................................................................19 DATABASES...........................................................................................................................................................................20 XML/XSLT ..............................................................................................................................................................................20 WEB SERVICES ....................................................................................................................................................................21 JAVA ........................................................................................................................................................................................24 OTHER J2EE TECHNOLOGIES/FRAMEWORKS..........................................................................................................26 QUESTIONS TO BE INCLUDED ........................................................................................................................................27
Transcript
Page 1: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 1 of 28

Table of Contents

GENERAL.................................................................................................................................................................................2 J2EE PATTERNS/DESIGN PATTERNS...............................................................................................................................2 UML/DESIGN/ARCHITECTURE .........................................................................................................................................6 EJB .............................................................................................................................................................................................9 STRUTS ...................................................................................................................................................................................13 WEB/JSP/SERVLET..............................................................................................................................................................16 JMS...........................................................................................................................................................................................19 DATABASES...........................................................................................................................................................................20 XML/XSLT..............................................................................................................................................................................20 WEB SERVICES ....................................................................................................................................................................21 JAVA........................................................................................................................................................................................24 OTHER J2EE TECHNOLOGIES/FRAMEWORKS..........................................................................................................26 QUESTIONS TO BE INCLUDED ........................................................................................................................................27

Page 2: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 2 of 28

General 1. Describe about your latest project and explain the various design patterns that have been used in the

current project. 2. What were the challenges faced by you in your latest project? 3. What are the performance issues that you faced and how did you resolve it? 4. What is your strongest skill set? What do you do well? 5. Suppose that you have a live production system running and something fails. Now you want to fix this

immediately without affecting the current users in the system how do you do that? - Hot Deployment. 6. Explain how the user security, authentication and authorization are handled in your current project? 7. What are the no of users working concurrently on you current application? How do you ensure the

concurrency of their transactions? 8. What is the difference between the Weblogic and the Websphere application server from the

deployers’ perspective? 9. How do you handle the Exceptions at various tiers of an application (UI, Business and database) and

how do show them to the users? 10. How was logging handled in your application? 11. Explain how you would debug a problem, if it arises in the Production system? 12. What are your Strengths in Java/J2EE? On a scale of 1 to 10, can you rate yourself in J2EE? 13. What’s new in J2EE 1.4? - The Java 2 Platform, Enterprise Edition version 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.

a. JSP 2.0

J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages? – The Model View Controller Architecture is a

widely used architectural approach for interactive applications. It divides functionality among objects involved in maintaining and presenting data to minimize the degree of coupling between the objects. The MVC Architecture divides your application in to three layers – model, view and controller - and decouples their respective responsibilities. Each layer handles specific tasks and has specific responsibilities to the other areas.

a. A model represents business data and business logic or operations that govern access and modification of the business data. Responsible for the business domain state knowledge

b. A view renders the content of a model. It accesses data from the model and specifies how that data should be presented. Responsible for a presentation view of the business domain.

c. A controller defines application behavior. It dispatches user requests and selects views for presentation. It interprets user inputs and maps them into actions to be performed by the model. Responsible for controlling the flow and state of the user input

15. What is the difference between Model 1 and Model 2 Architectures? The early JSP specifications presented two approaches for building web applications using JSP technology. These two approaches were the JSP Model 1 and Model 2 architectures. Although these terms are no longer used in the JSP specification, they still are widely used throughout the web tier development community. The two JSP architectures differ in several key areas. The major difference is in how and by which component the processing of a request is handled. With the Model 1 architecture, the JSP page handles all of the processing of the request and is responsible for displaying the output to the client. This is illustrated in the following figure

Page 3: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 3 of 28

JSP Model 1 architecture

Notice that there is no servlet involved in the process. The client request is sent directly to a JSP page, which may communicate with JavaBeans or other services, but ultimately the JSP page selects the next page for the client. The next view is determined based on either the JSP selected or parameters within the client's request.

In contrast, in the Model 2 architecture, the client request is first intercepted by a servlet, commonly referred to as a controller servlet. This servlet handles the initial processing of the request and determines which JSP page to display next. This approach is illustrated in the following figure

JSP Model 2 architecture

As shown in the figure, a client never sends a request directly to a JSP page in the Model 2 architecture. This allows the servlet to perform front-end processing, including authentication and authorization, centralized logging, and help with internationalization. Once request processing has completed, the servlet directs the request to the appropriate JSP page. How the next page is determined varies widely across different applications. For example, in simpler applications, the next JSP page to display may be hardcoded in the servlet based on the request, parameters, and current application state. In more sophisticated web applications, a workflow/rules engine might possibly be used. As you can see, the main difference between the two approaches is that the Model 2 architecture introduces a controller servlet that provides a single point of entry and encourages more reuse and extensibility than the Model 1 approach. With the Model 2 architecture, there is a clear separation of the business logic, presentation output, and request processing. This separation is often referred to as a Model-View-Controller (MVC) pattern 16. Can you name some of the presentation tier patterns? – Intercepting Filter, Front Controller, Context

Object, Application Controller, View Helper, Composite View, Service to Worker, Dispatcher View. 17. Can you name some of the business tier patterns? – Business Delegate, Service Locator, Session Façade,

Application Service, Business Object, Composite Entity, Transfer Object, Transfer Object Assembler, Value List Handler.

18. Can you name some of the Integration Tier Patterns? – Data Access Object, Service Activator, Domain Store, Web Service Broker.

19. What is Front Controller Pattern? What are its advantages? – A front controller helps you separate a view from its (access) control logic. A Front Controller as the initial point of contact for handling all related requests in an application. The Front Controller centralizes (access) control logic that might otherwise be duplicated, and manages the key request handling activities. The Front Controller provides a centralized entry point for handling requests. By centralizing control logic, the Front Controller also helps reduce the amount of programming logic embedded directly in the views. For a JSP view, for instance, this reduces the temptation to use large amounts of Java code, called scriptlet code, embedded

Page 4: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 4 of 28

within the JSP. A front controller typically uses an Application Controller, which is responsible for action and view management. Action management refers to locating and routing to the specific actions that will service a request. View management refers to finding and dispatching to the appropriate view. While this behavior can be folded into the Front Controller, partitioning it into separate classes as part of an Application Controller improves modularity, maintainability, and reusability. The advantages of using Front Controller are:

a. You can avoid duplication of control logic. b. You can apply common logic to multiple requests like security, logging etc. c. You can separate system processing logic from view. d. Centralized access point into your system

20. What is a View Helper Pattern? What are its advantages? – A view helper helps you separate a view from its processing logic. A View delegates its processing responsibilities to its helper classes, implemented as POJOs, custom tags, or tag files. Helpers serve as adapters between the view and the model, and perform processing related to formatting logic, such as generating an HTML table. This pattern applies primarily to template-based views like JSP. Static template text and markup tags define the overall template view, and hooks to programming logic are encapsulated in helpers and embedded in the template. Advantages:

a. Improves application partitioning, reuse, and maintainability - Separating HTML from processing logic, such as control logic, business logic, data access logic, and formatting logic, results in improved application partitioning. Each of these logically unrelated parts of the application can be encapsulated in highly cohesive, reusable components. Control logic can be moved into a Front Controller and command helpers, and business logic remains in Business Object. Data Access Objects get the data access logic, and formatting logic is moved into tag helpers. As a result, helpers exist in several forms, including JavaBeans, custom tags, or tag files (JSP 2.0+) and encapsulate processing logic that might otherwise be embedded within the view, cluttering it with scriptlet code.

21. What is an Application Controller Pattern? What are its advantages? – An Application Controller helps you to centralize and modularize action and view management. Action Management is the process of resolving an incoming request to an action that services the request. View management is the process of locating and dispatching the appropriate view. While a Front Controller acts as a centralized access point and controller for incoming requests, the mechanism for identifying and invoking commands and for identifying and dispatching to views can be broken out into its own set of components. Advantages:

a. Improves modularity - Separating common action and view management code, into its own set of classes makes the application more modular. This modularity might also ease testing, since aspects of the Application Controller functionality will not be tied to a web container.

b. Improves reusability - You can reuse the common, modular components. c. Improves extensibility - Functionality can be added to the request handling mechanism in a

predictable way, and independent of protocol-specific or network access code. Declarative flow control reduces coupling between code and navigation/flow control rules, allowing these rules to be modified without recompiling or modifying code.

22. What is Business Delegate Pattern? What are its advantages? Business Delegate encapsulates access to business service. The Business delegate hides the implementation details of the business service, such as lookup and access mechanisms. The advantages are:

a. A Business Delegate acts as a client-side business abstraction: it abstracts and hides the implementation details of the business services. For example, by using the Business Delegate, the client becomes transparent to naming and lookup services. (Hides Remoteness, exposes a simpler, uniform interface to the business tier)

b. Using a Business Delegate reduces the coupling between the client and the system's business services. Depending on the implementation strategy, the Business Delegate might shield clients from possible volatility in the implementation of the business service API. Potentially,

Page 5: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 5 of 28

this reduces the number of changes that must be made to the client code when the business service API or its underlying implementation changes. (Reduces Coupling)

c. A Business Delegate also handles the exceptions from the business services, such as java.rmi.Remote exceptions, JMS exceptions, and so on. The Business Delegate might intercept such service-level exceptions and generate application-level exceptions instead. Application-level exceptions are easier to handle by the clients, and are more likely to be user friendly. (Translates business service exceptions)

d. A Business Delegate can also transparently perform any retry or recovery operations necessary in the event of a service failure, without exposing the client to the problem, unless it is determined that the problem is not resolvable. These gains present a compelling reason to use the pattern.

e. The Business Delegate can cache results and references to remote business services. Caching can significantly improve performance, because it limits unnecessary and potentially costly round trips over the network. (Improves performance)

23. What is a Service Locator Pattern? What are its advantages? – Service Locator helps you transparently locate business components and services in a uniform manner. A Service Locator hides the implementation details of the lookup mechanism and encapsulates related dependencies. Advantages:

a. Abstracts complexity - The Service Locator encapsulates the complexity of the service lookup and creation process (described in the problem) and keeps it hidden from the client.

b. Provides uniform service access to clients - The Service Locator provides a useful and precise interface that all clients can use. The interface ensures that all types of clients in the application uniformly access business objects, in terms of lookup and creation. This uniformity reduces development and maintenance overhead.

c. Facilitates adding EJB business components - Because clients of enterprise beans are not aware of the EJB Home objects, you can add new EJB Home objects for enterprise beans developed and deployed at a later time without impacting the clients. JMS clients are not directly aware of the JMS connection factories, so you can add new connection factories without impacting the clients.

d. Improves network performance - The clients are not involved in lookup and object creation. Because the Service Locator performs this work, it can aggregate the network calls required to look up and create business objects.

e. Improves client performance by caching - The Service Locator can cache the initial context objects and references to the factory objects (EJBHome, JMS connection factories). Also, when accessing web services, the Service Locator can cache WSDL definitions and endpoints.

24. What is Session Façade pattern? What are its advantages? - Session Façade to encapsulate business-tier components and expose a coarse-grained service to remote clients. Clients access a Session Façade instead of accessing business components directly. Advantages:

a. Introduces a layer that provides services to remote clients - Session Façades introduce a layer between clients and the business tier to provide coarse-grained remote services. For some applications, this might be unnecessary overhead, especially if the business tier is implemented without using EJB components. However, Session Façades have almost become a necessity in J2EE applications because they provide remote services and leverage the benefits of an EJB container, such as transactions, security, and lifecycle management.

b. Exposes a uniform coarse-grained interface - A Session Façade encapsulates the complexity of the underlying business component interactions and presents the client with a simpler coarse-grained service-layer interface to the system that is easy to understand and use. In addition, by providing a Business Delegate for each Session Façade, you can make it easier for client-side developers to leverage the power of Session Façades.

c. Reduces coupling between the tiers - Using a Session Façade decouples the business components from the clients, and reduces tight coupling and dependency between the presentation and business tiers. You can additionally implement Application Services to

Page 6: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 6 of 28

encapsulate the complex business logic that acts on several Business Objects. Instead of implementing the business logic, the Session Façades can delegate the business logic to Application Services to implement.

d. Promotes layering, increases flexibility and maintainability - When using Session Façades with Application Services, you increase the flexibility of the system by layering and centralizing interactions. This provides a greater ability to cope with changes due to reduced coupling. Although changes to the business logic might require changes in the Application Services or even the Session Façades, the layering makes such changes more manageable.

e. Reduces complexity - Using Application Services, you reduce the complexity of Session Façades. Using Business Delegate for accessing Session Façades reduces the complexity of client code. This helps make the system more maintainable and flexible.

f. Improves performance, reduces fine-grained remote methods - The Session Façade can also improve performance because it reduces the number of remote network invocations by aggregating various fine-grained interactions into a coarse-grained method. Furthermore, the Session Façades are typically located in the same process space as the participating business components, enabling faster communication between the two.

25. What is a Transfer Object Pattern? What are its advantages? – A Transfer Object is used to carry multiple data elements across a tier. A Transfer Object is designed to optimize data transfer across tiers. Instead of sending or receiving individual data elements, a Transfer Object contains all the data elements in a single structure required by the request or response. The advantages are:

a. Reduces network traffic b. Simplifies remote object and remote interface. c. Transfer more data in fewer remote calls.

26. What is a Data Access Object Pattern? What are its advantages? – Data Access Object abstracts and encapsulates all access to the persistent store. The Data Access Object manages the connection with the data store to obtain and store data. The Data Access Object (also known simply as DAO) implements the access mechanism required to work with the data source. Regardless of what type of data source is used, the DAO always provides a uniform API to its clients. The business component that needs data access uses the simpler interface exposed by the DAO for its clients. The DAO completely hides the data source implementation details from its clients. Because the interface exposed by the DAO to clients does not change when the underlying data source implementation changes, this allows you to change a DAO implementation without changing the DAO client's implementation. Essentially, the DAO acts as an adapter between the component and the data source. The advantages are:

a. Enables easier migration - A layer of DAOs makes it easier for an application to migrate to a different database implementation. The clients have no knowledge of the underlying data store implementation. Thus, the migration involves changes only to the DAO layer.

b. Reduces code complexity in clients - Since the DAOs encapsulate all the code necessary to interact with the persistent storage, the clients can use the simpler API exposed by the data access layer. This reduces the complexity of the data access client code and improves the maintainability and development productivity.

c. Organizes all data access code in to a separate layer. 27. What is a Singleton Pattern? – A singleton pattern can have multiple instances (but a configurable

number of instances.)

UML/Design/Architecture 28. What kinds of diagrams have you developed in UML? – Class Diagrams, Sequence Diagrams, Activity

Diagrams. 29. What is the difference between Composition and Aggregation? Both are Associations and Part-Whole

relationships. Composition is stronger form of Association where in the part cannot exist with out the whole.

Page 7: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 7 of 28

30. How would you represent Composition and Aggregation in UML? – Composition is represented by a filled diamond symbol and Aggregation is represented by a hollow diamond.

31. What is Polymorphism, How do you achieve polymorphism in Java? - Polymorphism refers to a programming language’s ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results.

32. How is Polymorphism achieved in Java (Method overriding or overloading or both)? – Polymorphism is achieved through Inheritance (Method overriding) and not Method overloading.

33. What is Rational Unified Process? –

34. What does an idempotent method mean? - Methods can also have the property of "idempotence" in that

(aside from error or expiration issues) the side-effects of multiple identical requests is the same as for a single request.

35. What are the various ways of tracking a Session? 36. What do you implement in Struts’ Action Class’s execute method – Presentation logic or Business logic,

and why? – The execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) method itself should not contain the core business logic irrespective of whether or not you use EJBs or any fancy middle tier. First and foremost reason for this is that business logic classes should not have any dependencies on the Servlet package. By putting the business logic in the Action class, you are letting the javax.servlet.* classes proliferate into your business logic. This limits the reuse of the business logic, say for a pure Java client. The second reason is that if you ever decide to replace the Struts framework with some other presentation framework, you don’t have to go through the pain of modifying the business logic. The execute () method should preferably contain only the presentation logic and be starting point in the web tier to invoke the business logic. If Struts were replaced with an alternative framework, chances are the Action class would be replaced with something else. Therefore, it really isn't part of the model domain, but rather is tightly

Page 8: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 8 of 28

coupled to the Struts controller. What qualifies as Presentation logic: Analyzing request parameters and creating data transfer objects (for server side processing), invoking business logic (preferably through business delegates), creating view-models –the model JavaBeans for the JSPs, selecting the next view and converting exceptions in to appropriate action errors.

37. What are the advantages of having multiple application modules (multiple configuration files) in Struts? – Struts 1.1 supports multiple sub applications known as application modules. The advantages are:

a. You can now split your monolithic struts application into logical modules thus making maintenance easier.

b. It will cause less contention during development time as developers working on different modules get to work on their own struts configuration files. Each Struts Configuration file and hence each application module can choose its own RequestProcessor, MessageResources and PlugIn. You can now choose to implement one or more modules with Tiles.

38. How would you handle duplicate form submissions (using Struts feature)? – Duplicate form submissions can occur in many ways:

a. Using Refresh button b. Using the browser back button to traverse back and resubmit form c. Using Browser history feature and re-submit form d. Malicious submissions to adversely impact the server or personal gains e. Clicking more than once on a transaction that takes longer than usual

Duplicate form submissions are acceptable in some cases. Such scenarios are called idempotent transitions. When multiple submissions of data are not critical enough to impact the behavior of the application, duplicate form submissions do not pose a threat. Struts provides SynchronizerToken. The Action class has a method called saveToken() whose logic is as follows: HttpSession session = request.getSession (); String token = generateToken (request); if (token != null) {

session.setAttribute (Globals.TRANSACTION_TOKEN_KEY, token); } The method generates a random token using session id, current time and a MessageDigest

and store in the session with the key Globals.TRANSACTION_TOKEN_KEY. The value of this field is org.apache.struts.taglib.html.TOKEN.

The Action class that renders the form invokes the saveToken () method to create a session attribute with the above name. In the JSP, the token is used as a hidden filed in the form as follows:

<html:hidden name=”org.apache.struts.taglib.html.TOKEN” /> The <html:hidden> tag looks for a bean named org.apache.struts.taglib.html.TOKEN in different

scopes and renders its value as the value attribute of the <input> element. When the client submits the form, the hidden field is also submitted (It is not set as a property on the

ActionForm, since it does not belong there). In the Action that handles the form submission (which most likely is different from the Action that rendered the form), compare the token in the form submission with the token in the session by using the isTokenValid () method. The method compares the two tokens and returns a true if both are same. Be sure to p ass reset=”true” in the isTokenValid () method to clear the token from session after comparison. If the two tokens are equal, the form was submitted for the first time. However, it the two tokens do not match or if there is no token in the session, then it is a duplicate submission and handle it in the manner acceptable to your uses.

39. Is SOAP stateful or Stateless Protocol? – Stateless. 40. Are SOAP messages delivered using HTTP POST or HTTP GET? – HTTP requests are typified by the

messages that your browser sends to a Web server to request a Web page or submit a form. A request for a Web page is usually made in an HTTP GET message, while submission of a form is done with an HTTP POST message. While HTTP GET request is perfectly suited for request Web pages, it doesn’t have a payload area and therefore cannot be used to carry SOAP messages.

Page 9: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 9 of 28

EJB 41. What is EJB? – Enterprise Java Beans is a Standard server-side component model for distributed

business applications. 42. What are the different types of EJBs? – Session, Entity and MDB.

a. Session Beans are extensions of the client application that manage processes or tasks. b. Entity beans model business concepts that can be expressed as nouns. Ex: A customer. c. Message driven beans are integration points for other applications interested in working with

EJB application. Java applications or legacy systems that need to access EJB applications can send messages to message driven beans via JMS.

43. EJB 1.1 comes with (J2EE 1.2) – Introduced Entity Beans. 44. What are the new features of EJB 2.0(Comes with J2EE 1.3)? – 45. What are the new features of EJB 2.1(Comes with J2EE 1.4)? – 46. What are the advantages of using EJBs? – 47. EJBs may be accessed by a variety of clients. EJBs are distributed Objects that can be accessed

remotely. a. EJBs are supported by a rich set of services (Implicit and Explicit) by the application server.

i. Implicit services are Transactions, Security, LifeCycle, Concurrency, Persistence, Remote Access.

ii. Explicit services are JDBC, JTS, JNDI, JCA, RMI, JMX, JAAS. b. Makes it easier to build Business Components. c. EJBs provide Reliability, Robustness and Scalability.

48. What are the three classes/interfaces that you need to implement for Session Beans? a. Home Interface - extends from javax.ejb.EJBHome (for Remote) and extends from

javax.ejb.EJBLocalHome (for Local). b. Remote Interface - extends from javax.ejb.EJBOject (for Remote) and extends from

javax.ejb.EJBLocalObject (for Local). c. Bean Class – extends from javax.ejb.SessionBean.

49. How would you make an interface Remote? a. It must extend java.rmi.Remote b. Each method must declare a java.rmi.RemoteException (Checked Exception). c. Arguments and return types must be shippable (Serializable, Primitive or Remote)

50. Can Stateless Session Beans have multiple create () methods in Home Interface? – No. For Stateless Session Beans, there can be only one create () and it must NOT have arguments.

51. Can Stateful Session Beans have multiple create () methods in Home Interface? – Yes. Stateful session beans can have multiple, overloaded create () methods and do not need to have a no-arg create ().

52. What is the difference between Stateless and Stateful Session Beans? Conversational State is maintained in the case of Stateful Session Beans.

53. What is SessionContext, EntityContext, MessageDrivenContext? All three are subtypes of javax.ejb.EJBContext. These types provide the bean with information about its environment: its container, the client using the enterprise bean and the bean itself. The bean can use this information while processing requests from clients and callback methods from the container. Some methods of EJBContext are: getCallerPrincipal(), getUserTransaction(), getRollbackOnly() setRollbackOnly(), getCallerIdentity(), isCallerInRole(), getEnvironment().

54. What is a Remote Interface? It defines the bean’s business methods which can be accessed from applications outside the EJB container: the business methods a bean presents to the outside world. It extends javax.ejb.EJBOject, which in turn extends java.rmi.Remote.

55. What is a Remote Home Interface? It defines the bean’s life-cycle methods which can be accessed from applications outside the EJB container: the life-cycle methods for creating new beans, removing beans,

Page 10: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 10 of 28

and finding beans. The home interface extends javax.ejb.EJBHome, which in turn extends java.rmi.Remote.

56. What is a Local Interface? It defines business methods that can be used by other beans in the same EJB container: the business methods a bean presents to other beans running in the same JVM. It extends javax.ejb.EJBLocalObject.

57. What is a Local Home Interface? It defines life-cycle methods that can be used by other beans in the same EJB container.

58. What is an Endpoint Interface? – A new feature in EJB 2.1 defines business methods that can be accessed from applications outside the EJB container via SOAP (Turns the Session Bean to a Webservice). The endpoint interface is based on JAX-RPC (Java API for XML-RPC) and is designed to adhere to the SOAP and WSDL standards. IT extends java.rmi.Remote. It can be used only by stateless session beans. There is no home interface associated with the endpoint interface.

59. What is Message Interface? Message driven bean implement the message interface, which defines the methods by which messaging systems, such as Java Message Service, can deliver messages to the bean.

60. What is a Bean Class? The session and entity bean classes implement the bean’s business and life-cycle methods. Note that the bean class usually does not implement the remote or local component interfaces, but it may implement the endpoint interface. However, the bean class must have methods matching the signatures of the methods defined in the remote, local and endpoint interfaces and must have methods corresponding to some of the methods in both the remote and local home interfaces. It extends javax.ejb.SessionBean, javax.ejb.EntityBean or javax.ejb.MessageDrivenBean.

61. What is an EJBObject? On the server side, and EJB object is an object that implements the remote and/or local interfaces of the enterprise bean. The EJB object is generated by your EJB container and wraps the enterprise bean instance – that is, an instance of the bean class you’ve created. This object works with the container to apply transactions, security and other system-level operations to the bean at runtime.

62. What is an EJBHome? The EJB home is a lot like the EJB object. It’s another class that’s generated automatically when you install an enterprise bean in a container. It implements all the methods defined by the home interfaces and is responsible for helping the container manage the bean’s life cycle. The EJB home is responsible for locating, creating, and removing enterprise beans. These tasks may involve working with the EJB server’s resource managers, instance pooling and persistence mechanisms, the details of which are hidden from the developer.

63. What data types can be passed as parameters or returned from EJBs? The super types of the remote home interface and remote interface, javax.ejb.EJBHome and javax.ejb.EJBObject, both extend java.rmi.Remote. As Remote interface subtypes they are expected to adhere to the Java RMI specification for Remote interfaces. Following are the list of types that can be passed as parameters or returned in Java RMI.

a. Primitives. b. Java Serializable types – Any class that implements or any interface that extends

java.io.Serializable. c. Java RMI remote types – Any class that implements or any interface that extends

java.rmi.Remote. 64. Are parameters to methods defined in EJB Remote Interface passed by value or passed by reference?

a. Serializable objects are passed by value, not by reference. b. Objects that implement java.rmi.Remote are passed as remote references. When a remote

reference is passed as a parameter or returned from a method, the stub is serialized and passed by value, not the object referenced by the stub.

65. Explain the Life Cycle of a Stateless Session Bean – Two States: Does Not Exist, Method-Ready Pool. 66. Explain the Life Cycle of a Stateful Session Bean – Three States: Does Not Exist, Method_Ready,

Passive. 67. Explain the life cycle of Entity Bean – No State, Pooled State and Ready State. 68. Explain the life cycle of Message Driven Bean – Two States: Does Not Exist, Method-Ready Pool. 69. What is the difference between Bean Managed Persistence and Container Managed Persistence?

Page 11: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 11 of 28

70. What is EJB QL? – EJB QL is a declarative query language similar to the SQL used RDBMS, but it is tailored to work with the abstract persistence schema of entity beans. EJB QL makes it possible to define queries that are portable across databases and EJB vendors.

71. What is the difference between Local and Distributed Transactions? a. Local Transaction has only one Resource Manager. In a local transaction, the transaction

manager and resource manager are often indistinguishable. (Note: Transaction Manager is the supreme authority in overseeing the transaction. There can be only one transaction manager per transaction. Resource Managers are participants in a transaction. An example of a resource a manager is a JDBC Database driver.)

b. Distributed Transactions can span multiple resources enabling multiple resources to participate in the same transaction. To support a distributed transaction, the transaction and resource managers communicate using the XA Protocol. This protocol supports a two phase commit process.

72. How does Two-Phase Commit Work? – Transaction Manager should implement XA Protocol for supporting two phase commit. The transaction model is divided in to two distinct phases. The first phase is the preparation phase, and begins when a commit is called on the UserTransaction. Phase one consists of prepare calls to all the resource managers. The resource managers must determine if they can commit their changes without actually committing the changes. If the can successfully commit changes, they return a ready status. If they cannot commit, they indicate a ready to rollback status. The transaction manager prepares each resource manager to commit before entering the commit phase. You are now ready for the second phase. If all resource managers are “ready” at the end of the first phase, the resource managers are called to commit their changes in the second phase. If any of the resource managers need to rollback, all resource managers are instructed to rollback changes in the second phase. This two-phase commit process almost always eliminates atomicity problems in distributed transactions; however, it doesn’t prevent problems from creeping up in some cases. Heuristic decisions are situations that occur when a resource manager decides to commit or rollback changes without authorization from the transaction manager. Heuristic exceptions occur to indicate problem situations in which heuristic decisions were made that impact atomicity of the transaction.

73. How did you manage transactions in EJBs? – CMT or BMT. 74. Session and Message Driven Beans may use either CMT or BMT transaction management. 75. Entity bean transactions are always Container Managed. 76. How do you indicate the container that you are using CMT or BMT? You indicate that using the

<transaction-type> tag in the ejb-jar.xml deployment descriptor. This tag is available inside of <session> and <message-driven> bean tags.

77. What are the various transactional attributes in the case of CMT? – Not Supported, Supports, Required, RequiresNew, Mandatory and Never. Transaction Attribute Suggestions: EJB 2.0 specification suggests that entity beans use only the Required, RequiresNew and Mandatory. In fact, Never, Supports and NotSupported are optional for CMP entity beans.

78. What are transactional attributes supported by MDBs? – NotSupported and Required. 79. On what types of Exceptions will the container rollback the transaction? – System Exceptions cause the

container to roll back the transaction. A SystemException is defined as an exception that extends java.lang.RuntimeException or java.rmi.RemoteException. System exceptions indicate that an unrecoverable error occurred during execution. An Application Exception is defined as an exception that does not extend java.lang.RuntimeException or java.rmi.RemoteException. If an application exception I thrown the container will commit the transaction upon completion of the EJB method. It is the responsibility f the EJB developer to cause a rollback if they desire. This may be done by catching the desired application exception. In the case of BMT, you can call rollback() on the UesrTransaction. In the case of CMT, you can call the setRollbackOnly() on the SessionContext, EntityContext or MessageDrivenContext.

Page 12: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 12 of 28

80. What API/Interface is used for Bean Managed Transaction (BMT)? – Java Transaction API (JTA) is implemented by the javax.transaction package. Javax.transaction.UserTransaction Interface allows you to manage the scope of a transaction explicitly.

81. Can you explain UserTransaction API? Within the EJB model, each client has a specific user transaction instance. Because no transaction nesting is supported, each EJB client will have only one UserTransaction object. This can be obtained via a JNDI lookup. Context ctx = new InitialContext(); UserTransaction tran = (UserTransaction)jndi.lookup(“java:comp/UserTransaction”); The javax.transaction.UserTransacion interface consists of the following interface begin(), commit(), getStatus(), rollback() – this method rolls back the transaction, setRollbackOnly() – marks the transaction for rollback, BMT should not use this method, setTransactionTimeout(secs).

82. What are Transaction Isolation Levels? Transaction isolation level restricts access to resource manager changes in one transaction from another transaction. The EJB spec does not define and API for managing isolation levels. This is left up to the resource managers. It is then possible to have a different isolation level for each resource manager involved in a transaction. Isolation is defined in terms of conditions that describe what can happen when two transactions access the same data. The types are Dirty Reads, Repeatable Reads, Phantom Reads and Serializable (Most Restrictive, which causes all read and update accesses to be exclusive).

83. What are the four essential characteristics of a transaction? Transaction must be atomic, consistent, isolated and durable (ACID).

a. Atomic – Transaction must execute completely or not at all. b. Consistency refers to integrity of the underlying data store. c. Isolated refers to transaction execution without the interference from other processes or

transactions. d. Durability means that data is not lost in system crashes.

84. How do you manage security in EJB, What is the difference between Authentication and Authorization? - Authentication involves identifying who the caller of the EJB is. This involves checking the caller identity against a security realm. The security realm is the mechanism for managing security principals. These principals are individuals or groups that may be identified by userID and password. Many types of security realms are often supported, such as file-based, database, LDAP etc. The calling EJB principal is identified by the user and password on the JNDI lookup. Security roles may be defined to help simplify and define security assignment groupings. A security role is simply a semantic grouping of permissions that are used by a type of user of the application. Method permission can then be assigned to each define security role. These method permissions can apply to home, remote or local interface methods and are configured in the ejb-jar.xml.

85. What is the difference between Container Manage Security (CMS) and Bean Managed Security (BMS)? – Container Managed Security is configured in the deployment descriptors and then applied by the container automatically at runtime. To use CMS, you must: declare security role names, associate bean methods to roles and map roles to principals. Mapping of Security Realm Principals to the security roles in the application server specific deployment descriptor and is vendor specific. Bean Managed Security allows the bean to include security code inside the bean class. This is less portable and requires more work, but provides more granularity. Two methods are provided for checking bean managed security in the EJB. These methods are on the EJBContext instance that is passed into your EJB via setSessionContext(). EJBContext provide both a role-based method and direct principal access. getCallerPrincipal() and isCallerInRole(rolename). Management type for security is not specified. This enables you to use both container and bean managed security in your application. Container security checks are activated by the <method-permissions> tag. You can still access the isCallerInRole () method.

86. Explain the real life scenario where you would use stateless and stateful session beans.

Page 13: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 13 of 28

Struts 87. What’s new in Struts 1.1?

a. Multiple Application Support: You now can define multiple configuration files(multiple struts-config.xml files), allowing developers to work better in parallel.

b. DynaForms: Dynaforms allow you to define ActionForms directly from the struts-config.xml file, without needing to create an explicit new class. As a result, it's easy to create a new form on the fly, without having to spend a lot of time on bean properties.

c. Validator Framework: Hand in hand with Dynaforms, the validator framework allows you to define validation logic for forms using XML descriptors rather than having to write a validate () method on an ActionForm. In addition to the predefined validation (which includes length, type, and credit card checks), you can also define your own validations. You can also define field validations that depend on the values of other fields.

d. Tiles Taglib: Tiles provides a very powerful templating framework that enables you to define common document struts (headers, footers, sidebars) using either JSP documents or XML files. Using Tiles, you can essentially include document content from another file, passing parameters into the document.

e. Declarative exception handling that allows Actions to not have to worry about catching all exceptions

f. Use of Jakarta Commons libraries, such as BeanUtil and Logging. g. Integration with JSTL: As the Java Standard Tag Library becomes more widely adopted,

Struts has kept in step by offering tight integration. For example, the struts-el taglib offers versions of most of the Struts tags that can have embedded Expression Language (EL) values in them.

h. Integration with JSF: Looking ahead to the Java Server Faces framework, which will be released at the end of the year, Struts included a contributed JSF integration tag library, which will enable developers to begin exploring JSF and working out migration and integration strategies for this new Java Community Process Technology.

88. Whats new in Struts 1.2? 89. What is an ActionServlet? – The central component of the Struts Controller is the ActionServlet. It is a

concrete class and extends the javax.servlet.HttpServlet. It performs two important things: a. On startup, its reads the Struts Configuration file and loads it into memory in the init()

method. b. In the doGet() and doPost() methods, it intercepts HTTP request and handles it appropriately.

90. In which file is Struts Configuration Information stored? – struts-config.xml and located in WEB-INF directory of the web application or its sub directories. In fact, the name of the Struts Config file can be configured in web.xml.

a. What is RequestProcessor? – It is one of the Core Controller Components in Struts. Once the ActionServlet intercepts the HTTP request, it doesn’t do much. It delegates the request handling to another class called RequestProcessor by invoking its process () method. Most of the Struts Controller functionality is embedded in the process () method of RequestProcessor.

91. Where is the mapping from URL Path to an Action class defined? – The ActionMapping section in the Struts Config contains the mapping from URL path to an Action class (and also associates a Form bean with the path). <action-mappings> <action path=”/submitDetailForm” type=”mybank.example.CustomerAction” name=”CustomerForm” scope=”request” validate=”true” input=”CustomerDetailForm.jsp”> <forward name=”success” path=”Thankyou.jsp” redirect=”true” /> <forward name=”failure” path=”Failure.jsp”>

Page 14: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 14 of 28

</action> </action-mappings>

92. Which design pattern does Action Class follow? – Command Pattern. 93. What is an ActionForm (a.k.a. Form Bean)? - An ActionForm is a JavaBean that extends

org.apache.struts.action.ActionForm. It contains the data entered from the form (UI) on the client side. It is automatically populated on the server side by the RequestProcessor by iterating through the HTTP request parameters using Java Introspection. (Java Introspection is a special form of Reflection using the JavaBeans properties. Instead of directly using the reflection to set the field values, it uses the setter method to set the field value and getter method to retrieve the field value).

94. Can you explain the signature of the execute method in Action class? - Public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception The execute () method should preferable contain only the presentation logic and be starting point in the web tier to invoke the business logic.

95. What is an ActionForward? – ActionForward is the class that encapsulates the next view information. Struts, encourages you not to hardcode the JSP names for the next view. Rather you should associate a logical name for the next JSP page. This association of the logical name and the physical JSP page is encapsulated in the ActionForward instance returned from the execute method. The ActionForward can be local or global. The <forward> element in the ActionMapping contains three elements: name, path and redirect.

96. Can you name some of the Tag libraries that come with Struts? – There are six of them: HTML, Bean, Logic, Template, Nested and Tiles.

97. Can you name some of the built-in Struts Actions? – ForwardAction, IncludeAction, DispatchAction, LookupDispatchAction and SwitchAction.

98. What is ForwardAction? – ForwardAction allows you to adhere to MVC paradigm when designing JSP navigation. When you want to navigate from one page to another without performing any processing, you can use the built-in ForwardAction. It is declared in the Struts-Config file as follows: <action path=”/gotoPageB” parameter=”/PageB.jsp” type=”org.apache.struts.ForwardAction” />

99. What is DispatchAction? – DispatchAction is a built-in Struts Action. It cannot be used as it is. You will have to extend it to provide your own implementation. When there are multiple related actions in a page, instead of creating separate Action Classes for each action, you can combine all Actions into one. Thereby eliminating the duplication of code across Actions since they are related and making it a more elegant solution. You have to extend DispatchAction and define separate methods for each of the Action. DispatchAction uses the HTTP request parameter defined in the “parameter” attribute of ActionMapping element for invoking the correct method.

100. What is SwitchAction? When the application consists of multiple application modules. SwitchAction let you move from one module to another.

101. What are the various ways of doing Form Validations in Struts? a. By setting the validate attribute to true in ActionMapping and coding your validation logic in

the form bean’s validate () method. b. Externalizing the validation into an XML file that confirms to the Jakarta Commons

Validator syntax and integrate it into Struts. Jakarta Commons Project library is shipped with Struts 1.1. The XML based validations are located in two files – validation-rules.xml and validation.xml. The validation-rules.xml file contains the global set of rules that are ready to use and shipped with Struts. The second file – validation.xml is application specific. It associates the rules from the global rules file with individual fields of your ActionForm. Struts has a class called ValidatorForm in org.apache.struts.validator package. This is a subclass of ActionForm and implements the validate () method. The validate () method invokes the Commons Validator, executes the rules using the two xml files and generates ActionErrors using the MessageResources defined in the struts-config.xml. All you have to do is extend your form from ValidatorForm and write your rules in XML.

Page 15: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 15 of 28

102. What is DynaActionForm? – It is a new feature in Struts 1.1. FormBeans can be declaratively defined in Struts-Config.xml file instead of writing an ActionForm class. There are two major differences between a regular ActionForm and a DynaActionForm.

a. For a DynaActionForm, the type attribute of the form-bean is always org.apach.struts.action.DynaActionForm.

b. A regular ActionForm is developed in Java and declared in the struts-config.xml. A DynaActionForm has no associated Java class. With DynaActionForm there is no validate() method.

103. What is DynaValidatorForm? – An application specific form can take advantage of XML based validation by virtue of sub classing the ValidatorForm. The XML based dynamic forms can also avail this feature by specifying the type of the form to be DynaValidatorForm. DynaValidatorForm is actually a subclass of DynaActionForm. It implements the validate () method much like the ValidatorForm and invokes the Commons Validator. DynaValidatorForm brings the capability of writing XML based validation rules for dynamic forms too.

104. What controller class needs to be used when using Tiles? – TilesRequestProcessor and this is specified in the Struts Config file in the <controller processorClass=” TilesRequestProcessor”> element.

105. How would you display an ArrayList of elements in a table format? – Using the Struts Iterator Tag. 106. How does Tiles framework work, what are tiles components, what are the advantages of

using Tiles over JSP Include? 107. Can you name some of the top-level packages in Struts framewok? –

Package

name Description

action

Contains the controller classes, the ActionForm, ActionMessages, and several other required framework components.

actions

Contains the "out-of-box" Action classes, such as DispatchAction, that can be used or extended by your application.

config

Includes the configuration classes that are in-memory representations of the Struts configuration file.

Page 16: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 16 of 28

Package name Description

taglib Contains the tag handler classes for the Struts tag libraries.

Tiles Contains the classes used by the Tiles framework.

upload

Includes classes used for uploading and downloading files from the local filesystem, using a browser.

Util Contains general-purpose utility classes used by the entire framework.

validator

Contains the Struts-specific extension classes used by Struts when deploying the validator. The actual Validator classes and interfaces are in the commons package, separate from Struts.

Web/JSP/Servlet 108. What is the difference between HTTP GET and HTTP POST? - GET" is basically for just getting

(retrieving) data whereas "POST" may involve anything, like storing or updating data, or ordering a product, or sending E-mail. The HTML specifications technically define the difference between "GET" and "POST" so that former means that form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. But the specifications also give the usage recommendation that the "GET" method should be used when the form processing is "idempotent" (i.e. it has no lasting observable effect on the state of the world), and in those cases only. If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms. If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.

109. What is the life cycle of a Servlet? – init, service and destroy. 110. What is the difference between Generic Servlet and HTTP Servlet? – javax.servlet.Servlet is the

central interface in the Servlet API. Every servlet class must directly or indirectly implement this interface. It has five methods: init (), service (), destroy (), getServletConfig () and getServletInfo (). The service (ServletRequest, ServletResponse) method handles requests and creates responses. The servlet container automatically calls this method when it gets any request for this servlet.

a. GenericServlet: javax.servlet.GenericServlet class implements the Servlet interface. It is an abstract class that provides implementation for all methods except the service () method of the Servlet interface. We can extend this class and implement the service () method to write any kind of servlet.

b. HTTP Servlet: javax.servlet.http.HTTPServlet represents a HTTP capable servlet and is an abstract class that extends GenericServlet. It provides the support for HTTP protocol. It adds a new service () method with the signature: service (HttpServletRequest, HttpServletResponse). For every HTTP method, there is a corresponding method in the HTTPServlet class, e.g.; doGet (), doHead (), doPost (), doDelete (), doPut (), doOptions () and doTrace (). Depending on the HTTP method, the corresponding doXXX () method is called on the servlet.

Page 17: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 17 of 28

111. How would you preinitialize/preload a servlet? – The servlet specification defines the <load-on-startup> element which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.

112. What is a ServletConfig? – The ServletConfig is defined in the javax.servlet package. It provides four methods: getInitParameter (String), Enumeration getInitParameterNames (), getServletContext () and getServletName (). A servlet container takes information specified about a servlet in the deployment descriptor and wraps it into a ServletConfig object. This information can then be retrieved by the servlet at the time of its initialization. It is passed as parameter to the init method: init(javax.servlet.ServletConfig).

113. What is a ServletContext? – ServletContext interface is a window for a servlet to view its environment. Every web application has one and only one ServletContext and it is available to all the active resources of that application. It is also used by the servlets to share data with one another. A servlet can use this interface to get information such as initialization parameters for the web application or the servlet container’s version. This interface also provides utility methods for retrieving MIME type for a file, for retrieving shared resources, for logging and so forth.

114. How would you forward a request from a Serlvet to a JSP? – Using RequestDispatcher. RequestDispatcher dispatcher = httpServletRequest.getRequestDispatcher (url); dispatcher.forward (httpServletRequest, httpServletResponse);

115. What is the difference between RequestDispatcher.forward() and HttpServletResponse.sendRedirect()? - An important difference between RequestDispatcher.forward() and HttpServletResponse.sendRedirect() is that forward() is handled completely on the server side while redirect() sends a redirect message to the browser. In that sense, forward() is transparent to the browser while redirect() is not. Both javax.servlet.ServletContext and javax.servlet.ServletRequest have the method getReqeustDispatcher(path).

116. How would you prevent outside access to certain resources in a WAR file? – Servlet Specification explicitly state that contents located in the WEB-INF and its sub-directories are protected from outside access. Any resource with in a WAR can access resources located under WEB-INF directory without restrictions.

117. In which directory is web.xml located? - \root\WEB -INF\ 118. Can you name some of the Authentication mechanisms built in to HTTP? – HTTP Basic

Authentication, HTTP Digest Authentication, HTTPS Client Authentication and HTTP FORM-based Authentication.

119. What is JSTL? – JSTL stands for JSP Standard Template Library. 120. What is the difference between Single Threaded and Multi Threaded models in Servlets? – In the

case of a multi threaded model, all client requests access exactly the same Servlet instance. Each client request is associated with its own thread of execution, and many threads will access the same instance simultaneously. All threads see the same instance and class variables, access to these variables should be avoided or synchronized using synchronized methods or blocks. In the case of a Single Threaded model, a separate instance is used for each client request. You don’t have to be worried about instance variables, they can be used freely with out synchronization. Access to static variables should be synchronized. This model degrades performance. The single-threaded model was deprecated as of Servlets 2.4, which is the specification supported by J2EE 1.4. In the future the single threaded model will be phased out of the specification.

121. What are the various types of mark-up tags provided by JSP? – JSP provides four major categories of markup tags.

a. Directives – page, include and taglib. b. Scripting elements - are used to embed programming instructions. JSP provides three types

of scripting elements: declarations, scriptlets and expressions. i. Declarations allow the developer to define variables and methods for a page, which

may be accessed by other scripting elements. <%! Declarations %> or <jsp:declaration> declarations </jsp:declaration>. You can declare both methods and variables.

Page 18: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 18 of 28

ii. Scriptlets are blocks of code to be executed each time the JSP page is processed for a request. <% scriptlet %>

iii. Expressions are individual lines of code. <%= expression %> c. Comments –

i. JSP comments - <%-- comment --%>, - the body of the these comments are ignored by the JSP container. When the page is compiled in to a Servlet, anything appearing between these two delimiters is skipped while translating the page in to Servlet source code.

ii. Scripting language comments - <% /* comment */ %> - Like JSP comments, scripting language comments will not appear in the page’s output. Unlike JSP comments, though, which are ignored by the JSP container, scripting language comments will appear in the source code generated for the Servlet.

d. Actions 122. What are the various scopes available in JSP? – page, request, session, application and these four

scopes are supported by the following four implicit objects: pageContext, request, session and application.

123. Can you name some of the implicit objects in JSP? – JSP Container exposes a number of internal objects to the page author. These are referred to as implicit objects, because their availability in a JSP page is automatic. These objects are automatically assigned to variable names and are accessible via JSP Scripting elements. Following are the nine implicit objects provided by JSP and they fall in to four main categories:

a. Objects related to a JSP Page’s Servlet i. page – Page’s Servlet instance(represents the Servlet itself)

ii. config – Servlet Configuration Data b. Objects concerned with page input and output

i. request – Request data including parameters ii. response – Response data

iii. out – output stream for page content c. Objects providing information about the context within which a JSP page is being processed

i. session – user specific session data ii. application – Data shared by all application pages

iii. pageContext – Context data for page execution d. Objects resulting from errors

i. Exception – Uncaught error exception 124. Can you name some of the standard Action Tags in JSP? – A standard action is an action tag that has

been defined by the JSP standard. Standard actions are associated with the namespace jsp and appear with a prefix jsp:

a. <jsp:forward page=”localURL” /> b. <jsp:include page=”localURL” flush=”flag” /> c. <jsp:plugin> is used to generate browser specific HTML for specifying java applets which

rely on the Sun Microsystems java plug-in. d. <jsp:useBean>, <jsp:setProperty> and <jsp:getProperty>

125. What is a Directive, Can you name some of the directives in JSP? – Directives are used to convey special processing information about the page to the JSP container. Directives are applied at page translation(compile) time.

a. Page directive: <%@ page attr1=”val1” … %> . There are a list of attributes supported by the page directive: info, language, contentType, pageEncoding, extends, import, session, buffer, autoFlush, isThreadSafe, errorPage, isErrorPage.

i. The errorPage attribute is used to specify an alternate page to display if an uncaught error occurs while the JSP container is processing the page.

Page 19: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 19 of 28

ii. When the isErrorPage attribute is set to true, it indicates that the current page is intended for use as a JSP error page. As a result, this page will be able to access the exception implicity object.

b. Include directive: <%@ include … %> c. Taglibrary directive: <%@ taglib uri=”” prefix=”” %>

126. What are the various steps involved in creating a Tag Library? -

JMS 127. What are the different types of messaging models (messaging domains) in JMS? – Publish-and-

Subscribe, Point-to-Point. 128. In which package would you find the JMS API? – javax.jms. 129. Why would you choose messaging over other Java technologies like RMI? – JMS is a very loosely

coupled technology while RMI is very tightly coupled. 130. Explain Publish and Subscribe? Producers send messages to a Topic. All of the registered consumer

for that topic can retrieve those messages. Many consumers can receive the same message. 131. Explain Point to Point? Point to Point is built around the concept of message queues, sender and

receivers. A message producer sends a message to a specific queue. A message consumer can attach itself to a queue and listen for messages. When a message arrives on the queue, the consumer removes it from the queue and responds to it. Each message can have only one consumer.

132. What are the three components of a message? – Header, Properties and Body. 133. What kind of information is found in the header of a message? – The header of a message contains

message identification and routing information. 134. What the different message body formats defined in JMS API? – There are five of them:

StreamMessage, MapMessage, BytesMessage, TextMessage and ObjectMessage. 135. Which object is used to create a QueueSession object? – It is created from QueueConnection. 136. What is QueueSession responsible for? – Messages, Senders, Receivers, Transactions. 137. Is QueueSession object single or multi-threaded? – Single Threaded. Any message sending and

receiving happens in a well defined serial order. 138. What are the two methods of javax.jms.MessageConsumer used to receive messages in blocking and

non-blocking mode? – receive() and receiveNoWait(). 139. Explain the life cycle of a JMS sender application by explaining the steps you would need to perform

in order to send a message? – a. Use the JNDI to get Connection Factory and Destination object (either Queue or Topic). b. Create a Connection Object. c. Create a Session object in order for sending/receiver messages. d. Create a MessageProducer object. (Either a TopicPublisher or QueueSender). e. Start the Connection. f. Send the message to its destination. g. Close the session and connection.

140. Explain the life cycle of a JMS receiver application by explaining the steps you would need to perform in order to receive a message that will block?

a. Use the JNDI to get Connection Factory and Destination object (either Queue or Topic). b. Create a Connection Object. c. Create a Session object in order for sending/receiver messages. d. Create a MessageConsumer object (either a TopicSubscriber or QueueReceiver). e. Start the connection f. Receive the message. g. Close the session and connection.

Page 20: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 20 of 28

Databases 141. What is normalization in Database? 142. What is an Index in a Database? 143. What is an Outer Join? How would you write an outer join, i.e. what would the generic syntax be?

(Non vendor specific syntax?) 144. What is the difference between optimistic and pessimistic locking in a DB sense? 145. When two tables are joined with out a Where Clause, what is the output in the following case? –

select a.*, b.* from a, b – When two tables are joined, the database forms a Cartesian product i.e. all the rows in table a are mapped with all the rows in table b.

146. What is a Correlated Sub query? - A correlated subquery is a query within a query where the inner query is evaluated for each row in the outer query. A correlated sub query is a nested select that refers to a column from the outer select. In some cases they can rank among the poorest performing SQL statements imaginable because the inner result set must be constructed for every single row that is a candidate for inclusion in the outer result set. If both the inner and outer result sets are large the amount of processing required can be huge. Eg: SELECT COUNT (*) FROM parent1 WHERE NOT EXISTS (SELECT * FROM child1 WHERE parent1.primary1 = child1.primary1).

147. What is the difference between Where clause and Having clause? Where clause is used to filter rows whereas Having clause is used to filter groups.

148. What is Referential Integrity (RI)? - RI is explicitly declaring the relationships between tables (foreign keys) using DDL and the built-in server functions rather than using triggers or stored procedures to enforce relationships.

149. What is a Clustered Index? - Clustered indexes are indexes where the data rows are actually the leaf nodes of the index. The data is then physically stored in the indexed order. Only one clustered indexes per table 255 additional nonclustered indexes per table.

150. Have you worked on SQL tuning? What are the things that you’ve done to achieve SQL tuning?

XML/XSLT 151. What is XML? – eXtensible Markup Language (XML) is a meta-language – defines a set of tags that

are used to organize and describe text. 152. What is a DTD? – Document Type Definition (DTD) can be used to describe XML markup

languages and to validate instances of them (XML documents). 153. What does a “well formed” XML Document mean? – To be well formed, an XML document must

obey the syntactic rules of the XML mark up language. 154. What does a “Valid” XML Document mean? – In addition to being well formed, it’s sometimes

important to check that the document uses the right types of elements and attributes in the correct order and structure. DTD (Document Type Definition) validates the order and structure of an XML document.

155. What is a CDATA section in XML? – A CDATA section allows you to mark a section of text as literal so that it will not be parsed for tags and symbols, but will instead be considered just a string of characters. CDATA Sections take form <![CDATA[ text goes here ]]>.

156. What is the difference between SAX and DOM parsers? – SAX Parser uses an event based architecture for processing XML documents. It fires off events every time it encounters a new element, attribute, piece of text or other component. SAX Parsers are faster because they read an XML document sequentially and it can handle parsing huge XML documents. DOM presents the programmer with a generic, object-oriented model of an XML document. Elements, attributes and text values are represented as objects organized into a hierarchical tree structure that reflects the hierarchy of the XML document being processed. DOM allows an application to navigate the tree structure, modify elements and attributes, and generate new XML documents in

Page 21: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 21 of 28

memory. It’s a very powerful and flexible programming model, but its also slow compared to SAX, and consumes a lot more memory.

157. Can you explain the architecture of SAX, in terms of how you would use it to parse an XML document? – To use SAX, you create a class that implements one of the SAX listener interfaces, and register an instance of that class with a SAX parser at runtime. A SAX parser reads an XML document from a data stream sequentially, from beginning to end. As it reads the stream, the SAX parser sends events to the listener object that you registered. For e.g.: at the start of the XML document the parser invokes the listener’s startDocument () method, when it reads the start tag of an element it invokes the listener’s startElement () method, and when it reads the end tag of an element it invokes the listener’s endElement () method. The primary listener interface in SAX2 is the ContentHandler, which defines 11 methods, each of which corresponds to some part of an XML document. To make life easier, SAX2 provides an adapter class, org.xml.sax.helpers.DefaultHandler, which implements ContentHandler with empty methods. You can extend DefaultHandler, overriding only the event methods you want to implement, and ignore the rest.

158. What is the name of the XML parser that is part of the Java 2 Platform? – Crimson. 159. What is XSLT? - When your presentation model is XML, the most common approach for view

generation is to perform a View Transform using the extensible stylesheet language (XSL). XSL is a language consisting of three major components, two of which are dedicated to accessing and transforming XML. These two components are XSL Transformations (XSLT) and XML Path Language (XPath), a robust expression language used by XSLT [XSL]. How is this approach different from the typical JSP approach? XML is fed into a transforming engine along with a style sheet that describes how each part of the XML model should look in the view. The style sheet's formatting rules are matched to portions of the XML, triggering transformations that result in a different set of XML, adapted for the view. The style sheet encapsulates formatting-related code only, reducing its coupling to the XML content, which serves as the model.

Web services 160. What is a Webservice? - A Webservice is a remote application described using WSDL (Web Service

Description Language) and accessed using SOAP (Simple Object Access Protocol) according to the rules defined by the WSI (Web services Integration Organization).

161. What is an XML Schema, how does it differ from a DTD? – A schema describes an XML markup language. Specifically it defines which elements and attributes are used in a markup language, how they are ordered and nested, and what their data types are. To address limitation of DTDs, the W3C which manages the fundamental XML standards, created a new way to describe markup languages called XML Schema. DTDs have done an adequate job of telling us how elements and attributes are organized in a markup language, but they fail to address data typing. While constraints provided by DTDs are useful for validating XML instances, the probability that an XML instance will have a valid organization but invalid data is pretty high. DTDs have a very weak typing system that restricts elements to four broad types of data: EMPTY, ANY, element content or mixed element and text content. DTD don’t support types like integer, decimal, boolean and enumeration. XML Schema, by contrast, provides a much stronger type system which includes simple primitives (integer, double, boolean etc) as well as facilities for more complex types. XML schema facilitates type inheritance, which allows simple or complex types to be extended or restricted to create new types. In addition, XML schema supports the use of XML namespaces to create compound documents composed of multiple markup languages.

162. What is the difference between complex types and simple types in XML Schemas? – Complex types describe how elements are organized and nested. Simple types are the primitive data types contained by elements and attributes. Simple types resemble Java primitive types in that both are atomic; they cannot be broken down into constituent parts. It will only contain data. The XML schema specification defines

Page 22: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 22 of 28

many standard simple types (string, integer, float etc). Whereas a Complex Type is analogous to a Java class definition with fields but no methods.

163. What is the difference between extension and restriction in XML Schema in regards to Complex types? – Complex types can use two types of inheritance: extension and restriction. Both allow you to derive new complex types from existing complex types. Extension broadens a derived type by adding elements or attributes not present in the base type, while restriction narrows a derived type by omitting or constraining elements and attributes defined by the base type.

164. What is an XML Namespace? – An XML namespace provides a qualified name for an XML element or attribute, the same way that a Java package provides a qualified name for a Java class. Java package names allow us to separate Java classes into distinct namespaces, which improves organization and access control, and helps us avoid name conflicts. XML namespaces are similar to Java packages, and serve the same purposes; an XML namespace provides a kind of package name for individual elements and attributes.

165. What is SOAP? – SOAP 1.1 is simply a distributed object protocol like DCOM and CORBA IIOP. SOAP 1.1 is the standard messaging protocol used by J2EE Web Services, and is the de facto standard for Web services in general. SOAP’s primary application is Application to Application communication. SOAP has a clear purpose: exchanging data over networks. The most significant difference between SOAP 1.1 and other distributed object protocols is that SOAP is based on XML. EJB 2.1 and J2EE 1.4 are standardized on SOAP 1.1. SOAP is defined by its own XML Schema and relies heavily on the use of XML Namespaces. Every SOAP message that is sent across the wire is an XML document that consists of standard SOAP elements and application data. The use of namespaces differentiates the standard SOAP elements from the application data. Specifically, its used in B2B and EAI: Both focus on integration software applications and sharing data. To be truly effective in B2B and EAI, a protocol must be platform independent, flexible and based on standard technologies.

166. Explain the basic structure of SOAP? – SOAP message is a kind of XML document. SOAP has its own XML schema, namespaces and processing rules. A SOAP message is composed of the following elements:

a. <Envelope> element is the root of the SOAP message; all other elements are contained by it. It contains two different children <Header> element and the <Body> element.

b. <Header> element is generally used for carrying infrastructure data such as security tokens, transaction IDs, routing information, and so on. Header element is optional.

c. <Body> element carries the application specific data or a fault message. Application-specific data is the information that we want to exchange with a Webservice.

167. What are the different SOAP Messaging Modes? – Although SOAP supports four modes of messaging (RPC/Literal, Document/Literal, RPC/Encoded and Document/Encoded) the Webservice Base Profile permits the use of RPC/Literal or Document/Literal only. The RPC/Encoded and Document/Encoded modes are explicitly prohibited. A messaging mode is defined by its messaging style (RPC or Document) and its encoding style. The term “Literal” means that the XML document fragment can be validated against its XML schema.

168. What is Document/Literal mode? – In this mode of messaging, a SOAP Body element contains an XML document fragment, a well-formed XML element that contains arbitrary application data that belongs to an XML schema and namespace.

169. What is RPC/Literal mode? – This mode of messaging enables SOAP messages to model calls to procedures or method calls with parameters and return values. In RPC/Literal messaging, the contents of the Body are always formatted as a struct. An RPC request message contains the method name and the input parameters of the call. An RPC response contains the return value and any output parameters. In many cases, RPC/Literal messaging is used to expose traditional, components as Webservices.

170. What are the different Messaging Exchange Patterns? – One-Way and Request/Response. 171. SOAP messages are delivered using which protocol? – HTTP. Its possible to deliver SOAP messages

using other protocols, such as SMTP and FTP as well, but details of these non-HTTP bindings are not specified by SOAP and are not supported by the Webservices Basic Profile.

Page 23: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 23 of 28

172. Are SOAP messages delivered using HTTP POST or HTTP GET? – HTTP requests are typified by the messages that your browser sends to a Web server to request a Web page or submit a form. A request for a Web page is usually made in an HTTP GET message, while submission of a form is done with an HTTP POST message. While HTTP GET request is perfectly suited for request Web pages, it doesn’t have a payload area and therefore cannot be used to carry SOAP messages.

173. What is WSDL? – WSDL 1.1(Web Service Description Language) is an XML markup language used to describe a WebService. WSDL is used to specify the exact message format, Internet protocol, and address that a client must use to communicate with a particular Webservice.

174. Can you explain the basic structure of WSDL? – A WSDL document is an XML document that adheres to the WSDL XML schema. As an XML document instance, a WSDL document must use the correct elements in the correct fashion if it is to be valid and well formed. A WSDL document contains seven important elements: types, import, message, portType, operations, binding and service which are nested in the definitions element, the root element of a WSDL document.

175. What is UDDI? UDDI (Universal Description, Discovery and Integration) is a specification for creating a registry service that catalogs organizations (corporations) and their Webservices. You can access the data in a UDDI directory using SOAP, which makes a UDDI registry a Webservice. The UDDI specification describes about thirty different SOAP operations that allow you to add, update, delete and find information contained in a UDDI registry.

176. What is SAAJ? SOAP with Attachments API for Java (SAAJ) is an API for manipulating the structure of a SOAP message. SAAJ is an API you can use to create, read or modify SOAP messages using Java. SAAJ provides a number of interfaces you can use to construct a simple SOAP document. SAAJ is based on the Abstract Factory Pattern. Message Handlers in JAX-RPC use SAAJ to represent SOAP message.

177. SAAJ 1.2 redefined its API based on DOM or SAX? – DOM. 178. What is JAX-RPC? Java API for XML based RPC is basically Java RMI over SOAP. JAX-RPC is

deigned as a Java API for Webservices, so that J2EE applications can interoperate with non-Java applications. JAX-RPC is the very soul of J2EE Webservices. It defines the standard programming model for both Webservice clients and endpoints in J2EE. There are essentially two sides to the JAX-RPC model: client-side and server-side. The client-side programming model allows you to access a remote Webservice as if it were a local object, using methods that represent SOAP operations. The server-side programming model allows you to develop Webservice endpoints as Java objects or EJBs, which run on the J2EE platform.

179. What are the two Programming Models supported by JAX-RPC? - They are Server-side and Client-side programming models.

a. Server-Side programming Model: JAX-RPC defines two server-side programming models for creating J2EE Webservice endpoints: JAX-RPC service endpoints and EJB endpoints.

i. A JAX-RPC service endpoint (JSE) is easy to develop because its just a plain old Java object. In reality, a JSE is a full-fledged J2EE component, which runs inside the J2EE Servlets container system. It has access to the same resources and contexts as a standard servlet, but instead of exposing HTTP streams, it marshals SOAP messages in to method invocations defined by a remote interface. A JSE is composed of two parts: an implementation class that does all the work, and a java.rmi.Remote interface, called the endpoint interface, that declares the Webservice’s publicly accessible methods. Once you have defined the endpoint interface and implementation objects, you can use them along with other deployment files, to generate a WSDL document that provides a platform independent description of the JSE.

ii. Enterprise JavaBeans Endpoints: Stateless session beans can acts as Webservice endpoints. Because SOAP is a stateless messaging protocol, only stateless session beans can acts as EJB endpoints. Endpoint interface extends the javax.ejb.Remote interface. EJB endpoints do not require a corresponding home interface. SOAP

Page 24: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 24 of 28

doesn’t specify support for pass-by-reference, so you can’t ask one Webservice interface (a home interface) to pass you a reference to another (a remote interface).

b. Client-Side Programming Model: The JAX-RPC client –side programming models can be used by Java applications, servlets, JSPs, JAX-RPC service endpoints (JSEs) and EJBs to exchange SOAP messages with remote Webservice endpoints on any platform. JAX-RPC defines three client-programming models:

i. Generate Stubs: The JAX-RPC compiler which is provided by your J2EE vendor, generates Java remote interfaces and stubs that implement the endpoint operations described by the WSDL document. Once the stubs and interfaces are generated, you can bind them to the JNDI ENC (Environment Naming Context) of the any J2EE component and use them to communicate with the endpoint. Stuns are generated at deployment time.

ii. Dynamic Proxy: A dynamic proxy is used in the same way as a generated stub, except the remote interface’s stub implementation is generated dynamically, at runtime.

iii. DII (Dynamic Invocation Interface): JAX-RPC also provides another, even more dynamic API, called the Dynamic Invocation Interface. DII allows the developer to assemble SOAP method calls dynamically at runtime.

180. What is Message Handler? – Message handlers allow you to manipulate SOAP messages that are sent and received by JAX-RPC clients and Webservice endpoints. The primary purpose of message handlers is to provide a mechanism for adding, reading and manipulating header blocks in SOAP messages that JAX-RPC clients and Webservice endpoints send and receive. Message handlers operate behind the scenes, and are managed by the J2EE container system. At runtime the message handlers are not visible to your application code – they are applied automatically by the JAX-RPC runtime system.

181. What is JAXR? Java API for XML Registries (JAXR) allows you to access WebService registries usually UDDI (Universal Description, Discovery and Integration).

182. What is JAXP? - The Java API for XML Processing (JAXP) enables applications to parse and transform XML documents independent of a particular XML processing implementation. It is not a parser. It’s a set of factory classes and wrappers for DOM2 and SAX2 parsers.

183. What is JAXB? - Java Architecture for XML Binding (JAXB) provides a convenient way to bind an XML schema to a representation in Java code. This makes it easy for you to incorporate XML data and processing functions in applications based on Java technology without having to know much about XML itself.

184. What is JAXM? – Java API for XML Messaging.

JAVA 185. What is the difference between an Interface and an Abstract Class? – Abstract class can have

implementation whereas an interface cannot. 186. What is the difference between ArrayList and Vector? – Vector is synchronized whereas ArrayList is

not. 187. What is the difference between Treeset and HashSet? – The two general purpose Set implementations

are HashSet and TreeSet. HashSet is much faster (constant time versus log time for most operations) but offers no ordering guarantees.

188. What type of Collection would not allow duplicate elements? – Set. 189. What type of Collection provides support for ordered elements? – List. The user of this interface has

precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.

190. What is the difference between Hashtable and Hashmap? – a. Hashtable is synchronized whereas Hashmap is not. b. Hashmap permits null values and the null key.

Page 25: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 25 of 28

191. Are the Collection implementations in the J2SE API are Serializable? –Yes. 192. What interface do you implement to do sorting? – Comparable. 193. What is the difference between java.lang.Comparable and java.util.Comparator? 194. Why is the String class final in Java? - You can declare that your class is final, that is, that your class

cannot be subclassed. You might want to do this for two reasons: (1) to increase system security by preventing system subversion, and (2) for reasons of good object-oriented design.

Security: One mechanism that hackers use to subvert systems is to create a subclass of a class and to then substitute the subclass for the original. The subclass looks and feels like the original class but does vastly different things, possibly causing damage or getting into private information. To prevent this kind of subversion, you can declare your class to be final and thereby prevent any subclasses from being created. The String class is a final class for just this reason. This class is so vital to the operation of the Java platform that it must guarantee that whenever a method or an object uses a String, it gets exactly a java.lang.String and not another kind of string. This ensures that all strings have no strange, inconsistent, undesirable, or unpredictable properties.

If you try to compile a subclass of a final class, the compiler prints an error message and refuses to compile your program. In addition, the Java runtime system ensures that the subversion is not taking place at the bytecode level. It does this by checking to make sure that a class is not a subclass of a final class.

195. How do you serialize an object in Java? - To persist an object in Java, a. Step 1: An object is marked serializable by implementing the java.io.Serializable

interface, which signifies to the underlying API that the object can be flattened into bytes and subsequently inflated in the future.

b. Step 2: The next step is to actually persist the object. That is done with the java.io.ObjectOutputStream class. That class is a filter stream--it is wrapped around a lower-level byte stream (called a node stream) to handle the serialization protocol for us. Node streams can be used to write to file systems or even across sockets. That means we could easily transfer a flattened object across a network wire and have it be rebuilt on the other side!

c. To restore the object back, you use ObjectInputStream.readObject() method call. The method call reads in the raw bytes that we previously persisted and creates a live object that is an exact replica of the original. Because readObject () can read any serializable object, a cast to the correct type is required. With that in mind, the class file must be accessible from the system in which the restoration occurs. In other words, the object's class file and methods are not saved; only the object's state is saved.

196. How would you customize the serialization process? - By using a built-in feature of the serialization mechanism, developers can enhance the normal process by providing two methods inside their class files. Those methods are:

a. private void writeObject (ObjectOutputStream out) throws IOException; b. private void readObject (ObjectInputStream in) throws IOException,

ClassNotFoundException; Notice that both methods are (and must be) declared private, proving that neither method is inherited and overridden or overloaded. The trick here is that the virtual machine will automatically check to see if either method is declared during the corresponding method call. The virtual machine can call private methods of your class whenever it wants but no other objects can. Thus, the integrity of the class is maintained and the serialization protocol can continue to work as normal. The serialization protocol is always used the same way, by calling either ObjectOutputStream.writeObject () or ObjectInputStream.readObject (). So, even though those specialized private methods are provided, the object serialization works the same way as far as any calling object is concerned.

197. What if you create a class whose superclass is serializable but you do not want that new class to be serializable? - To stop the automatic serialization, you can once again use the private methods to just throw the NotSerializableException.

Page 26: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 26 of 28

198. How would you call a Stored Procedure from Java? – Using Callable Statement. 199. What is the difference between Statement and PreparedStatement? – PreparedStatements are pre-

compiled statements. The database doesn’t have to compile the sql each and every time it is executed. 200. How can you force Garbage Collection? – Garbage collection cannot be forced. 201. What is final, finalize () and finally?-

a. final: final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value.

b. finalize (): finalize () method is used just before an object is destroyed and called just prior to garbage collection.

c. finally: finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.

202. What is a Marker Interface? – An interface with no methods. Example: Serializable, Remote, Cloneable.

203. How would you clone an Object? By invoking the clone () method. Clone () method is declare in java.lang.Object and does a shallow copy. Invoking clone () on any object will throw a CloneNotSupportedException unless that class implements the Cloneable marker interface.

204. What is the eligibility for an Object to get cloned? – It must implement the Cloneable interface. 205. What are the different driver types available in JDBC? - 1. A JDBC-ODBC bridge 2. A native-API

partly Java technology-enabled driver 3. A net-protocol fully Java technology-enabled driver 4. A native-protocol fully Java technology-enabled driver. Level 4 drivers are completely implemented in Java to achieve platform independence and eliminate deployment administration issues. Useful for Internet-related applications.

206. Why would you use a Custom Class Loader? – In order to load classes over the network or from any source other than the class path, you must use a custom ClassLoader object that knows how to obtain data from that source.

Other J2EE Technologies/Frameworks 207. What is ANT? 208. What is JUNIT? 209. What is SPRING Framework? 210. What is HIBERNATE Framework? 211. What is Java RMI/JRMP? Remote Method Invocation (RMI) facilitates object function calls between

Java Virtual Machines (JVMs). JVMs can be located on separate computers. Methods can even pass objects that a foreign virtual machine has never encountered before, allowing dynamic loading of new classes as required. RMI was initially designed with JRMP (Java Remote Method Protocol) as the Java technology specific protocol for looking up and referencing remote objects. JRMP is a proprietary stream based protocol.

212. What is Java RMI-IIOP? - Java Remote Method Invocation technology run over Internet Inter-Orb Protocol ("RMI-IIOP") delivers Common Object Request Broker Architecture (CORBA) distributed computing capabilities to the Java 2 platform. Use the rmic Compiler with the -iiop option to generate stubs, skeletons, and ties for remote objects using the IIOP protocols. RMI server objects can use the IIOP protocol and communicate with CORBA client objects written in any language.

213. What is Maverick? - The Maverick MVC framework offers the ability to render views using JSP, the Velocity scripting language, or XSLT. Maverick is an MVC-type architecture, but it actually provides a view template mechanism. One neat feature of Maverick is that it can use reflection on JavaBeans in the

Page 27: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 27 of 28

presentation layer to create a DOM interface, so no XML generation or parsing is required. This allows for a little less clutter and probably better performance when using XSLT to generate the views. You can find more information on the Maverick framework at http://mav.sourceforge.net.

214. What is Webwork? - WebWork is a web application framework that uses the Pull Hierarchical Model View Controller (HMVC) design. With a standard MVC design, changes made to the model are pushed to the view. In the case of WebWork, the views pull the data when they need it. Interestingly, WebWork doesn't seem to be tied to a servlet; therefore, it can support other types of clients such as Swing. More information on the WebWork framework can be found at http://www.opensymphony.com/webwork.

215. What is JNDI-ENC (Environment Naming Context)? – All J2EE components including sevlets, EJBs etc have access to a private set of environment variables and resources using JNDI (Java Naming and Directory Interface). JNDI is usually used for access to a naming or directory service. A naming service binds objects or resources to names. A directory service also binds names to objects or resources and can organize bindings into a directory structure analogous to the directory structure used by your file system. Examples of directory systems include LDAP. J2EE defines a very simple directory service, called the JNDI Environment Naming Context (JNDI ENC), which allows developers to bind resources (JDBC and JMS connection factories, for example), EJBs, Webservice endpoints and environment variables into a directory structure. The JNDI ENC is a standard service available to all J2EE components, but each component has a unique view of the service. A component may access its own view of the JNDI ENC, but not the view of any other component. Every component’s view of the JNDI ENC is fixed at deployment time and is immutable, which means that it’s read-only. You cannot insert, remove, or modify values in the JNDI ENC at runtime.

The InitialContext object represents the root of the JNDI ENC hierarchy. Eg: javax.naming.InitialContext jndiEnc = new javax.naming.IntitalContext ();

Javax.sql.Datasource ds = (javax.sql.DataSource) jndiEnc.lookup (“java:comp/env/jdbc/DataSource”); Resources like the JDBC DataSource in the previous example are bound to names that you declare in the deployment descriptor. The root context of the JNDI ENC is always “java:comp/env”, but you can define any path relative to the root context you want.

Questions to be included 216. Struts and Web App Exception handling. 217. Transactional Attributes – scenarios, exceptions 218. Different types of GOF Patterns - creational, structural and behavioral 219. Different ways of creating Threads 220. Exception hierarchy 221. How would you invalidate a session 222. what is the signature of the method in MDB? What interface do you implement? 223. Tool for Code Reviews 224. Tool used for Unit Testing of Web pages. 225. What is a Non Clustered Index 226. What is the default port used in Webservices 227. How would you configure your application to use Struts 228. Can a Singleton Pattern have multiple instances 229. PL/SQL Section 230. What are the functions in a JUnit test case? – setUp, testXXX, tearDown. 231. What experience do you have with Unit Testing (i.e. J Unit) 232. If you have a swing application with multiple threads and you want to update a J Button.... 233. Threading: what is the "Race Condition"? 234. Regarding DB maintenance work, any experience tuning DB at the table and/or code level?

Page 28: Table of Contents · support, J2EE 1.4 offers platform Web services interoperability. a. JSP 2.0 J2EE Patterns/Design Patterns 14. What is MVC Architecture? What are its advantages?

Page 28 of 28

235. Regarding struts, if you had something you wanted to do with struts prior to action class, what can you do?

236. What experience do you have with web start (to configure)? 237. What is a possible way to authenticate user ID vs Password, etc.? 238. Regarding Java swing, can you describe your GUI testing experience? 239. Can you describe your test experience with TCP and UDP? What's the difference? What is the

disadvantage associated with UDP? 240. Regarding JDBC, if you want to execute four different rows to table in one shot, can you? How? 241. Regarding EJB, what are different ways if I want to call an external library? 242. Describe your experience with threading. 243. What XML API's have you used? 244. Ever used static initializers? What are they and when are they utilized? What is the difference

between an instance variable and a static variable? 245. EJB - Session Synchronization. 246. Servlet Chaining 247. Home interface methods 248. In how many different ways can you create objects in Java. 249. What is Agile technology? 250. How EJB implements Composite Object pattern 251. How using JMX measure the performance of a module in a J2EE application & bottleneck points. 252. How to you prevent the refresh button hit of a browser using custom class loader 253. Datasource.Connection.close() what happens 254. Exception Object in JSP, 255. Diff between CMP and BMP 256. Can we give a return statement in a finally block 257. How can I call a chain of constructors 258. Is manifest file present for WAR file? 259. What is reference cursor in oracle? 260. How can you write threads in ejb? Why cannot you write threads Can we have any type of object in

JNDI? 261. Can we call ejbRemove() in User code? 262. Why should one use EL? 263. Why do you need Home and Remote Interfaces? 264. What Pattern is EJB Remote Interface based on? 265. Struts Tags. 266. What is XJC, Cactus, CruiseControl 267. Manual Connection Pooling 268. How do you handle the Exceptions at various tiers of an application (UI, Business and database) and

how do show them to the users? 269. How do you obtain the JDBC connection? 270. How would you synchronize ArrayList? 271. Different acknowledgement modes in JMS 272. Steps to send a message 273. EJB exceptions handling in CMT/BMT 274. Methods defined in home interface 275. Methods defined in entity bean 276. Design patterns - Value List Handler, Composite entity, Command, Decorator 277. UML - Use Cases, State Diagrams, Class Diagrams, Realizations 278. Exception handling in Struts 279. Can you have nested transactions in EJBs 280. Form validation in Struts 281. Nested transactions in databases


Recommended