Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger


Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Sunday, 28 September 2008

J2EE Interview Questions and Answers 2

What is "application client" ?
A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have access to some J2EE platform APIs.

What is "application client container" ?
A container that supports application client components.

What is "application client module" ?
A software unit that consists of one or more classes and an application client deployment descriptor.

What is "application component provider" ?
A vendor that provides the Java classes that implement components' methods, JSP page definitions, and any required deployment descriptors.

What is "application configuration resource file" ?
An XML file used to configure resources for a Java Server Faces application, to define navigation rules for the application, and to register converters, Validator, listeners, renders, and components with the application.

What is "archiving" ?
The process of saving the state of an object and restoring it.

What is "asant" ?
A Java-based build tool that can be extended using Java classes. The configuration files are XML-based, calling out a target tree where various tasks get executed.

What is "attribute"?
A qualifier on an XML tag that provides additional information.

What is authentication ?
The process that verifies the identity of a user, device, or other entity in a computer system, usually as a prerequisite to allowing access to resources in a system. The Java servlet specification requires three types of authentication-basic, form-based, and mutual-and supports digest authentication.

What is authorization ?
The process by which access to a method or resource is determined. Authorization depends on the determination of whether the principal associated with a request through authentication is in a given security role. A security role is a logical grouping of users defined by the person who assembles the application. A deployer maps security roles to security identities. Security identities may be principals or groups in the operational environment.

What is authorization constraint ?
An authorization rule that determines who is permitted to access a Web resource collection.

What is B2B ?
B2B stands for Business-to-business.

What is backing bean ?
A JavaBeans component that corresponds to a JSP page that includes JavaServer Faces components. The backing bean defines properties for the components on the page and methods that perform processing for the component. This processing includes event handling, validation, and processing associated with navigation.

What is basic authentication ?
An authentication mechanism in which a Web server authenticates an entity via a user name and password obtained using the Web application's built-in authentication mechanism.

What is bean-managed persistence ?
The mechanism whereby data transfer between an entity bean's variables and a resource manager is managed by the entity bean.

What is bean-managed transaction ?
A transaction whose boundaries are defined by an enterprise bean.

What is binding (XML) ?
Generating the code needed to process a well-defined portion of XML data.

J2EE Interview Questions and Answers 1

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

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

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 PagesTM (JSPTM) technology components are web components.
Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
Resource adapter components provided by EIS and tool vendors.

What are the four types of J2EE modules?
1. Application client module
2. Web module
3. Enterprise JavaBeans module
4. Resource adapter module

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

What does web module contain?
The web module contains:
--JSP files,
--class files for servlets,
--GIF and HTML files, and
--a Web deployment descriptor.
Web modules are packaged as JAR files with a .war (Web ARchive) extension.

What are the differences between Ear, Jar and War files? Under what circumstances should we use each one?

There are no structural differences between the files; they are all archived using zip-jar compression. However, they are intended for different purposes.
--Jar files (files with a .jar extension) are intended to hold generic libraries of Java classes, resources, auxiliary files, etc.
--War files (files with a .war extension) are intended to contain complete Web applications. In this context, a Web application is defined as a single group of files, classes, resources, .jar files that can be packaged and accessed as one servlet context.
--Ear files (files with a .ear extension) are intended to contain complete enterprise applications. In this context, an enterprise application is defined as a collection of .jar files, resources, classes, and multiple Web applications.
Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc.

What is the difference between Session bean and Entity bean ?
The Session bean and Entity bean are two main parts of EJB container.
Session Bean
--represents a workflow on behalf of a client
--one-to-one logical mapping to a client.
--created and destroyed by a client
--not permanent objects
--lives its EJB container(generally) does not survive system shut down
--two types: stateless and stateful beans
Entity Bean
--represents persistent data and behavior of this data
--can be shared among multiple clients
--persists across multiple invocations
--findable permanent objects
--outlives its EJB container, survives system shutdown
--two types: container managed persistence(CMP) and bean managed persistence(BMP)

What is "applet" ?
A J2EE component that typically executes in a Web browser but can execute in a variety of other applications or devices that support the applet programming model.

What is "applet container" ?
A container that includes support for the applet programming model.

What is "application assembler" ?
A person who combines J2EE components and modules into deployable application units.

J2EE Interview Questions and Answers 3

What is binding (JavaServer Faces technology) ?
Wiring UI components to back-end data sources such as backing bean properties.

What is build file ?
The XML file that contains one or more asant targets. A target is a set of tasks you want to be executed. When starting asant, you can select which targets you want to have executed. When no target is given, the project's default target is executed.

What is business logic ?
The code that implements the functionality of an application. In the Enterprise JavaBeans architecture, this logic is implemented by the methods of an enterprise bean.

What is business method ?
A method of an enterprise bean that implements the business logic or rules of an application.

What is callback methods ?
Component methods called by the container to notify the component of important events in its life cycle.

What is caller ?
Same as caller principal.

What is caller principal ?
The principal that identifies the invoker of the enterprise bean method.

What is cascade delete ?
A deletion that triggers another deletion. A cascade delete can be specified for an entity bean that has container-managed persistence.

What is CDATA ?
A predefined XML tag for character data that means "don't interpret these characters," as opposed to parsed character data (PCDATA), in which the normal rules of XML syntax apply. CDATA sections are typically used to show examples of XML syntax.

