imp j 2 ee questions

Upload: sandeepkodan

Post on 05-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Imp j 2 Ee Questions

    1/26

  • 7/31/2019 Imp j 2 Ee Questions

    2/26

    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 Webcontainers. 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 enterprisebeans 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 browserand Java Plugin running on the client together.

    12.How do we package J2EE components? - J2EE components are packaged separately andbundled into a J2EE application for deployment. Each component, its related files such as GIFand HTML files or server-side utility classes, and a deployment descriptor are assembled into amodule and added to the J2EE application. A J2EE application is composed of one or moreenterprise bean,Web, or application client component modules. The final enterprise solutioncan use one J2EE application or be made up of two or more J2EE applications, depending ondesign requirements. A J2EE application and each of its modules has its own deploymentdescriptor. A deployment descriptor is an XML document with an .xml extension that describesa components deployment settings.

    13.What is a thin client? - A thin client is a lightweight interface to the application that does nothave such operations like query databases, execute complex business rules, or connect tolegacy applications.

    14.What are types of J2EE clients? - Following are the types of J2EE clients:

    o Applets

    o Application clients

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

    4. What is deployment descriptor? - A deployment descriptor is an Extensible MarkupLanguage (XML) text-based file with an .xml extension that describes a componentsdeployment settings. A J2EE application and each of its modules has its own deploymentdescriptor. For example, an enterprise bean module deployment descriptor declarestransaction attributes and security authorizationsfor an enterprise bean. Because deployment descriptor information is declarative, it can bechanged without modifying the bean source code. At run time, the J2EE server reads thedeployment descriptor and acts upon the component accordingly.

    5. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named fromEnterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.

    6. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is theabbreviation for the Jave Transaction Service. JTA provides a standard interface and allows youto demarcate transactions in a manner that is independent of the transaction managerimplementation. The J2EE SDK implements the transaction manager with JTS. But your codedoesnt call the JTS methods directly. Instead, it invokes the JTA methods, which then call thelower-level JTS routines. Therefore, JTA is a high level transaction interface that yourapplication uses to control transaction. and JTS is a low level transaction interface and ejb usesbehind the scenes (client code doesnt directly interact with JTS. It is based on objecttransaction service(OTS) which is part of CORBA.

    7. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing anddescribing text-based data which can be read and handled by any program or tool that usesXML 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 appropriateJavaBeans component to perform those operations.

    8. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and systemintegrators to create resource adapters that support access to enterprise information systemsthat can be plugged into any J2EE product. Each type of database or EIS has a differentresource adapter. Note: A resource adapter is a software component that allows J2EE

  • 7/31/2019 Imp j 2 Ee Questions

    3/26

    application components to access and interact with the underlying resource manager. Becausea resource adapter is specific to its resource manager, there is typically a different resourceadapter for each type of database or enterprise information system.

    9. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for aJ2EE application to authenticate and authorize a specific user or group of users to run it. It is astandard Pluggable Authentication Module (PAM) framework that extends the Java 2 platformsecurity architecture to support user-based authorization.

    10.What is Java Naming and Directory Service? - The JNDI provides naming and directoryfunctionality. It provides applications with methods for performing standard directoryoperations, such as associating attributes with objects and searching for objects using theirattributes. 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 toaccess multiple naming and directory services, including existing naming anddirectory services such as LDAP, NDS, DNS, and NIS.

    11.What is Struts? - A Web page development framework. Struts combines Java Servlets, JavaServer Pages, custom tags, and message resources into a unified framework. It is acooperative, 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 anappropriate 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 applicationsbusiness logic or state. Control is usually then forwarded back through the Controller to theappropriate View. The forwarding can be determined by consulting a set of mappings, usuallyloaded from a database or configuration file. This provides a loose coupling between the Viewand 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 thescreen, a JSP page and presentation components; Model: System state and a business logicJavaBeans.

    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 Strutsis robust architecture and can be used for the development of application of any size. Strutsframework makes it much easier to design scalable, reliable Web applications with Java.

    2. What is ActionServlet? - The class org.apache.struts.action.ActionServlet is the calledthe ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. Allthe requests to the server goes through the controller. Controller is responsible for handling allthe requests.

    3. How you will make available any Message Resources Definitions file to the StrutsFramework Environment? - Message Resources Definitions file are simple .properties filesand these files contains the messages that can be used in the struts project. MessageResources Definitions files can be added to the struts-config.xml file through tag.Example:

    4. What is Action Class? - The Action Class is part of the Model and is a wrapper around thebusiness logic. The purpose of Action Class is to translate the HttpServletRequest to thebusiness 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 allthe database related stuffs in the Action Class. The ActionServlet (commad) passes theparameterized class to Action Form using the execute() method. The return type of theexecute method is ActionForward which is used by the Struts Framework to forward therequest to the file as per the value of the returned ActionForward object.

    5. Write code of any Action Class? - Here is the code of Action Class that returns theActionForward object.

    6. import javax.servlet.http.HttpServletRequest;7. import javax.servlet.http.HttpServletResponse;

  • 7/31/2019 Imp j 2 Ee Questions

    4/26

    8. import org.apache.struts.action.Action;9. import org.apache.struts.action.ActionForm;10. import org.apache.struts.action.ActionForward;11. import org.apache.struts.action.ActionMapping;12.13. public class TestAction extends Action14. {

    15. public ActionForward execute(16. ActionMapping mapping,17. ActionForm form,18. HttpServletRequest request,19. HttpServletResponse response) throws Exception20. {21. return mapping.findForward(\"testAction\");22. }23. }

    24.What is ActionForm? - An ActionForm is a JavaBean that extendsorg.apache.struts.action.ActionForm. ActionForm maintains the session state for webapplication and the ActionForm object is automatically populated on the server side with dataentered from a form on the client side.

    25.What is Struts Validator Framework? - Struts Framework provides the functionality tovalidate the form data. It can be use to validate the data on the users browser as well as onthe server side. Struts Framework emits the java scripts and it can be used validate the formdata on the client browser. Server side validation of form can be accomplished by sub classingyour From Bean with DynaValidatorForm class. The Validator framework was developed byDavid Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part ofJakarta Commons project and it can be used with or without Struts. The Validator frameworkcomes 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 Frameworkuses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xmldefines the standard validation routines, these are reusable and used in validation.xml. todefine the form specific validations. The validation.xml defines the validations applied to aform bean.

    27.How you will display validation fail errors on jsp page? -The following tag displays allthe errors:

    28.How you will enable front-end validation based on the xml in validation.xml? - The tag to allow front-end validation based on the xml in validation.xml. Forexample the code: generates the client side javascript for the form logonForm as defined in the validation.xml file. The 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 viaJNDI. Return Home Object reference to the client. Create me a new EJB Object through HomeObject interface. Create EJB Object from the Ejb Object. Return EJB Object reference to theclient. Invoke business method using EJB Object reference. Delegate request to Bean(Enterprise Bean).

    2. Is it possible to share an HttpSession between a JSP and EJB? What happens when Ichange a value in the HttpSession from inside an EJB? - You can pass the HttpSession asparameter to an EJB method, only if all objects in session are serializable.This has to be

    http://www.devbistro.com/tech-interview-questions/Java.jsp#tophttp://www.devbistro.com/tech-interview-questions/Java.jsp#top
  • 7/31/2019 Imp j 2 Ee Questions

    5/26

    consider as passed-by-value, that means that its read-only in the EJB. If anything is alteredfrom inside the EJB, it wont be reflected back to the HttpSession of the Servlet Container.Thepass-by-reference can be used between EJBs Remote Interfaces, as they are remotereferences. While it is possible to pass an HttpSession as a parameter to an EJB object, it isconsidered to be bad practice in terms of object-oriented design. This is because you arecreating 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 thatacts as a value object (or structure) that holds all the data you need to pass back and forthbetween front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it.

    3. The EJB container implements the EJBHome and EJBObject classes. For everyrequest from a unique client, does the container create a separate instance of thegenerated EJBHome and EJBObject classes? - The EJB container maintains an instancepool. The container uses these instances for the EJB Home reference irrespective of the clientrequest. while refering the EJB Object classes the container creates a separate instance foreach client request. The instance pool maintenance is up to the implementation of thecontainer. If the container provides one, it is available otherwise it is not mandatory for theprovider to implement it. Having said that, yes most of the container providers implement thepooling functionality to increase the performance of the application server. The way it isimplemented is, again, up to the implementer.

    4. Can the primary key in the entity bean be a Java primitive type such as int? - Theprimary 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 aprimitive).

    5. Can you control when passivation occurs? - The developer, according to the specification,cannot directly control when passivation occurs. Although for Stateful Session Beans, thecontainer cannot passivate an instance that is inside a transaction. So using transactions canbe 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 therequire optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability totune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD -Thepassivation-strategy can be either default or transaction. With the default setting thecontainer will attempt to keep a working set of beans in the cache. With the transactionsetting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).

    6. What is the advantage of using Entity bean for database operations, over directlyusing 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 replacesJDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. InContainer Managed Entity Bean - Whenever the instance of the bean is created the containerautomatically retrieves the data from the DB/Persistance storage and assigns to the objectvariables in bean for user to manipulate or use them. For this the developer needs to map thefields in the database to the variables in deployment descriptor files (which varies for eachvendor). In the Bean Managed Entity Bean - The developer has to specifically makeconnection, retrive values, assign them to the objects in the ejbLoad() which will be called bythe container when it instatiates a bean object. Similarly in the ejbStore() the container savesthe object values back the the persistance storage. ejbLoad and ejbStore are callback methodsand can be only invoked by the container. Apart from this, when you use Entity beans you dontneed to worry about database transaction handling, database connection pooling etc. which

    are taken care by the ejb container.7. 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 findermethods for entity beans with container managed persistenceand is portable across containersand persistence managers. EJB QL is used for queries of two types of finder methods: Findermethods that are defined in the home interface of an entity bean and which return entityobjects. Select methods, which are not exposed to the client, but which are used by the BeanProvider to select persistent values that are maintained by the Persistence Manager or toselect entity objects that are related to the entity bean on which the query is defined.

  • 7/31/2019 Imp j 2 Ee Questions

    6/26

    8. Brief description about local interfaces? - EEJB was originally designed around remoteinvocation using the Java Remote Method Invocation (RMI) mechanism, and later extended tosupport to standard CORBA transport for these calls using RMI/IIOP. This design allowed formaximum flexibility in developing applications without consideration for the deploymentscenario, and was a strong feature in support of a goal of component reuse in J2EE. Manydevelopers are using EJBs locally, that is, some or all of their EJB calls are between beans in asingle 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, toallow streamlined calls to the bean if a caller is in the same container. This does not involvethe overhead involved with RMI like marshalling etc. This facility will thus improve theperformance of applications in which co-location is planned. Local interfaces also provide thefoundation for container-managed relationships among entity beans with container-managedpersistence.

    9. What are the special design care that must be taken when you work with localinterfaces? - It is important to understand that the calling semantics of local interfaces aredifferent from those of remote interfaces. For example, remote interfaces pass parametersusing call-by-value semantics, while local interfaces use call-by-reference. This means that inorder to use local interfaces safely, application developers need to carefully consider potentialdeployment 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 localinterfaces 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 tobe factored into the design decision.

    10.What happens if remove( ) is never invoked on a session bean? - In case of a statelesssession bean it may not matter if we call or not as in both cases nothing is done. The numberof beans in cache is managed by the container. In case of stateful session bean, the bean maybe kept in cache till either the session times out, in which case the bean is removed or whenthere is a requirement for memory in which case the data is cached and the bean is sent tofree 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 instancesmimics the behavior of stateless session EJB instances, which exist only for the duration of aparticular method call. However, message-driven beans are different from stateless sessionEJBs (and other types of EJBs) in several significant ways: Message-driven beans processmultiple JMS messages asynchronously, rather than processing a serialized sequence of

    method calls. Message-driven beans have no home or remote interface, and therefore cannotbe directly accessed by internal or external clients. Clients interact with message-driven beansonly indirectly, by sending a message to a JMS Queue or Topic. Only the container directlyinteracts with a message-driven bean by creating bean instances and passing JMS messages tothose instances as necessary. The Container maintains the entire lifecycle of a message-drivenbean; 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. Itjust works. Use JNDI to locate the Home Interface of the other bean, then acquire an instancereference, 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 EJBContextcalled EntityContext. Session beans use a subclass called SessionContext. These EJBContextobjects provide the bean class with information about its container, the client using the beanand the bean itself. They also provide other functions. See the API docs and the spec for moredetails.

    ^Back to Top

    Java Web development interview questions

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

    http://www.devbistro.com/tech-interview-questions/Java.jsp#tophttp://www.devbistro.com/tech-interview-questions/Java.jsp#top
  • 7/31/2019 Imp j 2 Ee Questions

    7/26

    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 youwont have access to a ServletConfig or ServletContext.

    2. How can a servlet refresh automatically if some new data has entered thedatabase? - 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); intry block will not allow finally code to execute.

    4. How many messaging models do JMS provide for and what are they? - JMS provide fortwo 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 Addressand 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 adriver and register it with the DriverManager. When you have loaded a driver, it is available formaking a connection with a DBMS.

    7. How to Retrieve Warnings? - SQLWarning objects are a subclass of SQLException that dealwith database access warnings. Warnings do not stop the execution of an application, asexceptions do; they simply alert the user that something did not happen as planned. A warningcan be reported on a Connection object, a Statement object (including PreparedStatement andCallableStatement objects), or a ResultSet object. Each of these classes has a getWarningsmethod, 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 threescripting 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 toany shared objects defined at the page level.

    22.What are stored procedures? How is it useful? - A stored procedure is a set ofstatements/commands which reside in the database. The stored procedure is pre-compiled andsaves the database the effort of parsing and compiling sql statements everytime a query isrun. Each database has its own stored procedure language, usually a variant of C with a SQLpreproceesor. 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 toimplement the business logic( A lot of systems still do it). The biggest advantage is of coursespeed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide amechanism to do these manipulations. Stored procs are also useful when you want to do Batchupdates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection maybe significant in these cases.

    23.How do I include static files within a JSP page? - Static resources should always beincluded using the JSP include directive. This way, the inclusion is performed just once duringthe translation phase. Do note that you should always supply a relative URL for the fileattribute. Although you can also include static resources using the action, this is not advisableas 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 andjcomponents.

  • 7/31/2019 Imp j 2 Ee Questions

    8/26

    25.How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe byhaving them implement the SingleThreadModel interface. This is done by adding the directive 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 anEJB? - Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query aclass to obtain information about the declared members that are not otherwise accessible tothe enterprise bean because of the security rules of the Java language.

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

    3. 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 writingcode inside the Session Bean. This is because you are not allowed to access Threads inside anEJB.

    4. What is the default transaction attribute for an EJB? - There is no default transactionattribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a valuefor the transaction attribute for those methods having container managed transaction. InWebLogic, the default transaction attribute for EJB is SUPPORTS.

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

    6. Is there any default cache management system with Entity beans ? In other wordswhether 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 persistentstorage(database). Transactions also play an important role in this scenario. If data is removedfrom the database, via an external application - your Entity Bean can still be alive the EJBcontainer. When the transaction commits, ejbStore() is called and the row will not be found,and the transaction rolled back.

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

    8. Why do we have a remove method in both EJBHome and EJBObject? - With theEJBHome version of the remove, you are able to delete an entity bean without firstinstantiating 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 interfaceversion works on an entity bean that you have already instantiated. In addition, the remoteversion also works on session beans (stateless and stateful) to inform the container of yourloss of interest in this bean.

    9. How can I call one EJB from inside of another EJB? - EJBs can be clients of other EJBs. Itjust works. Use JNDI to locate the Home Interface of the other bean, then acquire an instancereference, and so forth.

    http://www.devbistro.com/tech-interview-questions/Java.jsp#tophttp://www.devbistro.com/tech-interview-questions/Java.jsp#top
  • 7/31/2019 Imp j 2 Ee Questions

    9/26

    10.What is the difference between a Server, a Container, and a Connector? - An EJBserver is an application, usually a product such as BEA WebLogic, that provides (or shouldprovide) for concurrent client connections and manages system resources such as threads,processes, memory, database connections, network connections, etc. An EJB container runsinside (or within) an EJB server, and provides deployed EJB beans with transaction and securitymanagement, etc. The EJB container insulates an EJB bean from the specifics of an underlyingEJB 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 EJBserver which supports the Connector architecture. See Suns J2EE Connectors for more in-depth information on Connectors.

    11.How is persistence implemented in enterprise beans? - Persistence in EJB is taken careof 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 rununder takes care of the persistence of the fields you have declared to be persisted with thedatabase - this declaration is in the deployment descriptor. So, anytime you modify a field in aCMP bean, as soon as the method you have executed is finished, the new data is persisted tothe database by the container. For BMP, the EJB bean developer is responsible for defining thepersistence 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 thedatabase. 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 havefunctionality 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 EJBContextcalled EntityContext. Session beans use a subclass called SessionContext. These EJBContextobjects provide the bean class with information about its container, the client using the beanand the bean itself. They also provide other functions. See the API docs and the spec for moredetails.

    13.Is method overloading allowed in EJB? - Yes you can overload methods14.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 atransaction? - 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 neverserializes an instance of an Entity bean (unlike stateful session beans). Thus passivation simplyinvolves moving the bean from the ready to the pooled bin. So what happens to thecontents of an instance variable is controlled by the programmer. Remember that when anentity bean is passivated the instance gets logically disassociated from its remote object. Becareful here, as the functionality of passivation/activation for Stateless Session, StatefulSession and Entity beans is completely different. For entity beans the ejbPassivate methodnotifies the entity bean that it is being disassociated with a particular entity prior to reuse orfor dereference.

    17.What is a Message Driven Bean, what functions does a message driven bean haveand how do they work in collaboration with JMS? - Message driven beans are the latestaddition 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 stateassociated 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 JMSmessage consumers. A message bean is associated with a JMS topic or queue and receives JMSmessages sent by EJB clients or other beans. Unlike entity beans and session beans, messagebeans do not have home or remote interfaces. Instead, message driven beans are instantiatedby the container as required. Like stateless session beans, message beans maintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances.Clients send JMS messages to message beans in exactly the same manner as they would sendmessages to any other JMS destination. This similarity is a fundamental design goal of the JMS

    http://java.sun.com/j2ee/connector/http://java.sun.com/j2ee/connector/
  • 7/31/2019 Imp j 2 Ee Questions

    10/26

    capabilities of the new specification. To receive JMS messages, message driven beansimplement the javax.jms.MessageListener interface, which defines a single onMessage()method. When a message arrives, the container ensures that a message bean correspondingto the message topic/queue exists (instantiating it if necessary), and calls its onMessagemethod passing the clients message as the single argument. The message beansimplementation 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 anIIOP connection in the same way as RMI does across a JRMP connection? - Yes. TheJDK 1.2 support the dynamic class loading.

    19.The EJB container implements the EJBHome and EJBObject classes. For everyrequest from a unique client, does the container create a separate instance of thegenerated EJBHome and EJBObject classes? - The EJB container maintains an instancepool. The container uses these instances for the EJB Home reference irrespective of the clientrequest. while refering the EJB Object classes the container creates a separate instance foreach client request. The instance pool maintainence is up to the implementation of thecontainer. If the container provides one, it is available otherwise it is not mandatory for theprovider to implement it. Having said that, yes most of the container providers implement thepooling functionality to increase the performance of the application server. The way it isimplemented 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 ofentity beans that has been created, but has not been yet synchronized or assigned to anEJBObject. This mean that the instances do represent entity beans, but they can be used onlyfor serving Home methods (create or findBy), since those methods do not relay on the specificvalues of the bean. All these instances are, in fact, exactly the same, so, they do not havemeaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client isusing an entity bean of a particular type there is no need for cachig it (the data is persisted inthe database). Therefore, in such cases, the container will, after some time, move the entitybean from the Ready State to the Pooled state to save memory. Then, to save additionalmemory, the container may begin moving entity beans from the Pooled State to the DoesNot Exist State, because even though the beans cache has been cleared, the bean still takesup some memory just being in the Pooled State.

    21.Can a Session Bean be defined without ejbCreate() method? - The ejbCreate() methodsis 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 StatelessSession Bean must have a single create() method with no arguments, while the session beanclass must contain exactly one ejbCreate() method, also without arguments. Stateful SessionBeans can have arguments (more than one create method) stateful beans can contain multipleejbCreate() as long as they match with the home interface definition. You need a reference toyour EJBObject to startwith. For that Sun insists on putting a method for creating thatreference (create method in the home interface). The EJBObject does matter here. Not theactual bean.

    22.Is it possible to share an HttpSession between a JSP and EJB? What happens when Ichange a value in the HttpSession from inside an EJB? - You can pass the HttpSession asparameter to an EJB method, only if all objects in session are serializable.This has to beconsider as passed-by-value, that means that its read-only in the EJB. If anything is alteredfrom inside the EJB, it wont be reflected back to the HttpSession of the Servlet Container.Thepass-by-reference can be used between EJBs Remote Interfaces, as they are remotereferences. 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 arecreating 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 thewhole, fat, HttpSession (which carries with it a bunch of http semantics), create a class thatacts as a value object (or structure) that holds all the data you need to pass back and forthbetween front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it. (1) Core J2EEdesign patterns (2001)

    23.Is there any way to read values from an entity bean without locking it for the rest ofthe transaction (e.g. read-only transactions)? We have a key-value map bean which

  • 7/31/2019 Imp j 2 Ee Questions

    11/26

    deadlocks during some concurrent reads. Isolation levels seem to affect thedatabase 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 objectcontaining all of your entity beans attributes (or all interesting attributes). This method couldthen be placed in a Requires New transaction. This way, the current transaction would besuspended for the duration of the call to the entity bean and the entity beansfetch/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 groupaccessor might be overkill.

    24.What is the difference between a Coarse Grained Entity Bean and a FineGrained Entity Bean? - A fine grained entity bean is pretty much directly mapped to onerelational table, in third normal form. A coarse grained entity bean is larger and morecomplex, either because its attributes include values or lists from other tables, or because itowns one or more sets of dependent objects. Note that the coarse grained bean might bemapped to a single table or flat file, but that single table is going to be pretty ugly, with datacopied 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 willtend to increase the load on several of the EJB servers subsystems (there will be more objectsexported through the distribution layer, more objects participating in transactions, moreskeletons 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 anddeploying enterprise applications. J2EE specification is defined by Sun Microsystems Inc. The J2EEplatform 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), andprotocols, which provides the functionality necessary for developing multi-tiered, web-basedapplications. You can download the J2EE SDK and development tools fromhttp://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 samecontainer type along with one deployment descriptor of that type. J2EE specification defines four typesof modules:a) EJBb) Webc) application client andd) resource adapterIn the J2EE applications modules can be deployed as stand-alone units. Modules can also be assembledinto J2EE applications.

    Question: Tell me something about J2EE component?Answer: J2EE component isa self-contained functional software unit supported by acontainer andconfigurable 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.

    http://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://java.sun.com/http://java.sun.com/http://java.sun.com/j2ee/1.4/docs/glossary.html#88608http://java.sun.com/j2ee/1.4/docs/glossary.html#88608http://java.sun.com/j2ee/1.4/docs/glossary.html#108715http://java.sun.com/j2ee/1.4/docs/glossary.html#88499http://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://java.sun.com/j2ee/1.4/docs/glossary.html#89333http://www.roseindia.net/interview-questions/Interview-Questions/J2EEhttp://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://java.sun.com/http://java.sun.com/j2ee/1.4/docs/glossary.html#88608http://java.sun.com/j2ee/1.4/docs/glossary.html#108715http://java.sun.com/j2ee/1.4/docs/glossary.html#88499http://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://java.sun.com/j2ee/1.4/docs/glossary.html#89333
  • 7/31/2019 Imp j 2 Ee Questions

    12/26

    Enterprise JavaBeans (EJB) components (enterprise beans) are business components that runon the server. J2EE components are written in the Java programming language and arecompiled in the same way as any program in the language. The difference between J2EEcomponents and "standard" Java classes is that J2EE components are assembled into a J2EEapplication, verified to be well formed and in compliance with the J2EE specification, anddeployed to production, where they are run and managed by the J2EE server or clientcontainer.

    Source:J2EE v1.4 Glossary

    Question: What are the contents of web module?Answer: A web module may contain:a) JSP filesb) Java classesc) gif and html files andd) 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 differentpurposes. Here is the description of these files:

    .jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources andaccessories files like property files..war files: These files are with the .war extension. The war file contains the web application that canbe deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other filesfor 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 ApplicationServer. Stateless session is easy to develop and its efficient. As compare to entity beans sessionbeans require few server resources.

    A session bean is similar to an interactive session and is not shared; it can have only one client, in thesame way that an interactive session can have only one user. A session bean is not persistent and it isdestroyed once the session terminates.

    Entity Bean: An entity bean represents persistent global data from the database. Entity beans dataare 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 applicationsallows the developers to design and implement the business logic into components according tobusiness requirement. J2EE architecture allows the development of multi-tired applications and thedeveloped applications can be installed on different machines depending on the tier in the multi-tieredJ2EE 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 thed) 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 manylines of intricate code to handle transaction and state management, multithreading, resource pooling,

    http://java.sun.com/j2ee/1.4/docs/glossary.html#109200http://java.sun.com/j2ee/1.4/docs/glossary.htmlhttp://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://java.sun.com/j2ee/1.4/docs/glossary.html#109200http://java.sun.com/j2ee/1.4/docs/glossary.htmlhttp://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/j2ee-interview-questions.shtml
  • 7/31/2019 Imp j 2 Ee Questions

    13/26

    and other complex low-level details. The component-based and platform-independent J2EEarchitecture makes J2EE applications easy to write because business logic is organized into reusablecomponents. In addition, the J2EE server provides underlying services in the form of a containerfor every component type. Because you do not have to develop these services yourself, you are free toconcentrate 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 specificfunctionality that supports the component. The application like Web, enterprise bean, or applicationclient 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 beanb) Security for the beanc) Persistence of the beand) Remote access to the beane) Lifecycle management of the beanf) Database-connection poolingg) 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 J2EEcontainer. Following are the J2EE clients:a) Appletsb) Java-Web Start clientsc) Wireless clientsd) Web applications

    Q: What is Jakarta Struts Framework?A:Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for thedevelopment 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.ActionServletis the called the ActionServlet. In the the JakartaStruts Framework this class plays the role of controller. All the requests to the server goes through thecontroller. 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 themessages that can be used in the struts project. Message Resources Definitions files can be added tothe struts-config.xml file through tag.Example:

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

    http://java.sun.com/j2ee/1.3/docs/tutorial/doc/Overview4.htmlhttp://java.sun.com/j2ee/1.3/docs/tutorial/doc/Overview4.htmlhttp://www.roseindia.net/interviewquestions/jakartastrutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/jakartastrutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/jakartastrutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/jakartastrutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/strutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/index.shtmlhttp://www.roseindia.net/interviewquestions/corejava.shtmlhttp://java.sun.com/j2ee/1.3/docs/tutorial/doc/Overview4.htmlhttp://www.roseindia.net/interviewquestions/jakartastrutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/jakartastrutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/jakartastrutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/jakartastrutsinterviewquestions.shtml
  • 7/31/2019 Imp j 2 Ee Questions

    14/26

    HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite theexecute() method. The ActionServlet (commad) passes the parameterized class to Action Form usingthe execute() method. There should be no database interactions in the action. The action shouldreceive the request, call business objects (which then handle database, or interface with J2EE, etc) andthen determine where to go next. Even better, the business objects could be handed to the action atruntime (IoC style) thus removing any dependencies on the model. The return type of the executemethod 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 theActionForward object.TestAction.java

    package roseindia.net;

    importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;

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

    public classTestAction 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. ActionFormmaintains the session state for web application and the ActionForm object is automatically populatedon 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 thedata on the users browser as well as on the server side. Struts Framework emits the java scripts and itcan be used validate the form data on the client browser. Server side validation of form can beaccomplished 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 doingany 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 andvalidation.xml . The validator-rules.xml defines the standard validation routines, these are reusableand used in validation.xml . to define the form specific validations. The validation.xml defines thevalidations applied to a form bean.

  • 7/31/2019 Imp j 2 Ee Questions

    15/26

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

    Q. How you will enable front-end validation based on the xml in validation.xml?A:The tag to allow front-end validation based on the xml in validation.xml. For

    example the code: generates the client side java script for the form "logonForm" as defined inthe validation.xml file. The when added in the jsp file generates the client sitevalidation script.

    Question: What is RequestProcessor and RequestDispatcher?Answer: The controller is responsible for intercepting and translating user input into actions to beperformed by the model. The controller is responsible for selecting the next view based on user inputand the outcome of model operations. The Controller receives the request from the browser, invoke abusiness 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 differentcomponents likeThe ActionServlet ClassThe RequestProcessor ClassThe Action Class

    The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is notabstract 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 thecentral controller in the deployment descriptor as follows.

    actionorg.apache.struts.action.ActionServlet

    All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor asfollows.

    action

    *.do*.do

    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 mappingwhere a pattern ends with /* as shown below.

    action/do/*

    *.doA request URI that matches this pattern will have the following form.http://www.my_site_name.com/mycontext/do/action_NameThe class org.apache.struts.action.requestProcessor process the request from the controller. Youcan 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

    http://www.roseindia.net/interviewquestions/strutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/strutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/strutsinterviewquestions.shtmlhttp://www.roseindia.net/interviewquestions/strutsinterviewquestions.shtml
  • 7/31/2019 Imp j 2 Ee Questions

    16/26

    Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as abridge between a client-side user action and business operation. The Action class decouples the clientrequest from the business model. This decoupling allows for more than one-to-one mapping betweenthe user request and an action. The Action class also can perform other functions such asauthorization, logging before invoking business operation. the Struts Action class contains severalmethods, but most important method is the execute() method.public ActionForward execute(ActionMapping mapping,

    ActionForm form, HttpServletRequest request, HttpServletResponse response) throwsException;The execute() method is called by the controller when a request is received from a client. Thecontroller creates an instance of the Action class if one doesnt already exist. The strut framework willcreate 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 atstartup and made available to the framework at runtime. Each Action element is represented inmemory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMappingobject contains a path attribute that is matched against a portion of the URI of the incoming request.

    path= "/somerequest"type="com.somepackage.someAction"scope="request"name="someForm"

    validate="true"input="somejsp.jsp"

    Once this is done the controller should determine which view to return to the client. The executemethod signature in Action class has a return type org.apache.struts.action.ActionForward class. TheActionForward class represents a destination to which the controller may send control once an actionhas completed. Instead of specifying an actual JSP page in the code, you can declaratively associate asaction forward through out the application. The action forward are specified in the configuration file.

    path= "/somerequest"type="com.somepackage.someAction"scope="request"

    name="someForm"validate="true"input="somejsp.jsp"

    The action forward mappings also can be specified in a global section, independent of any specificaction mapping.

    public interface RequestDispatcher

    Defines an object that receives requests from the client and sends them to any resource (such as aservlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcherobject, which is used as a wrapper around a server resource located at a particular path or given by aparticular name.This interface is intended to wrap servlets, but a servlet container can create RequestDispatcherobjects to wrap any type of resource.

    getRequestDispatcher

    public RequestDispatcher getRequestDispatcher(java.lang.String path)

  • 7/31/2019 Imp j 2 Ee Questions

    17/26

    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 theresource 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. UsegetContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null ifthe 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 applicationdeployment 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:

    banking

    org.apache.struts.action.ActionServletconfig/WEB-INF/struts-config.xml,

    /WEB-INF/struts-authentication.xml,/WEB-INF/struts-help.xml

    1

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

    http://www.roseindia.net/interview-questions/Interview-Questions/J2EE
  • 7/31/2019 Imp j 2 Ee Questions

    18/26

    b) Harder to learnStruts 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 multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the abilityto describe the order ofWeb 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 theControl Flow could be extracted from Cocoon. (Ref: http://struts.sourceforge.net/struts-flow/index.html )

    Question: What are the difference between and ?Answer:: This tag is used to output locale-specific text (from the properties files)from a MessageResources bundle.

    : This tag is used to output property values from a bean. is a commonlyused 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 incases 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 ViewController: Action Servlet of Struts is part of Controller components which works as front controller tohandle 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. Thesetag 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 theyare specific to a particular bean property.Each individual message is described by an ActionMessage object, which contains a message key (tobe looked up in an appropriate message resources database), and up to four placeholder argumentsused for parametric substitution in the resulting message.

    ActionErrors: A class that encapsulates the error messages being reported by the validate() methodof an ActionForm. Validation errors are either global to the entire ActionForm bean they are associatedwith, or they are specific to a particular bean property (and, therefore, a particular input field on thecorresponding form).

    Question: How you will handle exceptions in Struts?Answer: In Struts you can handle the exceptions in two ways:

    http://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://struts.sourceforge.net/struts-flow/index.htmlhttp://struts.sourceforge.net/struts-flow/index.htmlhttp://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.htmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://struts.sourceforge.net/struts-flow/index.htmlhttp://struts.sourceforge.net/struts-flow/index.htmlhttp://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.htmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtml
  • 7/31/2019 Imp j 2 Ee Questions

    19/26

    a) Declarative Exception Handling:You can either define global exception handling tags in yourstruts-config.xml or define the exception handling tags within .. tag.Example:

    b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle theexception.

    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 acolon, followed by the action name followed by one or more attribute parameters.

    There are six JSP Actions:

    Question: What is the difference between and?.Answer: Both the tag includes the information from one page in another. The differences are asfollows:: This is like a function call from one jsp to another jsp. It is executed ( theincluded 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 webapplication. If the included file changed then the new content will be included in the output.

    : In this case the content of the included file is textually embedded in thepage that have directive. In this case in the included file changes, the changedcontent will not included in the output. This approach is used when the code from one jsp file requiredto include in multiple jsp files.

    http://www.roseindia.net/interviewquestions/jsp-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/index.shtmlhttp://www.roseindia.net/interviewquestions/struts-interviewquestion-1.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions.shtml
  • 7/31/2019 Imp j 2 Ee Questions

    20/26

    Question: What is the difference between andresponse.sendRedirect(url),?.Answer: The element forwards the request object containing the client requestinformation from one JSP file to another file. The target file can be an HTML file, another JSP file, or aservlet, 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 newrequest 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 pagesb) Platform independencec) Creation of database-driven Web applicationsd) Server-side programming capabilities

    Answer :- Embedding of Java code in HTML pages

    Write the following code for a JSP page:

    RESULT PAGESuppose you access this JSP file, Find out your answer.a) A blank page will be displayed.b) A page with the text Welcome is displayedc) An exception will be thrown because the implicit out object is not usedd) 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 Webcontainer and contain information related to a particular request, page, or application. The JSP implicitobjects are:

    Variable Class Description

    application javax.servlet.ServletContextThe context for the JSP page's servlet and any Web components

    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.

    page java.lang.ObjectThe instance of the JSP page's servlet processing the currentrequest. Not typically used by JSP page authors.

    pageContext javax.servlet.jsp.PageContextThe context for the JSP page. Provides a single API to managethe various scoped attributes.

    request Subtype of The request triggering the execution of the JSP page.

    http://www.roseindia.net/interviewquestions/jsp-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions.shtml
  • 7/31/2019 Imp j 2 Ee Questions

    21/26

    javax.servlet.ServletRequest

    responseSubtype ofjavax.servlet.ServletResponse

    The response to be returned to the client. Not typically used byJSP page authors.

    session javax.servlet.http.HttpSession The session object for the client.

    Question: What are all the different scope values for the tag?Answer: tag is used to use any java object in the jsp page. Here are the scope valuesfor tag:a) pageb) requestc) session andd) application

    Question: What is JSP Output Comments?Answer: JSP Output Comments are the comments that can be viewed in the HTML source file.Example:

    and

    Question: What is expression in JSP?Answer: Expression tag is used to insert Java values directly into the output. Syntax for theExpression tag is: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 timeon the output:

    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 outputcomments. A hidden comments does not appear in the generated output in the html, while outputcomments appear in the generated output.Example of hidden comment:Example of 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:

  • 7/31/2019 Imp j 2 Ee Questions

    22/26

    Values of Cnt are:

    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. Java code written inside scriptlet executes every time the JSP isinvoked.Example:

    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 anyother 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 andthe 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 definedtags that can encapsulate common functionality. For example you can write your own tag to accessthe database and performing database operations. You can also write custom tag for encapsulate bothsimple and complex behaviors in an easy to use syntax and greatly simplify the readability of JSPpages.

    Question: What is JSP?Answer: JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamiccontent to web clientsin a portable, secure and well-defined way. The JavaServer Pages specificationextends 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.

    http://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interview-questions/Interview-Questions/J2EEhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtml
  • 7/31/2019 Imp j 2 Ee Questions

    23/26

    Question: What do you understand by context initialization parameters?Answer: The context-param element contains the declaration of a web application's servlet contextinitialization parameters.

    namevalue

    The Context Parameters page lets you manage parameters that are accessed through theServletContext.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 isessentially 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.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 exceptionsautomatically and then forwarded to an error processing page.

    For example:above code forwards the request to "customerror.jsp" page if an uncaught exception is encounteredduring request processing. Within "customerror.jsp", you must indicate that it is an error-processingpage, via the directive: .

    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 developingserver side of web application

    . Earlier CGI was developed to provide server side capabilities to the web applications. Although CGIplayed a major role in the explosion of the Internet,its performance

    http://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/index.shtmlhttp://www.roseindia.net/interviewquestions/index.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/jsp-interview-questions2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/
  • 7/31/2019 Imp j 2 Ee Questions

    24/26

  • 7/31/2019 Imp j 2 Ee Questions

    25/26

    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 IndependenceJava Servlets are 100% pure Java, so it is platform independence. It can run on any Servletenabled 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 (ifApache Serve is installed) without modification or compilation of code. Platform independencyof servlets provide a great advantages over alternatives of servlets.

    2. PerformanceDue to interpreted nature of java, programs written in java are slow. But the java servlets runsvery fast. These are due to the way servlets run on web server. For any program initializationtakes significant amount of time. But in case of servlets initialization takes place very first timeit receives a request and remains in memory till times out or server shut downs. After servlet isloaded, to handle a new request it simply creates a new thread and runs service method ofservlet. In comparison to traditional CGI scripts which creates a new process to serve therequest. This intuitive method of servlets could be use to develop high speed data driven websites.

    3. ExtensibilityJava Servlets are developed in java which is robust, well-designed and object orientedlanguage which can be extended or polymorphed into new objects. So the java servlets takesall these advantages and can be extended from existing class the provide the ideal solutions.

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

    5. SecureServlets are server side components, so it inherits the security provided by the web server.Servlets are also benefited with Java Security Manager.

    6. Question: What are the lifecycle methods of Servlet?Answer: The interfacejavax.servlet.Servlet, defines the three life-cycle methods. Theseare:public void init(ServletConfig config) throws ServletExceptionpublic void service( ServletRequest req, ServletResponse res) throwsServletException, IOExceptionpublic 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 destroymethod.

    http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/
  • 7/31/2019 Imp j 2 Ee Questions

    26/26

    7. Question: What are the type of protocols supported by HttpServlet?Answer: It extends the GenericServlet base class and provides an framework for handling theHTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

    8. Question: What are the directory Structure of WebApplication?Answer: Web component follows the standard directory structure defined in the J2EEspecification.

    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 tocommunicate with its servlet container, for example, to get the MIME type of a file, dispatchrequests, 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 specificsubset 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 notinitialized by default. But the container receives the request it loads the servlet. But in somecases if you want your servlet to be initialized when context is loaded, you have to use aconcept called pre-initialization of Servlet. In case of Pre-initialization, the servlet is loadedwhen context is loaded. You can specify 1in between the 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 tomaintain 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 caseof 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 areclient 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 highperformance system

    * A Servlet can be used to load balance among serveral servers, as Servlet can easilyforward 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 ServeltRequestencapsulates the communication from the client to theserver. While ServletResponse encapsulates the communication from the Servlet back to theclient.

    http://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtml