Sie sind auf Seite 1von 26

1. What makes J2EE suitable for distributed multitiered Applications?

- The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are: o Client-tier components run on the client machine. o Web-tier components run on the J2EE server. o Business-tier components run on the J2EE server. o Enterprise information system (EIS)-tier software runs on the EIS server. What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications. What are the components of J2EE application? - A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: Application clients and applets are client components. Java Servlet and JavaServer Pages technology components are web components. Enterprise JavaBeans components (enterprise beans) are business components. Resource adapter components provided by EIS and tool vendors. What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program. Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier. Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture. Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either. What can be considered as a web component? - J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. What is the container? - Containers are the interface between a component and the lowlevel platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.

2. 3.

2.

1. 2. 3. 4.

3.

4.

5.

6.

7.

8. What are container services? - A container is a runtime support of a system-level entity.


Containers provide components with services such as lifecycle management, security, deployment, and threading. 9. What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server. 10. What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications. Enterprise beans and their container run on the J2EE server. 11. What is Applet container? It manages the execution of applets. Consists of a Web browser and Java Plugin running on the client together. 12. How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a components deployment settings. 13. What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications. 14. What are types of J2EE clients? - Following are the types of J2EE clients:

o o o o

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

4. What is deployment descriptor? - A deployment descriptor is an Extensible Markup


Language (XML) text-based file with an .xml extension that describes a components deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesnt call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesnt directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE

5. 6.

7.

8.

application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system. 9. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization. 10. What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS. 11. What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between. 12. How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an applications business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.