What is certificate authority ?
A trusted organization that issues public key certificates and provides identification to the bearer.

What is client-certificate authentication ?
An authentication mechanism that uses HTTP over SSL, in which the server and, optionally, the client authenticate each other with a public key certificate that conforms to a standard that is defined by X.509 Public Key Infrastructure.

What is comment ?
In an XML document, text that is ignored unless the parser is specifically told to recognize it.

What is commit ?
The point in a transaction when all updates to any resources involved in the transaction are made permanent.

What is component contract ?
The contract between a J2EE component and its container. The contract includes life-cycle management of the component, a context interface that the instance uses to obtain various information and services from its container, and a list of services that every container must provide for its components.

What is component-managed sign-on ?
A mechanism whereby security information needed for signing on to a resource is provided by an application component.

What is connector ?
A standard extension mechanism for containers that provides connectivity to enterprise information systems. A connector is specific to an enterprise information system and consists of a resource adapter and application development tools for enterprise information system connectivity. The resource adapter is plugged in to a container through its support for system-level contracts defined in the Connector architecture.

What is container-managed persistence ?
The mechanism whereby data transfer between an entity bean's variables and a resource manager is managed by the entity bean's container.

J2EE Interview Questions and Answers 5

What is deployment descriptor ?
An XML file provided with each module and J2EE application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve.

What is destination ?
A JMS administered object that encapsulates the identity of a JMS queue or topic. See point-to-point messaging system, publish/subscribe messaging system.

What is digest authentication ?
An authentication mechanism in which a Web application authenticates itself to a Web server by sending the server a message digest along with its HTTP request message. The digest is computed by employing a one-way hash algorithm to a concatenation of the HTTP request message and the client's password. The digest is typically much smaller than the HTTP request and doesn't contain the password.

What is distributed application ?
An application made up of distinct components running in separate runtime environments, usually on different platforms connected via a network. Typical distributed applications are two-tier (client-server), three-tier (client-middleware-server), and multitier (client-multiple middleware-multiple servers).

What is document ?
In general, an XML structure in which one or more elements contains text intermixed with subelements.

What is Document Object Model ?
An API for accessing and manipulating XML documents as tree structures. DOM provides platform-neutral, language-neutral interfaces that enables programs and scripts to dynamically access and modify content and structure in XML documents.

What is document root ?
The top-level directory of a WAR. The document root is where JSP pages, client-side classes and archives, and static Web resources are stored.

What is DTD ?
Document type definition. An optional part of the XML document prolog, as specified by the XML standard. The DTD specifies constraints on the valid tags and tag sequences that can be in the document. The DTD has a number of shortcomings, however, and this has led to various schema proposals. For example, the DTD entry says that the XML element called username contains parsed character data-that is, text alone, with no other structural elements under it. The DTD includes both the local subset, defined in the current file, and the external subset, which consists of the definitions contained in external DTD files that are referenced in the local subset using a parameter entity.

What is durable subscription ?
In a JMS publish/subscribe messaging system, a subscription that continues to exist whether or not there is a current active subscriber object. If there is no active subscriber, the JMS provider retains the subscription's messages until they are received by the subscription or until they expire.

What is EAR file ?
Enterprise Archive file. A JAR archive that contains a J2EE application.

What is ebXML ?
Electronic Business XML. A group of specifications designed to enable enterprises to conduct business through the exchange of XML-based messages. It is sponsored by OASIS and the United Nations Centre for the Facilitation of Procedures and Practices in Administration, Commerce and Transport (U.N./CEFACT).

What is EJB ?
Enterprise JavaBeans.

What is EJB container ?
A container that implements the EJB component contract of the J2EE architecture. This contract specifies a runtime environment for enterprise beans that includes security, concurrency, life-cycle management, transactions, deployment, naming, and other services. An EJB container is provided by an EJB or J2EE server.

What is EJB container provider ?
A vendor that supplies an EJB container.

What is EJB context ?
A vendor that supplies an EJB container. An object that allows an enterprise bean to invoke services provided by the container and to obtain the information about the caller of a client-invoked method.

J2EE Interview Questions and Answers 4

What is container-managed sign-on ?
The mechanism whereby security information needed for signing on to a resource is supplied by the container.

What is container-managed transaction ?
A transaction whose boundaries are defined by an EJB container. An entity bean must use container-managed transactions.

What is content ?
In an XML document, the part that occurs after the prolog, including the root element and everything it contains.

What is context attribute ?
An object bound into the context associated with a servlet.

What is context root ?
A name that gets mapped to the document root of a Web application.

What is conversational state ?
The field values of a session bean plus the transitive closure of the objects reachable from the bean's fields. The transitive closure of a bean is defined in terms of the serialization protocol for the Java programming language, that is, the fields that would be stored by serializing the bean instance.

What is CORBA ?
Common Object Request Broker Architecture. A language-independent distributed object model specified by the OMG.

What is create method ?
A method defined in the Interview Questions - Home interface and invoked by a client to create an enterprise bean.

What is credentials ?
The information describing the security attributes of a principal.

What is CSS ?
Cascading style sheet. A stylesheet used with HTML and XML documents to add a style to all elements marked with a particular tag, for the direction of browsers or other presentation mechanisms.