1. What is Jakarta Struts Framework? - Jakarta Struts is open source implementation of MVC
(Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. What is ActionServlet? - The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests. How you will make available any Message Resources Definitions file to the Struts Framework Environment? - Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <messageresources /> tag. Example: <message-resources parameter=MessageResources /> What is Action Class? - The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

2.

3.

4.

5. Write code of any Action Class? - Here is the code of Action Class that returns the
6. 7. ActionForward object. import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23.

import import import import

org.apache.struts.action.Action; org.apache.struts.action.ActionForm; org.apache.struts.action.ActionForward; org.apache.struts.action.ActionMapping;

public class TestAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward(\"testAction\"); } } 24. What is ActionForm? - An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

25. What is Struts Validator Framework? - Struts Framework provides the functionality to
validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

26. Give the Details of XML files used in Validator Framework? - The Validator Framework
uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean. 27. How you will display validation fail errors on jsp page? - The following tag displays all the errors: <html:errors/>

28. How you will enable front-end validation based on the xml in validation.xml? - The
<html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName=logonForm dynamicJavascript=true staticJavascript=true /> generates the client side java script for the form logonForm as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.

^Back to Top Tough interview questions on EJB

1. How EJB Invocation happens? - Retrieve Home Object reference from Naming Service via
JNDI. Return Home Object reference to the client. Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to Bean (Enterprise Bean). Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? - You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be

2.

3.

4.

5.

6.

7.

consider as passed-by-value, that means that its read-only in the EJB. If anything is altered from inside the EJB, it wont be reflected back to the HttpSession of the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTPbased client. This higher level of abstraction will be flexible enough to support it. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is, again, up to the implementer. Can the primary key in the entity bean be a Java primitive type such as int? - The primary key cant be a primitive type. Use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive). Can you control when passivation occurs? - The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD -The passivation-strategy can be either default or transaction. With the default setting the container will attempt to keep a working set of beans in the cache. With the transaction setting, the container will passivate the bean after every transaction (or method call for a nontransactional invocation). What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other? Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you dont need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container. What is EJB QL? - EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistenceand is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.

8. Brief description about local interfaces? - EEJB was originally designed around remote
invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence. 9. What are the special design care that must be taken when you work with local interfaces? - It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision. 10. What happens if remove( ) is never invoked on a session bean? - In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool. 11. What is the difference between Message Driven Beans and Stateless Session beans? - In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls. 12. How can I call one EJB from inside of another EJB? - EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth. 13. What is an EJB Context? - EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.

^Back to Top Java Web development interview questions

1. Can we use the constructor, instead of init(), to initialize servlet? - Yes , of course you
can use the constructor instead of init(). Theres nothing to stop you. But you shouldnt. The original reason for init() was that ancient versions of Java couldnt dynamically invoke

constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you wont have access to a ServletConfig or ServletContext. 2. How can a servlet refresh automatically if some new data has entered the database? - You can use a client-side Refresh or Server Push. 3. The code in a finally clause will never fail to execute, right? - Using System.exit(1); in try block will not allow finally code to execute. 4. How many messaging models do JMS provide for and what are they? - JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing. 5. What information is needed to create a TCP Socket? - The Local System?s IP Address and Port Number. And the Remote Systems IPAddress and Port Number. 6. What Class.forName will do while loading drivers? - It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS. 7. How to Retrieve Warnings? - SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object 8. SQLWarning warning = stmt.getWarnings(); 9. if (warning != null) 10. { 11. while (warning != null) 12. { 13. System.out.println(\"Message: \" + warning.getMessage()); 14. System.out.println(\"SQLState: \" + warning.getSQLState()); 15. System.out.print(\"Vendor error code: \"); 16. System.out.println(warning.getErrorCode()); 17. warning = warning.getNextWarning(); 18. } 19. } 20. How many JSP scripting elements are there and what are they? - There are three scripting language elements: declarations, scriptlets, expressions. 21. In the Servlet 2.4 specification SingleThreadModel has been deprecated, why? Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level. 22. What are stored procedures? How is it useful? - A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of dbs support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases. 23. How do I include static files within a JSP page? - Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request. 24. Why does JComponent have add() and remove() methods but Component does not? because JComponent is a subclass of Container, and can contain other components and jcomponents.

25. How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by
having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

^Back to Top EJB interview questions

1. Is is possible for an EJB client to marshal an object of class java.lang.Class to an


EJB? - Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. Is it legal to have static initializer blocks in EJB? - Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods. Is it possible to stop the execution of a method before completion in a SessionBean? - Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB. What is the default transaction attribute for an EJB? - There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for those methods having container managed transaction. In WebLogic, the default transaction attribute for EJB is SUPPORTS. What is the difference between session and entity beans? When should I use one or the other? - An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw) Is there any default cache management system with Entity beans ? In other words whether a cache of the data in database will be maintained in EJB ? - Caching data from a database inside the Application Server are what Entity EJBs are used for.The ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the persistent storage(database). Transactions also play an important role in this scenario. If data is removed from the database, via an external application - your Entity Bean can still be alive the EJB container. When the transaction commits, ejbStore() is called and the row will not be found, and the transaction rolled back. Why is ejbFindByPrimaryKey mandatory? - An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB. Why do we have a remove method in both EJBHome and EJBObject? - With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it (you can provide a PrimaryKey object as a parameter to the remove method). The home version only works for entity beans. On the other hand, the Remote interface version works on an entity bean that you have already instantiated. In addition, the remote version also works on session beans (stateless and stateful) to inform the container of your loss of interest in this bean. How can I call one EJB from inside of another EJB? - EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.

2.

3.

4.

5.

6.

7.

8.

9.

10. What is the difference between a Server, a Container, and a Connector? - An EJB
server is an application, usually a product such as BEA WebLogic, that provides (or should provide) for concurrent client connections and manages system resources such as threads, processes, memory, database connections, network connections, etc. An EJB container runs inside (or within) an EJB server, and provides deployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean and its container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJB server which supports the Connector architecture. See Suns J2EE Connectors for more indepth information on Connectors. 11. How is persistence implemented in enterprise beans? - Persistence in EJB is taken care of in two ways, depending on how you implement your beans: container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container. For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being looked up, when the create() method is called on the Home interface, then the container is responsible for calling the ejbCreate() method in the bean, which should have functionality inside for going to the database and looking up the data. 12. What is an EJB Context? - EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details. 13. Is method overloading allowed in EJB? - Yes you can overload methods 14. Should synchronization primitives be used on bean methods? - No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime. 15. Are we allowed to change the transaction isolation property in middle of a transaction? - No. You cannot change the transaction isolation level in the middle of transaction. 16. For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the bean is passivated? - The specification infers that the container never serializes an instance of an Entity bean (unlike stateful session beans). Thus passivation simply involves moving the bean from the ready to the pooled bin. So what happens to the contents of an instance variable is controlled by the programmer. Remember that when an entity bean is passivated the instance gets logically disassociated from its remote object. Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior to reuse or for dereference. 17. What is a Message Driven Bean, what functions does a message driven bean have and how do they work in collaboration with JMS? - Message driven beans are the latest addition to the family of component bean types defined by the EJB specification. The original bean types include session beans, which contain business logic and maintain a state associated with client sessions, and entity beans, which map objects to persistent data. Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and session beans, message beans do not have home or remote interfaces. Instead, message driven beans are instantiated by the container as required. Like stateless session beans, message beans maintain no clientspecific state, allowing the container to optimally manage a pool of message-bean instances. Clients send JMS messages to message beans in exactly the same manner as they would send messages to any other JMS destination. This similarity is a fundamental design goal of the JMS

capabilities of the new specification. To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, which defines a single onMessage() method. When a message arrives, the container ensures that a message bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the clients message as the single argument. The message beans implementation of this method contains the business logic required to process the message. Note that session beans and entity beans are not allowed to function as message beans. 18. Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in the same way as RMI does across a JRMP connection? - Yes. The JDK 1.2 support the dynamic class loading. 19. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer. 20. What is the advantage of putting an Entity Bean instance from the Ready State to Pooled state? - The idea of the Pooled State is to allow a container to maintain a pool of entity beans that has been created, but has not been yet synchronized or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using an entity bean of a particular type there is no need for cachig it (the data is persisted in the database). Therefore, in such cases, the container will, after some time, move the entity bean from the Ready State to the Pooled state to save memory. Then, to save additional memory, the container may begin moving entity beans from the Pooled State to the Does Not Exist State, because even though the beans cache has been cleared, the bean still takes up some memory just being in the Pooled State. 21. Can a Session Bean be defined without ejbCreate() method? - The ejbCreate() methods is part of the beans lifecycle, so, the compiler will not return an error because there is no ejbCreate() method. However, the J2EE spec is explicit: the home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments. Stateful Session Beans can have arguments (more than one create method) stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition. You need a reference to your EJBObject to startwith. For that Sun insists on putting a method for creating that reference (create method in the home interface). The EJBObject does matter here. Not the actual bean. 22. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? - You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as passed-by-value, that means that its read-only in the EJB. If anything is altered from inside the EJB, it wont be reflected back to the HttpSession of the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice (1) in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejbs api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-httpbased client. This higher level of abstraction will be flexible enough to support it. (1) Core J2EE design patterns (2001) 23. Is there any way to read values from an entity bean without locking it for the rest of the transaction (e.g. read-only transactions)? We have a key-value map bean which

deadlocks during some concurrent reads. Isolation levels seem to affect the database only, and we need to work within a transaction. - The only thing that comes to (my) mind is that you could write a group accessor - a method that returns a single object containing all of your entity beans attributes (or all interesting attributes). This method could then be placed in a Requires New transaction. This way, the current transaction would be suspended for the duration of the call to the entity bean and the entity beans fetch/operate/commit cycle will be in a separate transaction and any locks should be released immediately. Depending on the granularity of what you need to pull out of the map, the group accessor might be overkill. 24. What is the difference between a Coarse Grained Entity Bean and a Fine Grained Entity Bean? - A fine grained entity bean is pretty much directly mapped to one relational table, in third normal form. A coarse grained entity bean is larger and more complex, either because its attributes include values or lists from other tables, or because it owns one or more sets of dependent objects. Note that the coarse grained bean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with data copied from other tables, repeated field groups, columns that are dependent on non-key fields, etc. Fine grained entities are generally considered a liability in large systems because they will tend to increase the load on several of the EJB servers subsystems (there will be more objects exported through the distribution layer, more objects participating in transactions, more skeletons in memory, more EJB Objects in memory, etc.) 25. What is EJBDoclet? - EJBDoclet is an open source JavaDoc doclet that generates a lot of the EJB related source files from custom JavaDoc comments tags embedded in the EJB source file. Question: What is J2EE? Answer: J2EE Stands for Java 2 Enterprise Edition. J2EE is an environment for developing and deploying enterprise applications. J2EE specification is defined by Sun Microsystems Inc. The J2EE platform is one of the best platform for the development and deployment of enterprise applications. The J2EE platform is consists of a set of services, application programming interfaces (APIs), and protocols, which provides the functionality necessary for developing multi-tiered, web-based applications. You can download the J2EE SDK and development tools from http://java.sun.com/.

Question: What do you understand by a J2EE module? Answer: A J2EE module is a software unit that consists of one or more J2EE components of the same container type along with one deployment descriptor of that type. J2EE specification defines four types of modules: a) EJB b) Web c) application client and d) resource adapter In the J2EE applications modules can be deployed as stand-alone units. Modules can also be assembled into J2EE applications.

Question: Tell me something about J2EE component? Answer: J2EE component is a self-contained functional software unit supported by a container and configurable at deployment time. The J2EE specification defines the following J2EE components:

Application clients and applets are components that run on the client. Java servlet and JavaServer Pages (JSP) technology components are Web components that run on the server.

Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server. J2EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between J2EE components and "standard" Java classes is that J2EE components are assembled into a J2EE application, verified to be well formed and in compliance with the J2EE specification, and deployed to production, where they are run and managed by the J2EE server or client container. Source: J2EE v1.4 Glossary

Question: What are the contents of web module? Answer: A web module may contain: a) JSP files b) Java classes c) gif and html files and d) web component deployment descriptors

Question: Differentiate between .ear, .jar and .war files. Answer: These files are simply zipped file using java jar tool. These files are created for different purposes. Here is the description of these files: .jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources and accessories files like property files. .war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other files for necessary for the development of web applications. .ear files: The .ear file contains the EJB modules of the application.

Question: What is the difference between Session Bean and Entity Bean? Answer: Session Bean: Session is one of the EJBs and it represents a single client inside the Application Server. Stateless session is easy to develop and its efficient. As compare to entity beans session beans require few server resources. A session bean is similar to an interactive session and is not shared; it can have only one client, in the same way that an interactive session can have only one user. A session bean is not persistent and it is destroyed once the session terminates. Entity Bean: An entity bean represents persistent global data from the database. Entity beans data are stored into database.