What is CTS ?
Compatibility test suite. A suite of compatibility tests for verifying that a J2EE product complies with the J2EE platform specification.

What is data ?
The contents of an element in an XML stream, generally used when the element does not contain any subelements. When it does, the term content is generally used. When the only text in an XML structure is contained in simple elements and when elements that have subelements have little or no data mixed in, then that structure is often thought of as XML data, as opposed to an XML document.

What is DDP ?
Document-driven programming. The use of XML to define applications.

What is declaration ?
The very first thing in an XML document, which declares it as XML. The minimal declaration is . The declaration is part of the document prolog.

What is declarative security ?
Mechanisms used in an application that are expressed in a declarative syntax in a deployment descriptor.

What is delegation ?
An act whereby one principal authorizes another principal to use its identity or privileges with some restrictions.

What is deployer ?
A person who installs J2EE modules and applications into an operational environment.

What is deployment ?
The process whereby software is installed into an operational environment.

J2EE Interview Questions and Answers 6

What is EJB Home object ?
An object that provides the life-cycle operations (create, remove, find) for an enterprise bean. The class for the EJB Home object is generated by the container's deployment tools. The EJB Home object implements the enterprise bean's Home interface. The client references an EJB Home object to perform life-cycle operations on an EJB object. The client uses JNDI to locate an EJB Home object.

What is EJB JAR file ?
A JAR archive that contains an EJB module.

What is EJB module ?
A deployable unit that consists of one or more enterprise beans and an EJB deployment descriptor.

What is EJB object ?
An object whose class implements the enterprise bean's remote interface. A client never references an enterprise bean instance directly; a client always references an EJB object. The class of an EJB object is generated by a container's deployment tools.

What is EJB server ?
Software that provides services to an EJB container. For example, an EJB container typically relies on a transaction manager that is part of the EJB server to perform the two-phase commit across all the participating resource managers. The J2EE architecture assumes that an EJB container is hosted by an EJB server from the same vendor, so it does not specify the contract between these two entities. An EJB server can host one or more EJB containers.

What is EJB server provider ?
A vendor that supplies an EJB server.

What is element ?
A unit of XML data, delimited by tags. An XML element can enclose other elements.

What is empty tag ?
A tag that does not enclose any content.

What is enterprise bean ?
A J2EE component that implements a business task or business entity and is hosted by an EJB container; either an entity bean, a session bean, or a message-driven bean.

What is enterprise bean provider ?
An application developer who produces enterprise bean classes, remote and Interview Questions - Home interfaces, and deployment descriptor files, and packages them in an EJB JAR file.

What is enterprise information system ?
The applications that constitute an enterprise's existing system for handling companywide information. These applications provide an information infrastructure for an enterprise. An enterprise information system offers a well-defined set of services to its clients. These services are exposed to clients as local or remote interfaces or both. Examples of enterprise information systems include enterprise resource planning systems, mainframe transaction processing systems, and legacy database systems.

What is enterprise information system resource ?
An entity that provides enterprise information system-specific functionality to its clients. Examples are a record or set of records in a database system, a business object in an enterprise resource planning system, and a transaction program in a transaction processing system.

What is Enterprise JavaBeans (EJB) ?
A component architecture for the development and deployment of object-oriented, distributed, enterprise-level applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and secure.

What is Enterprise JavaBeans Query Language (EJB QL) ?
Defines the queries for the finder and select methods of an entity bean having container-managed persistence. A subset of SQL92, EJB QL has extensions that allow navigation over the relationships defined in an entity bean's abstract schema.

What is an entity ?
A distinct, individual item that can be included in an XML document by referencing it. Such an entity reference can name an entity as small as a character (for example, <, which references the less-than symbol or left angle bracket, <). An entity reference can also reference an entire document, an external entity, or a collection of DTD definitions.

J2EE Interview Questions and Answers 7

What is entity bean ?
An enterprise bean that represents persistent data maintained in a database. An entity bean can manage its own persistence or can delegate this function to its container. An entity bean is identified by a primary key. If the container in which an entity bean is hosted crashes, the entity bean, its primary key, and any remote references survive the crash.

What is entity reference ?
A reference to an entity that is substituted for the reference when the XML document is parsed. It can reference a predefined entity such as <>

What is error ?
A SAX parsing error is generally a validation error; in other words, it occurs when an XML document is not valid, although it can also occur if the declaration specifies an XML version that the parser cannot handle. See also fatal error, warning.

What is Extensible Markup Language ?
XML.

What is external entity ?
An entity that exists as an external XML file, which is included in the XML document using an entity reference.

What is external subset ?
That part of a DTD that is defined by references to external DTD files.

What is fatal error ?
A fatal error occurs in the SAX parser when a document is not well formed or otherwise cannot be processed. See also error, warning.

What is filter ?
An object that can transform the header or content (or both) of a request or response. Filters differ from Web components in that they usually do not themselves create responses but rather modify or adapt the requests for a resource, and modify or adapt responses from a resource. A filter should not have any dependencies on a Web resource for which it is acting as a filter so that it can be composable with more than one type of Web resource.

What is filter chain ?
A concatenation of XSLT transformations in which the output of one transformation becomes the input of the next.