Question: Why J2EE is suitable for the development distributed multi-tiered enterprise applications? Answer: The J2EE platform consists of multi-tiered distributed application model. J2EE applications allows the developers to design and implement the business logic into components according to business requirement. J2EE architecture allows the development of multi-tired applications and the developed applications can be installed on different machines depending on the tier in the multi-tiered J2EE environment . The J2EE application parts are: a) Client-tier components run on the client machine. b) Web-tier components run on the J2EE server. c) Business-tier components run on the J2EE server and the d) Enterprise information system (EIS)-tier software runs on the EIS servers

Question: Why do understand by a container? Answer: Normally, thin-client multi-tiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling,

and other complex low-level details. The component-based and platform-independent J2EE architecture makes J2EE applications easy to write because business logic is organized into reusable components. In addition, the J2EE server provides underlying services in the form of a container for every component type. Because you do not have to develop these services yourself, you are free to concentrate on solving the business problem at hand (Source: http://java.sun.com/j2ee/1.3/docs/tutorial/doc/Overview4.html ). In short containers are the interface between a component and the low-level platform specific functionality that supports the component. The application like Web, enterprise bean, or application client component must be assembled and deployed on the J2EE container before executing.

Question: What are the services provided by a container? Answer: The services provided by container are as follows: a) Transaction management for the bean b) Security for the bean c) Persistence of the bean d) Remote access to the bean e) Lifecycle management of the bean f) Database-connection pooling g) Instance pooling for the bean