What is finder method ?
A method defined in the Interview Questions - Home interface and invoked by a client to locate an entity bean.

What is form-based authentication ?
An authentication mechanism in which a Web container provides an application-specific form for logging in. This form of authentication uses Base64 encoding and can expose user names and passwords

What is general entity ?
An entity that is referenced as part of an XML document's content, as distinct from a parameter entity, which is referenced in the DTD. A general entity can be a parsed entity or an unparsed entity.

What is group ?
An authenticated set of users classified by common traits such as job title or customer profile. Groups are also associated with a set of roles, and every user that is a member of a group inherits all the roles assigned to that group.

What is handle ?
An object that identifies an enterprise bean. A client can serialize the handle and then later deserialize it to obtain a reference to the enterprise bean.

What is Interview Questions - Home handle ?
An object that can be used to obtain a reference to the Interview Questions - Home interface. A Interview Questions - Home handle can be serialized and written to stable storage and de-serialized to obtain the reference.

What is Interview Questions - Home interface ?
One of two interfaces for an enterprise bean. The Interview Questions - Home interface defines zero or more methods for managing an enterprise bean. The Interview Questions - Home interface of a session bean defines create and remove methods, whereas the Interview Questions - Home interface of an entity bean defines create, finder, and remove methods.

J2EE Interview Questions and Answers 8

What is HTML ?
Hypertext Markup Language. A markup language for hypertext documents on the Internet. HTML enables the embedding of images, sounds, video streams, form fields, references to other objects with URLs, and basic text formatting.

What is HTTP ?
Hypertext Transfer Protocol. The Internet protocol used to retrieve hypertext objects from remote hosts. HTTP messages consist of requests from client to server and responses from server to client.

What is HTTPS ?
HTTP layered over the SSL protocol.

What is IDL ?
Interface Definition Language. A language used to define interfaces to remote CORBA objects. The interfaces are independent of operating systems and programming languages.

What is IIOP ?
Internet Inter-ORB Protocol. A protocol used for communication between CORBA object request brokers.

What is impersonation ?
An act whereby one entity assumes the identity and privileges of another entity without restrictions and without any indication visible to the recipients of the impersonator's calls that delegation has taken place. Impersonation is a case of simple delegation.

What is initialization parameter ?
A parameter that initializes the context associated with a servlet.

What is ISO 3166 ?
The international standard for country codes maintained by the International Organization for Standardization (ISO).

What is ISV ?
Independent software vendor.

What is J2EE ?
Java 2 Platform, Enterprise Edition.

What is J2EE application ?
Any deployable unit of J2EE functionality. This can be a single J2EE module or a group of modules packaged into an EAR file along with a J2EE application deployment descriptor. J2EE applications are typically engineered to be distributed across multiple computing tiers.

What is J2EE component ?
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.

What is J2EE module ?
A software unit that consists of one or more J2EE components of the same container type and one deployment descriptor of that type. There are four types of modules: EJB, Web, application client, and resource adapter. Modules can be deployed as stand-alone units or can be assembled into a J2EE application.

What is J2EE product ?
An implementation that conforms to the J2EE platform specification.

What is J2EE product provider ?
A vendor that supplies a J2EE product.

What is J2EE server ?
The runtime portion of a J2EE product. A J2EE server provides EJB or Web containers or both.

J2EE Interview Questions and Answers 9

What is J2ME ?
Abbreviate of Java 2 Platform, Micro Edition.

What is J2SE ?
Abbreviate of Java 2 Platform, Standard Edition.

What is JAR ?
Java archive. A platform-independent file format that permits many files to be aggregated into one file.

What is Java 2 Platform, Enterprise Edition (J2EE) ?
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 is Java 2 Platform, Micro Edition (J2ME) ?
A highly optimized Java runtime environment targeting a wide range of consumer products, including pagers, cellular phones, screen phones, digital set-top boxes, and car navigation systems.

What is Java 2 Platform, Standard Edition (J2SE) ?
The core Java technology platform.

What is Java API for XML Processing (JAXP) ?
An API for processing XML documents. JAXP leverages the parser standards SAX and DOM so that you can choose to parse your data as a stream of events or to build a tree-structured representation of it. JAXP supports the XSLT standard, giving you control over the presentation of the data and enabling you to convert the data to other XML documents or to other formats, such as HTML. JAXP provides namespace support, allowing you to work with schema that might otherwise have naming conflicts.

What is Java API for XML Registries (JAXR) ?
An API for accessing various kinds of XML registries.

What is Java API for XML-based RPC (JAX-RPC) ?
An API for building Web services and clients that use remote procedure calls and XML.

What is Java IDL ?
A technology that provides CORBA interoperability and connectivity capabilities for the J2EE platform. These capabilities enable J2EE applications to invoke operations on remote network services using the Object Management Group IDL and IIOP.

What is Java Message Service (JMS) ?
An API for invoking operations on enterprise messaging systems.

What is Java Naming and Directory Interface (JNDI) ?
An API that provides naming and directory functionality.

What is Java Secure Socket Extension (JSSE) ?
A set of packages that enable secure Internet communications.

What is Java Transaction API (JTA) ?
An API that allows applications and J2EE servers to access transactions.

What is Java Transaction Service (JTS) ?
Specifies the implementation of a transaction manager that supports JTA and implements the Java mapping of the Object Management Group Object Transaction Service 1.1 specification at the level below the API.

What is JavaBeans component ?
A Java class that can be manipulated by tools and composed into applications. A JavaBeans component must adhere to certain property and event interface conventions.

What is JavaMail ?
An API for sending and receiving email.

What is JavaServer Faces Technology ?
A framework for building server-side user interfaces for Web applications written in the Java programming language.

J2EE Interview Questions and Answers 10

What is JavaServer Faces conversion model ?
A mechanism for converting between string-based markup generated by JavaServer Faces UI components and server-side Java objects.

What is JavaServer Faces event and listener model ?
A mechanism for determining how events emitted by JavaServer Faces UI components are handled. This model is based on the JavaBeans component event and listener model.

What is JavaServer Faces expression language ?
A simple expression language used by a JavaServer Faces UI component tag attributes to bind the associated component to a bean property or to bind the associated component's value to a method or an external data source, such as a bean property. Unlike JSP EL expressions, JavaServer Faces EL expressions are evaluated by the JavaServer Faces implementation rather than by the Web container.

What is JavaServer Faces navigation model ?
A mechanism for defining the sequence in which pages in a JavaServer Faces application are displayed.

What is JavaServer Faces UI component ?
A user interface control that outputs data to a client or allows a user to input data to a JavaServer Faces application.

What is JavaServer Faces UI component class ?
A JavaServer Faces class that defines the behavior and properties of a JavaServer Faces UI component.

What is JavaServer Faces validation model ?
A mechanism for validating the data a user inputs to a JavaServer Faces UI component.

What is JavaServer Pages (JSP) ?
An extensible Web technology that uses static data, JSP elements, and server-side Java objects to generate dynamic content for a client. Typically the static data is HTML or XML elements, and in many cases the client is a Web browser.

What is JavaServer Pages Standard Tag Library (JSTL) ?
A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.

What is JAXR client ?
A client program that uses the JAXR API to access a business registry via a JAXR provider.

What is JAXR provider ?
An implementation of the JAXR API that provides access to a specific registry provider or to a class of registry providers that are based on a common specification.

What is JDBC ?
An JDBC for database-independent connectivity between the J2EE platform and a wide range of data sources.

What is JMS ?
Java Message Service.

What is JMS administered object ?
A preconfigured JMS object (a resource manager connection factory or a destination) created by an administrator for the use of JMS clients and placed in a JNDI namespace.

What is JMS application ?
One or more JMS clients that exchange messages.

What is JMS client ?
A Java language program that sends or receives messages.

What is JMS provider ?
A messaging system that implements the Java Message Service as well as other administrative and control functionality needed in a full-featured messaging product.

J2EE Interview Questions and Answers 11

What is JMS session ?
A single-threaded context for sending and receiving JMS messages. A JMS session can be nontransacted, locally transacted, or participating in a distributed transaction.

What is JNDI ?
Abbreviate of Java Naming and Directory Interface.

What is JSP ?
Abbreviate of JavaServer Pages.

What is JSP action ?
A JSP element that can act on implicit objects and other server-side objects or can define new scripting variables. Actions follow the XML syntax for elements, with a start tag, a body, and an end tag; if the body is empty it can also use the empty tag syntax. The tag must use a prefix. There are standard and custom actions.

What is JSP container ?
A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.

What is JSP container, distributed ?
A JSP container that can run a Web application that is tagged as distributable and is spread across multiple Java virtual machines that might be running on different hosts.

What is JSP custom action ?
A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages.

What is JSP custom tag ?
A tag that references a JSP custom action.

What is JSP declaration ?
A JSP scripting element that declares methods, variables, or both in a JSP page.

What is JSP directive ?
A JSP element that gives an instruction to the JSP container and is interpreted at translation time.

What is JSP document ?
A JSP page written in XML syntax and subject to the constraints of XML documents.

What is JSP element ?
A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element.

What is JSP expression ?
A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the implicit out object.

What is JSP expression language ?
A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression.

What is JSP page ?
A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet.

What is JSP scripting element ?
A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose content is written according to the scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute is "java".

What is JSP scriptlet ?
A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is "java".

Friday, 26 September 2008

J2EE Interview Questions and Answers 12

What is JSP standard action ?
An action that is defined in the JSP specification and is always available to a JSP page.

What is JSP tag file ?
A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.

What is JSP tag handler ?
A Java programming language object that implements the behavior of a custom tag.

What is JSP tag library ?
A collection of custom tags described via a tag library descriptor and Java classes.

What is JSTL ?
Abbreviate of JavaServer Pages Standard Tag Library.

What is JTA ?
Abbreviate of Java Transaction API.

What is JTS ?
Abbreviate of Java Transaction Service.

What is keystore ?
A file containing the keys and certificates used for authentication

What is life cycle (J2EE component) ?
The framework events of a J2EE component's existence. Each type of component has defining events that mark its transition into states in which it has varying availability for use. For example, a servlet is created and has its init method called by its container before invocation of its service method by clients or other servlets that require its functionality. After the call of its init method, it has the data and readiness for its intended use. The servlet's destroy method is called by its container before the ending of its existence so that processing associated with winding up can be done and resources can be released. The init and destroy methods in this example are callback methods. Similar considerations apply to the life cycle of all J2EE component types: enterprise beans, Web components (servlets or JSP pages), applets, and application clients.