Question: What are types of J2EE clients? Answer: J2EE clients are the software that access the services components installed on the J2EE container. Following are the J2EE clients: a) Applets b) Java-Web Start clients c) Wireless clients d) Web applications

Q: What is Jakarta Struts Framework? A: Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications . Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

Q: What is ActionServlet? A: The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

Q: How you will make available any Message Resources Definitions file to the Struts Framework Environment? A: Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag. Example: <message-resources parameter="MessageResources" />

Q: What is Action Class? A: The Action is part of the controller. The purpose of Action Class is to translate the

HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

Q: Write code of any Action Class? A: Here is the code of Action Class that returns the ActionForward object. TestAction.java package roseindia.net; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import import import import org.apache.struts.action.Action; org.apache.struts.action.ActionForm; org.apache.struts.action.ActionForward; org.apache.struts.action.ActionMapping;

public class TestAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ return mapping.findForward("testAction"); } } Q: What is ActionForm? A: An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

Q: What is Struts Validator Framework? A: Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

Q. Give the Details of XML files used in Validator Framework? A: The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

Q. How you will display validation fail errors on jsp page? A: Following tag displays all the errors: <html:errors/>

Q. How you will enable front-end validation based on the xml in validation.xml? A: The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script. Question: What is RequestProcessor and RequestDispatcher? Answer: The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client. The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like The ActionServlet Class The RequestProcessor Class The Action Class The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application. The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows. <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> </servlet> All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> <url-pattern>*.do</url-pattern> A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/actionName.do The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>/do/*</url-pattern> <url-pattern>*.do</url-pattern> A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/do/action_Name The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed. Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the

Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception; The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesnt already exist. The strut framework will create only a single instance of each Action class in your application. Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request. <action> path= "/somerequest" type="com.somepackage.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" redirect="true"/> </action> Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file. <action> path= "/somerequest" type="com.somepackage.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" redirect="true"/> </action> The action forward mappings also can be specified in a global section, independent of any specific action mapping. <global-forwards> <forward name="Success" path="/action/somejsp.jsp" /> <forward name="Failure" path="/someotherjsp.jsp" /> </global-forwards> public interface RequestDispatcher Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource. getRequestDispatcher public RequestDispatcher getRequestDispatcher(java.lang.String path)

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static. The pathname must begin with a "/" and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher. Parameters: path - a String specifying the pathname to the resource Returns: a RequestDispatcher object that acts as a wrapper for the resource at the specified path See Also: RequestDispatcher, getContext(java.lang.String) getNamedDispatcher public RequestDispatcher getNamedDispatcher(java.lang.String name) Returns a RequestDispatcher object that acts as a wrapper for the named servlet. Servlets (and JSP pages also) may be given names via server administration or via a web application deployment descriptor. A servlet instance can determine its name using ServletConfig.getServletName(). This method returns null if the ServletContext cannot return a RequestDispatcher for any reason. Parameters: name - a String specifying the name of a servlet to wrap Returns: a RequestDispatcher object that acts as a wrapper for the named servlet See Also: RequestDispatcher, getContext(java.lang.String), ServletConfig.getServletName() Question: Can I setup Apache Struts to use multiple configuration files? Answer: Yes Struts can use multiple configuration files. Here is the configuration example: <servlet> <servlet-name>banking</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet </servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml, /WEB-INF/struts-authentication.xml, /WEB-INF/struts-help.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>

Question: What are the disadvantages of Struts? Answer: Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts: a) High Learning Curve Struts requires lot of efforts to learn and master it. For any small project less experience developers could spend more time on learning the Struts.

b) Harder to learn Struts are harder to learn, benchmark and optimize. Question: What is Struts Flow? Answer: Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow, like multiform wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. (Ref: http://struts.sourceforge.net/strutsflow/index.html ) Question: What are the difference between <bean:message> and <bean:write>? Answer: <bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle. <bean:write>: This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables the programmers to easily present the data. Question: What is LookupDispatchAction? Answer: An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. (Ref. http://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.html). Question: What are the components of Struts? Answer: Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller. Model: Components like business logic / business processes and data are the part of Model. View: JSP, HTML etc. are part of View Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests. Question: What are Tag Libraries provided with Struts? Answer: Struts provides a number of tag libraries that helps to create view components easily. These tag libraries are: a) Bean Tags: Bean Tags are used to access the beans and their properties. b) HTML Tags: HTML Tags provides tags for creating the view components like forms, buttons, etc.. c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets. d) Nested Tags: Nested Tags helps to work with the nested context. Question: What are the core classes of the Struts Framework? Answer: Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc. Question: What are difference between ActionErrors and ActionMessage? Answer: ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property. Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message. ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form). Question: How you will handle exceptions in Struts? Answer: In Struts you can handle the exceptions in two ways:

a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag. Example: <exception key="database.error.duplicate" path="/UserExists.jsp" type="mybank.account.DuplicateUserException"/> b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.

Question: What do you understand by JSP Actions? Answer: JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.

There are six JSP Actions: <jsp:include/> <jsp:forward/> <jsp:plugin/> <jsp:usebean/> <jsp:setProperty/> <jsp:getProperty/>

Question: What is the difference between <jsp:include page = ... > and <%@ include file = ... >?. Answer: Both the tag includes the information from one page in another. The differences are as follows: <jsp:include page = ... >: This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful to for modularizing the web application. If the included file changed then the new content will be included in the output. <%@ include file = ... >: In this case the content of the included file is textually embedded in the page that have <%@ include file=".."> directive. In this case in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.

Question: What is the difference between <jsp:forward page = ... > and response.sendRedirect(url),?. Answer: The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect kills the session variables.

Question: Identify the advantages of JSP over Servlet. a) Embedding of Java code in HTML pages b) Platform independence c) Creation of database-driven Web applications d) Server-side programming capabilities Answer :- Embedding of Java code in HTML pages

Write the following code for a JSP page: <%@ page language = "java" %> <HTML> <HEAD><TITLE>RESULT PAGE</TITLE></HEAD> <BODY> <% PrintWriter print = request.getWriter(); print.println("Welcome"); %> </BODY> </HTML> Suppose you access this JSP file, Find out your answer. a) A blank page will be displayed. b) A page with the text Welcome is displayed c) An exception will be thrown because the implicit out object is not used d) An exception will be thrown because PrintWriter can be used in servlets only Answer :- A page with the text Welcome is displayed

Question: What are implicit Objects available to the JSP Page? Answer: Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are: Description The context for the JSP page's servlet and any Web components application javax.servlet.ServletContext contained in the same application. config javax.servlet.ServletConfig Initialization information for the JSP page's servlet. exception java.lang.Throwable Accessible only from an error page. out javax.servlet.jsp.JspWriter The output stream. The instance of the JSP page's servlet processing the current page java.lang.Object request. Not typically used by JSP page authors. The context for the JSP page. Provides a single API to manage pageContext javax.servlet.jsp.PageContext the various scoped attributes. request Subtype of The request triggering the execution of the JSP page. Variable Class

response session

javax.servlet.ServletRequest Subtype of The response to be returned to the client. Not typically used by javax.servlet.ServletResponse JSP page authors. javax.servlet.http.HttpSession The session object for the client.

Question: What are all the different scope values for the <jsp:useBean> tag? Answer:<jsp:useBean> tag is used to use any java object in the jsp page. Here are the scope values for <jsp:useBean> tag: a) page b) request c) session and d) application

Question: What is JSP Output Comments? Answer: JSP Output Comments are the comments that can be viewed in the HTML source file. Example: <!-- This file displays the user login screen --> and <!-- This page was loaded on <%= (new java.util.Date()).toLocaleString() %> -->

Question: What is expression in JSP? Answer: Expression tag is used to insert Java values directly into the output. Syntax for the Expression tag is: <%= expression %> An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. The following expression tag displays time on the output: <%=new java.util.Date()%>

Question: What types of comments are available in the JSP? Answer: There are two types of comments are allowed in the JSP. These are hidden and output comments. A hidden comments does not appear in the generated output in the html, while output comments appear in the generated output. Example of hidden comment: <%-- This is hidden comment --%> Example of output comment: <!-- This is output comment -->

Question: What is JSP declaration? Answer: JSP Decleratives are the JSP tag used to declare variables. Declaratives are enclosed in the < %! %> tag and ends in semi-colon. You declare variables and functions in the declaration tag and can use anywhere in the JSP. Here is the example of declaratives: <%@page contentType="text/html" %> <html> <body>

<%! int cnt=0; private int getCount(){ //increment cnt and return the value cnt++; return cnt; } %> <p>Values of Cnt are:</p> <p><%=getCount()%></p> </body> </html>

Question: What is JSP Scriptlet? Answer: JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked. Example: <% //java codes String userName=null; userName=request.getParameter("userName"); %>

Question: What are the life-cycle methods of JSP? Answer: Life-cycle methods of the JSP are: a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance. b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden. c) jspDestroy(): The container calls this when its instance is about to destroyed. The jspInit() and jspDestroy() methods can be overridden within a JSP page. Question: What is JSP Custom tags? Answer: JSP Custom tags are user defined JSP language element. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tag for encapsulate both simple and complex behaviors in an easy to use syntax and greatly simplify the readability of JSP pages.

Question: What is JSP? Answer: JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers Question: What is the role of JSP in MVC Model? Answer: JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.

Question: What do you understand by context initialization parameters? Answer: The context-param element contains the declaration of a web application's servlet context initialization parameters. <context-param> <param-name>name</param-name> <param-value>value</param-value> </context-param> The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods. Question: Can you extend JSP technology? Answer: JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions and tag libraries can be developed. Question: What do you understand by JSP translation? Answer: JSP translators generate standard Java code for a JSP page implementation class. This class is essentially a servlet class wrapped with features for JSP functionality. Question: What you can stop the browser to cash your page? Answer: Instead of deleting a cache, you can force the browser not to catch the page. <% response.setHeader("pragma","no-cache");//HTTP 1.1 response.setHeader("Cache-Control","no-cache"); response.setHeader("Cache-Control","no-store"); response.addDateHeader("Expires", -1); response.setDateHeader("max-age", 0); //response.setIntHeader ("Expires", -1); //prevents caching at the proxy server response.addHeader("cache-Control", "private"); %> put the above code in your page. Question: What you will handle the runtime exception in your jsp page? Answer: The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page. For example: <%@ page errorPage="customerror.jsp" %> above code forwards the request to "customerror.jsp" page if an uncaught exception is encountered during request processing. Within "customerror.jsp", you must indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %>.

Collection of large number of Servlet Interview Questions. These questions are frequently asked in the Java Interviews. Question: What is a Servlet? Answer: Java Servlets are server side components that provides a powerful mechanism for developing server side of web application . Earlier CGI was developed to provide server side capabilities to the web applications. Although CGI played a major role in the explosion of the Internet, its performance

, scalability and reusability issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun's write once run anywhere technology java servlets provide excellent framework for server side processing. Question: What are the types of Servlet? Answer: There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality linke doGet and doPost methods. Question: What are the differences between HttpServlet and Generic Servlets? Answer: HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

doGet, if the servlet supports HTTP GET requests doPost, for HTTP POST requests doPut , for HTTP PUT requests doDelete, for HTTP DELETE requests init and destroy, to manage resources that are held for the life of the servlet getServletInfo, which the servlet uses to provide information about itself

There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). Likewise, there's almost no reason to override the doOptions and doTrace methods. GenericServlet defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead. GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it's more common to extend a protocol-specific subclass such as HttpServlet. GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface. To write a generic servlet, you need only override the abstract service method. Question: Differentiate between Servlet and Applet. Answer: Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser. Applets have GUI interface but there is not GUI interface in case of Servlets. Question: Differentiate between doGet and doPost method? Answer: doGet is used when there is are requirement of sending data appended to a query string in the URL. The doGet models the GET method of Http and it is used to retrieve the info on the client from some server as a request to it. The doGet cannot be used to send too much info appended as a query stream. GET puts the form values into the URL string. GET is limited to about 256 characters (usually a browser limitation) and creates really ugly URLs. POST allows you to have extremely dense forms and pass that to the server without clutter or limitation in size. e.g. you obviously can't send a file from the client to the server via GET. POST has no limit on the amount of data you can send and because the data does not show up on the URL you can send passwords. But this does not mean that POST is truly secure. For real security you have to look into encryption which is an entirely different topic

Question: What are methods of HttpServlet? Answer: The methods of HttpServlet class are : * doGet() is used to handle the GET, conditional GET, and HEAD requests * doPost() is used to handle POST requests * doPut() is used to handle PUT requests * doDelete() is used to handle DELETE requests * doOptions() is used to handle the OPTIONS requests and * doTrace() is used to handle the TRACE requests Question: What are the advantages of Servlets over CGI programs? Answer: Question: What are methods of HttpServlet? Answer: Java Servlets have a number of advantages over CGI and other API's. They are:

1. Platform Independence
Java Servlets are 100% pure Java, so it is platform independence. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server (if Apache Serve is installed) without modification or compilation of code. Platform independency of servlets provide a great advantages over alternatives of servlets.

2. Performance
Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place very first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request. This intuitive method of servlets could be use to develop high speed data driven web sites. Extensibility Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions. Safety Java provides a very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension. Secure Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager. Question: What are the lifecycle methods of Servlet? Answer: The interface javax.servlet.Servlet, defines the three life-cycle methods. These are: public void init(ServletConfig config) throws ServletException public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy() The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps. 1. If an instance of the servlet does not exist, the web container * Loads the servlet class. * Creates an instance of the servlet class. * Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet. 2. The container invokes the service method, passing request and response objects. 3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.

3.

4. 5. 6.

7. Question: What are the type of protocols supported by HttpServlet?


Answer: It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol. 8. Question: What are the directory Structure of Web Application? Answer: Web component follows the standard directory structure defined in the J2EE specification. Directory Structure of Web Component / index.htm, JSP, Images etc Web-inf web.xml classes servlet classes lib jar files 9. Question: What is ServletContext? Answer: ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.) 10. Question: What is meant by Pre-initialization of Servlet? Answer: When servlet container is loaded, all the servlets defined in the web.xml file does not initialized by default. But the container receives the request it loads the servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In case of Pre-initialization, the servlet is loaded when context is loaded. You can specify <load-on-startup>1</load-on-startup> in between the <servlet></servlet> tag. 11. Question: What mechanisms are used by a Servlet Container to maintain session information? Answer: Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session. 12. Question: What do you understand by servlet mapping? Answer: Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet. 13. Question: What must be implemented by all Servlets? Answer: The Servlet Interface must be implemented by all servlets. 14. Question: What are the differences between Servlet and Applet? Answer: Servlets are server side components that runs on the Servlet container. Applets are client side components and runs on the web browsers. Servlets have no GUI interface. 15. Question: What are the uses of Servlets? Answer: * Servlets are used to process the client request. * A Servlet can handle multiple request concurrently and be used to develop high performance system * A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request. 16. Question: What are the objects that are received when a servlets accepts call from client? Answer: The objects are ServeltRequest and ServletResponse . The ServeltRequest encapsulates the communication from the client to the server. While ServletResponse encapsulates the communication from the Servlet back to the client.

Das könnte Ihnen auch gefallen