What is life cycle (JavaServer Faces) ?
A set of phases during which a request for a page is received, a UI component tree representing the page is processed, and a response is produced. During the phases of the life cycle: The local data of the components is updated with the values contained in the request parameters. Events generated by the components are processed. Validators and converters registered on the components are processed. The components' local data is updated to back-end objects. The response is rendered to the client while the component state of the response is saved on the server for future requests.

What is local subset ?
That part of the DTD that is defined within the current XML file.

What is managed bean creation facility ?
A mechanism for defining the characteristics of JavaBeans components used in a JavaServer Faces application.

What is message ?
In the Java Message Service, an asynchronous request, report, or event that is created, sent, and consumed by an enterprise application and not by a human. It contains vital information needed to coordinate enterprise applications, in the form of precisely formatted data that describes specific business actions.

What is message consumer ?
An object created by a JMS session that is used for receiving messages sent to a destination.

What is message-driven bean ?
An enterprise bean that is an asynchronous message consumer. A message-driven bean has no state for a specific client, but its instance variables can contain state across the handling of client messages, including an open database connection and an object reference to an EJB object. A client accesses a message-driven bean by sending messages to the destination for which the bean is a message listener.

What is message producer ?
An object created by a JMS session that is used for sending messages to a destination.

J2EE Interview Questions and Answers 13

What is mixed-content model ?
A DTD specification that defines an element as containing a mixture of text and one more other elements. The specification must start with #PCDATA, followed by diverse elements, and must end with the "zero-or-more" asterisk symbol (*).

What is method-binding expression ?
A Java Server Faces EL expression that refers to a method of a backing bean. This method performs either event handling, validation, or navigation processing for the UI component whose tag uses the method-binding expression.

What is method permission ?
An authorization rule that determines who is permitted to execute one or more enterprise bean methods.

What is mutual authentication ?
An authentication mechanism employed by two parties for the purpose of proving each other's identity to one another.

What is namespace ?
A standard that lets you specify a unique label for the set of element names defined by a DTD. A document using that DTD can be included in any other document without having a conflict between element names. The elements defined in your DTD are then uniquely identified so that, for example, the parser can tell when an element should be interpreted according to your DTD rather than using the definition for an element in a different DTD.

What is naming context ?
A set of associations between unique, atomic, people-friendly identifiers and objects.

What is naming environment ?
A mechanism that allows a component to be customized without the need to access or change the component's source code. A container implements the component's naming environment and provides it to the component as a JNDI naming context. Each component names and accesses its environment entries using the java:comp/env JNDI context. The environment entries are declaratively specified in the component's deployment descriptor.

What is normalization ?
The process of removing redundancy by modularizing, as with subroutines, and of removing superfluous differences by reducing them to a common denominator. For example, line endings from different systems are normalized by reducing them to a single new line, and multiple whitespace characters are normalized to one space.

What is North American Industry Classification System (NAICS) ?
A system for classifying business establishments based on the processes they use to produce goods or services.

What is notation ?
A mechanism for defining a data format for a non-XML document referenced as an unparsed entity. This is a holdover from SGML. A newer standard is to use MIME data types and namespaces to prevent naming conflicts.

What is OASIS ?
Organization for the Advancement of Structured Information Standards. A consortium that drives the development, convergence, and adoption of e-business standards.

What is OMG ?
Object Management Group. A consortium that produces and maintains computer industry specifications for interoperable enterprise applications.

What is one-way messaging ?
A method of transmitting messages without having to block until a response is received.

What is ORB ?
Object request broker. A library that enables CORBA objects to locate and communicate with one another.

What is OS principal ?
A principal native to the operating system on which the J2EE platform is executing.

What is OTS ?
Object Transaction Service. A definition of the interfaces that permit CORBA objects to participate in transactions.

http://www.interviewdoor.com

Wednesday, 24 September 2008

J2EE Interview Questions and Answers 15

What is queue ?
A messaging system built on the concept of message queues. Each message is addressed to a specific queue; clients extract messages from the queues established to hold their messages.

What is RAR ?
Resource Adapter Archive. A JAR archive that contains a resource adapter module.

What is RDF ?
Resource Description Framework. A standard for defining the kind of data that an XML file contains. Such information can help ensure semantic integrity-for example-by helping to make sure that a date is treated as a date rather than simply as text.

What is RDF schema ?
A standard for specifying consistency rules that apply to the specifications contained in an RDF.

What is realm ?
See security policy domain. Also, a string, passed as part of an HTTP request during basic authentication, that defines a protection space. The protected resources on a server can be partitioned into a set of protection spaces, each with its own authentication scheme or authorization database or both. In the J2EE server authentication service, a realm is a complete database of roles, users, and groups that identify valid users of a Web application or a set of Web applications.

What is reentrant entity bean ?
An entity bean that can handle multiple simultaneous, interleaved, or nested invocations that will not interfere with each other.

What is reference ?
A reference to an entity that is substituted for the reference when the XML document is parsed. It can reference a predefined entity such as <>

What is registry ?
An infrastructure that enables the building, deployment, and discovery of Web services. It is a neutral third party that facilitates dynamic and loosely coupled business-to-business (B2B) interactions.

What is registry provider ?
An implementation of a business registry that conforms to a specification for XML registries (for example, ebXML or UDDI).

What is relationship field ?
A virtual field of an entity bean having container-managed persistence; it identifies a related entity bean.

What is remote interface ?
One of two interfaces for an enterprise bean. The remote interface defines the business methods callable by a client.

What is remove method ?
Method defined in the Home interface and invoked by a client to destroy an enterprise bean.

What is render kit ?
A set of renderers that render output to a particular client. The JavaServer Faces implementation provides a standard HTML render kit, which is composed of renderers that can render HMTL markup.

What is renderer ?
A Java class that can render the output for a set of JavaServer Faces UI components.

What is resource adapter ?
A system-level software driver that is used by an EJB container or an application client to connect to an enterprise information system. A resource adapter typically is specific to an enterprise information system. It is available as a library and is used within the address space of the server or client using it. A resource adapter plugs in to a container. The application components deployed on the container then use the client API (exposed by the adapter) or tool-generated high-level abstractions to access the underlying enterprise information system. The resource adapter and EJB container collaborate to provide the underlying mechanisms-transactions, security, and connection pooling-for connectivity to the enterprise information system.

J2EE Interview Questions and Answers 14

What is parameter entity ?
An entity that consists of DTD specifications, as distinct from a general entity. A parameter entity defined in the DTD can then be referenced at other points, thereby eliminating the need to recode the definition at each location it is used.

What is parsed entity ?
A general entity that contains XML and therefore is parsed when inserted into the XML document, as opposed to an unparsed entity.

What is parser ?
A module that reads in XML data from an input source and breaks it into chunks so that your program knows when it is working with a tag, an attribute, or element data. A nonvalidating parser ensures that the XML data is well formed but does not verify that it is valid. See also validating parser.

What is passivation ?
The process of transferring an enterprise bean from memory to secondary storage. See activation.

What is persistence ?
The protocol for transferring the state of an entity bean between its instance variables and an underlying database.

What is persistent field ?
A virtual field of an entity bean that has container-managed persistence; it is stored in a database.

What is POA ?
Portable Object Adapter. A CORBA standard for building server-side applications that are portable across heterogeneous ORBs.

What is point-to-point messaging system ?
A messaging system built on the concept of message queues. Each message is addressed to a specific queue; clients extract messages from the queues established to hold their messages.

What is primary key ?
An object that uniquely identifies an entity bean within a home.

What is principal ?
The identity assigned to a user as a result of authentication.

What is privilege ?
A security attribute that does not have the property of uniqueness and that can be shared by many principals.

What is processing instruction ?
Information contained in an XML structure that is intended to be interpreted by a specific application.

What is programmatic security ?
Security decisions that are made by security-aware applications. Programmatic security is useful when declarative security alone is not sufficient to express the security model of an application.

What is prolog ?
The part of an XML document that precedes the XML data. The prolog includes the declaration and an optional DTD.

What is public key certificate ?
Used in client-certificate authentication to enable the server, and optionally the client, to authenticate each other. The public key certificate is the digital equivalent of a passport. It is issued by a trusted organization, called a certificate authority, and provides identification for the bearer.

What is publish/subscribe messaging system ?
A messaging system in which clients address messages to a specific node in a content hierarchy, called a topic. Publishers and subscribers are generally anonymous and can dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a node's multiple publishers to its multiple subscribers.

What is query string ?
A component of an HTTP request URL that contains a set of parameters and values that affect the handling of the request.

Thursday, 19 June 2008

J2EE interview questions

  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:
    • Client-tier components run on the client machine.
    • Web-tier components run on the J2EE server.
    • Business-tier components run on the J2EE server.
    • Enterprise information system (EIS)-tier software runs on the EIS server.
  2. 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.
  3. What are the components of J2EE application?
    - A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
    1. Application clients and applets are client components.
    2. Java Servlet and JavaServer Pages technology components are web components.
    3. Enterprise JavaBeans components (enterprise beans) are business components.
    4. Resource adapter components provided by EIS and tool vendors.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. What is the container? - Containers are the interface between a component and the low-level 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.
  10. 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.
  11. 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.
  12. 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.
  13. What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.
  14. 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 component’s deployment settings.
  15. 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.
  16. What are types of J2EE clients? - Following are the types of J2EE clients:
    • Applets
    • Application clients
    • Java Web Start-enabled rich clients, powered by Java Web Start technology.
    • Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
  17. What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. 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.
  18. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.
  19. What 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 doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.
  20. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. 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.
  21. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE 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.
  22. 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.
  23. 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.
  24. 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.
  25. How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.

Common JSP interview questions

  1. What are the implicit objects? - Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception.
  2. Is JSP technology extensible? - Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
  3. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? - 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. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the <%! DECLARE %>tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe
  4. How does JSP handle run-time exceptions? - You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %>

    redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
  5. How do I prevent the output of my JSP or Servlet pages from being cached by the browser? - You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.

    <%

    response.setHeader("Cache-Control","no-store"); //HTTP 1.1

    response.setHeader("Pragma","no-cache"); //HTTP 1.0

    response.setDateHeader ("Expires", 0); //prevents caching at the proxy server

    %>

  6. How do I use comments within a JSP page? - You can use “JSP-style” comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example:
    	<%-- the scriptlet is now commented out

    <%

    out.println("Hello World");

    %>

    --%>

    You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

    Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:

    	<%

    //some comment

    /**

    yet another comment

    **/

    %>

  7. Response has already been commited error. What does it mean? - This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type=”text/html” or “text/xml” or “plain-text” or “image/jpg”, etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn’t finished to set up the header. If not starter to set up the header, there are no problems, but if it ’s already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case it’s like you have a file started with some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1
  8. How do I use a scriptlet to initialize a newly instantiated bean? - A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.

    The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.



    value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >

    <%-- scriptlets calling bean setter methods go here --%>



  9. How can I enable session tracking for JSP pages if the browser has disabled cookies? - We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
    	hello1.jsp

    <%@ page session="true" %>

    <%

    Integer num = new Integer(100);

    session.putValue("num",num);

    String url =response.encodeURL("hello2.jsp");

    %>

    '>hello2.jsp

    	hello2.jsp

    <%@ page session="true" %>

    <%

    Integer i= (Integer )session.getValue("num");

    out.println("Num value in session is "+i.intValue());

  10. How can I declare methods within my JSP page? - You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example:
    	<%!

    public String whereFrom(HttpServletRequest req) {

    HttpSession ses = req.getSession();

    ...

    return req.getRemoteHost();

    }

    %>

    <%

    out.print("Hi there, I see that you are coming in from ");

    %>

    <%= whereFrom(request) %>

    Another Example

    file1.jsp:

    <%@page contentType="text/html"%>

    <%!

    public void test(JspWriter writer) throws IOException{

    writer.println("Hello!");

    }

    %>

    	file2.jsp

    <%@include file="file1.jsp"%>





    <%test(out);% >





  11. Is there a way I can set the inactivity lease period on a per-session basis? - Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example:
    	<%

    session.setMaxInactiveInterval(300);

    %>

    would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

  12. How can I set a cookie and delete a cookie from within a JSP page? - A cookie, mycookie, can be deleted using the following scriptlet:
    	<%

    //creating a cookie

    Cookie mycookie = new Cookie("aName","aValue");

    response.addCookie(mycookie);

    //delete a cookie

    Cookie killMyCookie = new Cookie("mycookie", null);

    killMyCookie.setMaxAge(0);

    killMyCookie.setPath("/");

    response.addCookie(killMyCookie);

    %>

  13. How does a servlet communicate with a JSP page? - The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
    	public void doPost (HttpServletRequest request, HttpServletResponse response) {

    try {

    govi.FormBean f = new govi.FormBean();

    String id = request.getParameter("id");

    f.setName(request.getParameter("name"));

    f.setAddr(request.getParameter("addr"));

    f.setAge(request.getParameter("age"));

    //use the id to compute

    //additional bean properties like info

    //maybe perform a db query, etc.

    // . . .

    f.setPersonalizationInfo(info);

    request.setAttribute("fBean",f);

    getServletConfig().getServletContext().getRequestDispatcher

    ("/jsp/Bean1.jsp").forward(request, response);

    } catch (Exception ex) {

    . . .

    }

    }

    The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.

    jsp:useBean id="fBean" class="govi.FormBean" scope="request"

    / jsp:getProperty name="fBean" property="name"

    / jsp:getProperty name="fBean" property="addr"

    / jsp:getProperty name="fBean" property="age"

    / jsp:getProperty name="fBean" property="personalizationInfo" /

  14. How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default? - One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:

    Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
    • The service() method has to invoke the _jspService() method
    • The init() method has to invoke the jspInit() method
    • The destroy() method has to invoke jspDestroy()

    If any of the above conditions are not satisfied, the JSP engine may throw a translation error.

    Once the superclass has been developed, you can have your JSP extend it as follows:

    	<%@ page extends="packageName.ServletName" %>

  15. How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values? - You could make a simple wrapper function, like
    	<%!

    String blanknull(String s) {

    return (s == null) ? "" : s;

    }

    %>

    then use it inside your JSP form, like

    " >

  16. How can I get to print the stacktrace for an exception occuring within my JSP page? - By printing out the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:
    	<%@ page isErrorPage="true" %>

    <%

    out.println(" ");

    PrintWriter pw = response.getWriter();

    exception.printStackTrace(pw);

    out.println(" ");

    %>

  17. How do you pass an InitParameter to a JSP? - The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
    	<%@ page import="java.util.*" %>

    <%!

    ServletConfig cfg =null;

    public void jspInit(){

    ServletConfig cfg=getServletConfig();

    for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {

    String name=(String)e.nextElement();

    String value = cfg.getInitParameter(name);

    System.out.println(name+"="+value);

    }

    }

    %>

  18. How can my JSP page communicate with an EJB Session Bean? - The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:
    	<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>

    <%!

    //declare a "global" reference to an instance of the home interface of the session bean

    AccountHome accHome=null;

    public void jspInit() {

    //obtain an instance of the home interface

    InitialContext cntxt = new InitialContext( );

    Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");

    accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);

    }

    %>

    <%

    //instantiate the session bean

    Account acct = accHome.create();

    //invoke the remote methods

    acct.doWhatever(...);

    // etc etc...

    %>