jump to navigation

J2EE May 26, 2006

Posted by Allu in J2EE.
comments closed

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

  1. 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.
  2. 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.
  3. 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.


  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. What is Applet container? – It manages the execution of applets. Consists of a Web browser and Java Plug-in running on the client together.
  8. 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.
  9. 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.
  10. 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.
  2. 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.
  3. 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.
  4. What is JTA and JTS? – JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Java Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call 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.
  5. 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.
  6. 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.
  7. What is JAAS? – 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.
  8. 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.
  9. 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.
  10. 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.

Struts FAQs May 25, 2006

Posted by Allu in Struts.
comments closed

java_L.gifWhat is Struts?

Struts is a java framework based on Model 2 architecture of JSP or popularly called Model-View-Controller architecture.It provides a controller for this architecture.

Explain Struts navigation flow?

Struts Navigation flow.

1) A request is made from previously displayed view.
2) The request reaches the ActionServlet which acts as the controller .The ActionServlet Looksup the requested URI in an XML file (Struts-Config.xml) and determines the name of the Action class that has to perform the requested business logic.
3)The Action Class performs its logic on the Model Components associated with the Application.
4) Once The Action has been completed its processing it returns the control to the Action Servlet.As part of its return the Action Class provides a key to determine where the results should be forwarded for presentation.
5)The request is complete when the Action Servlet responds by forwarding the request to the view, and this view represents the result of the action.

What is the difference between Struts 1.0 and Struts 1.1?


The new features added to Struts 1.1 are
1. RequestProcessor class
2. Method perform() replaced by execute() in Struts base Action Class
3. Changes to web.xml and struts-config.xml
4.Declarative exception handling
5.Dynamic ActionForms
7.Multiple Application Modules
8.Nested Tags
9.The Struts Validator
10.Change to the ORO package
11.Change to Commons logging
12.Removal of Admin actions
13. Deprecation of the GenericDataSource.


What is the purpose of tiles-def.xml file, resourcebundle.properties file, validation.xml file?

1. tiles-def.xml
tiles-def.xml is used as a configuration file for an appliction during tiles development
You can define the layout / header / footer / body content for your View.


<definition name="siteLayoutDef" path="/layout/thbiSiteLayout.jsp">
<put name="title" value="Title of the page" />
<put name="header" value="/include/thbiheader.jsp" />
<put name="footer" value="/include/thbifooter.jsp" />
<put name="content" type="string">
Content goes here

<definition name="userlogin" extends="siteLayoutDef">
<put name="content" value="/dir/login.jsp" />

2. validation.xml

The validation.xml file is used to declare sets of validations that should be applied to Form Beans.

Each Form Bean you want to validate has its own definition in this file
Inside that definition, you specify the validations you want to apply to the Form Bean's fields.


<form name="logonForm">
<field property="username"
<arg0 key=" prompt.username"/>
<field property="password"
<arg0 key="prompt.password"/>

3. Resourcebundle.properties

Instead of having hard-coded error messages in the framework, Struts Validator allows you to specify a key to a message in the ApplicationResources.properties (or resourcebundle.properties) file that should be returned if a validation fails.


In ApplicationResources.properties

errors.registrationForm.name={0} Is an invalid name.

In the registrationForm.jsp

<html:messages id="messages" property="name">
<font color="red">
<bean:write name="messages" />

Output(in red color) : abc Is an invalid name


1. Purpose of tiles-def.xml file is used to in the design face of the webpage. For example in the webpage "top or bottom or left is
fixed" center might be dynamically chaged.
It is used for the easy design of the web sites. Reusability

2. resourcebundle.properties file is used for lot of purpose. One of its purpose is internationalization. We can make our page to view on any language. It is independent of it. Just based on the browser setting it selects the language and it displayed as you mentioned in the resourcebundle.properties file.

3. Validation rule.xml is used to put all the validation of the front-end in the validationrule.xml. So it verifies. If the same rule is applied in more than one page. No need to write the code once again in each page. Use validation to chek the errors in forms.


tiles-def.xml – is required if your application incorporates the tiles framework in the "View" part of MVC. Generally we used to have a traditional JSP's (Which contgains HTML & java scriplets) are used in view. But Tiles is an advanced (mode or less ) implementation of frames used in HTML. We used to define the frames in HTML to seperate the header html, footer html, menu or left tree and body.html to reuse the contents. Hence in the same way, Tiles are defined to reuse the jsp's in struts like architectures, and we can define the jsp's which all are to be display at runtime, by providing the jsp names at runtime. To incorporate this we need tile-def.xml and the Class generally which extends RequestProcessor should extend TilesRequestProcessor.

resourcebundle.properties — It is to incorporate i18n (internationalization) in View part of MVC.

validation.xml – This file is responsible for business validations carried at server side before processing the request actually. It reduces the complexity in writing _JavaScript validations, and in this way, we can hide the validations from the user, in View of MVC.



What we will define in Struts-config.xml file. And explain their purpose?


In struts-config.xml we define Date Sources / Form Beans / Global Exceptions / Global Forwards / Action Mappings / Message Resources / Plug-ins

Example :

<!– Date Sources –>
<data-source autoCommit="false" description="First Database Config" driverClass=" org.gjt.mm.mysql.Driver" maxCount="4" minCount="2" password="admin" url="jdbc: mysql://localhost/ARTICLEDB" user="admin">
<!– Form Beans –>
<form-bean name="registrationForm" type="com.aaa.merchant.wsp.ActionForms.RegistrationForm">

<!– Global Exceptions –>
<exception key="some.key" type="java.io.IOException" handler="com.yourcorp.ExceptionHandler"/>


<!– A global-forward is retrieved by the ActionMapping findForward method. When the findForward method can't find a locally defined forward with the specified name, it searches the global-forwards available and return the one it finds.–>
<forward name="logoff" path="/logoff"/>
<forward name="logon" path="/logon.jsp"/>

<!– Actionn Mappings –>
<action path="/validateRegistration" type="com.dd.merchant.wsp.Actions.ValidateRegistration" validate="true" input="" name="registrationForm">
<forward name="success" path="/logon.jsp">

<!– Message Resources –>
<message-resources parameter="wsppaymentsweb.resources.ApplicationResources"/>

<!– Plug-ins –>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>


Struts-Config.xml is one of the most important part of any web application based on Sturts. This file is responsible for instructing the Struts what forms are available, what actions are available, and also allows a number of plug-in models to be added to the base Struts package. It can contain Data Source Configuration,Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions, Message Resources Definitions etc.

The most important are Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions.

The <form-bean/> is configured using only two attributes, name and type and doesn't contain any body. The form-bean tag is used to describe an instance of a particular Form Bean that will be later bound to action.

The attribute name specifies the name of the form bean, which is a unique identifier to this form bean & the attribute type specifies the absolute path of the class file.

<global-forwards/>: It is also configured using only two attributes, name and path and there is also an optional attribute redirect. The <forward/> specifies the mapping of a logical name to a context-relative URI path. In the above sample xml file we can see, one of the <forward/> is specified with the name as failure and its corresponding path as index.jsp. That means whenever the logical name failure is encountered the action will be forwarded to the index.jsp page.

The optional attribute redirect is set to false by default. When it is set to true it causes the ActionServlet to use HttpSevletResponse.sendRedirect() method.

<action-mappings/>: The action mapping mainly defines the mapping between the logical Action name and the physical action class. Now lets have an understanding about its attributes.

· The attribute path must be compulsorily defined and it should start with a '/' character. It specifies the context relative path of the submitted request.

· The type attribute specifies the absolute path of the fully qualified class name of the Action class.

· The attribute name must be the same as that of the form bean name for which you want to associate the action.

· The attribute scope specifies the scope of the particular form bean which is an optional one and its default value is session.

· The next attribute validate is also an optional one which by default is set to true. When set to true, the validate() method in the form bean is called which gets associated with a particular Action.

· The next attribute, input is also optional. Whenever a validation error is encountered then the control returns to the path specified in the input attribute.

<controller/>: The <controller/> can be used to modify the default behaviour of the Struts Controller i.e, we can define a RequestProcessor.

In struts-config.xml, we define all the global-forwards, action mappings, view mappings, form-bean mappings, controller mapping and finally message-resources declaration if any.
Why we need to declare means, the Controller servelet defined in struts internally looks for this xml file for its proceddings. In real scenario, that the controller servlet inplemented internally is nothing but a slave to this struts-config.xml. The information provided in this file is nothing but like the intelligence to the controller servlet to say – what to do in which situation ?
So, Controller servlet, needs this file to proceede/ run the application.

What is DispatchAction?

DispatchAction is specialized child of Struts Action class. It combines or group the methods that can further access the bussiness logic at a single place. The method can be anyone from CRUD [Create,Retrieve,Update or Delete] or it can be security check one like autheniticate user etc.
This class apart from having thread-safe execute method also can have user-defined methods.
In struts-config.xml files following changes are required for Dispatch action to work:

<action path="/login"
type ="com…..LoginAction"
name ="loginForm"
parameter ="task"
scope = "request"
validate = "false"
input = "/index.jsp">
<forward name="success" path="/jsp/common/index.jsp"/>
<forward name="loginagain" path="/index.jsp"/>

If above is your struts-config.xml file structure and LoginAction extends DispatchAction instead of normal Action class. And assuming [keep assuming] your LoginAction class have method named authenticateUser, then in your login.jsp add any hidden parameter called task with value as your method name and on submit of that page following will be the url:


Thus if we try to combine the last part of this puzzle we get the climax at struts-config.xml file's action-mapping tag described above. The parameter property of <action> tag have the task as it's value pointing to task variable in the request having it's value as authenticateUser hence the framework search in the LoginAction a method called authenticateUser through reflection and forwards the execution flow to it. This is all folks, the briallancy of Struts framework. Note DispatchAction class is included in 1.1 version.


How to call ejb from Struts?


We can call EJB from struts by using the service locator design patteren or by Using initial context with create home object and getting return remote referenc object.

What is the difference between ActionErrors and ActionMessages?

There is no differnece between these two classes.All the behavior of ActionErrors was copied into ActionMessages and vice versa. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — where as errors being only one kind of message.

The difference between saveErrors(…) and saveMessages(…) is simply the attribute name under which the ActionMessages object is stored, providing two convenient default locations for storing controller messages for use by the view. If you look more closely at the html:errors and html:messages tags, you can actually use them to get an ActionMessages object from any arbitrary attribute name in any scope.


What are the various Struts tag libraries?

The Struts distribution includes four tag libraries for the JSP framework (in struts-config.xml) :
* Bean tag library [ struts-bean.tld ] : Contains tags for accessing JavaBeans and their properties. Developers can also define new beans and set properties
* HTML tag library [ struts-html.tld ] : Contains tags to output standard HTML, including forms, textfields, checkboxes, radio buttons
* Logic tag library [ struts-logic.tld ] : Contains tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library [ struts-tiles.tld / struts-template.tld ] : For tiles implementation
* Nested tag library [ struts-nested.tld ] : allows the use of nested beans.

The libraries are designed to:

* Facilitate the separation of presentation and business logic.
* Dynamically generate Web pages.
* Implement the flow of control to and from the ActionServlet.

How you will handle errors and exceptions using Struts?

Struts exception handling can be done by two ways:
1. Declarative (using struts features via struts-config.xml)

key ="errors.exception2"

This makes coding in the Action class very simple
Since the execute method declares throws Exception we don't need a try-catch block.
Struts saves the exception using one of its global constants. You may use the field G lobals.EXCEPTION_KEY to retrieve it from the request object.

2. Programmatic (using the usual try-catch exception handling in Action Class)


We can Handle the errors by holding them into ActionError or ActionErrors classes defined by struts Framework. The other way around is by using the methods say saveErrors()….etc defined in Action class and can throw the error messages.


Struts handles errors by providing the ActionErrors class which is
extended from org.apache.struts.action…
To install your customized exception handler, the first step is to
create a class that extends org.apache.struts.action.ExceptionHandler. There are
two methods that you can override, execute() and storeException().
For handling exceptions you have to mention in <global-exceptions> tag
of struts-config.xml which accepts attributes like exception type,key and

How you will save the data across different pages for a particular client request using Struts?

One simple and general way is by using session Object.

In specific, we can pass this by using request Object as well.

Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request.


What is Action Class? What are the methods in Action class?

An Action class is some thing like an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.
The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method. Struts Action class is a unit of logic. It is where a call to business function is made. In short the Action class acts like a bridge between client side(user action) and business operation(on server.
Some of the impotant methods of Action class are, execute()
generateToken() resetToken() getServlet()

Explain about token feature in Struts?


Use the Action Token methods to prevent duplicate submits:
There are methods built into the Struts action to generate one-use tokens. A token is placed in the session when a form is populated and also into the HTML form as a hidden property. When the form is returned, the token is validated. If validation fails, then the form has already been submitted, and the user can be apprised.
on the return trip,

What is the difference between ActionForm and DynaActionForm

# The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

# The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.

# ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

# ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).

# DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

# Time savings from DynaActionForm is insignificant. It doesn t take long for today s IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters and setters in the IDE than fixing your Action code and redeploying your web application)

Portal & Portlets FAQs May 25, 2006

Posted by Allu in Portlets.
comments closed

java_L.gifWhat is a portal ?
A portal can be best described as a web site that acts as a "point of entry" or a gate to a larger system. While it seems pretty difficult to define a portal in the strictest sense, these are some of the common features of portals:
Content aggregation:Portals tend to aggregate content from multiple, disparate sources and provide one unified view of the same.
Personalization:This refers to the ability of the portal to tailor the content/services that it offers according to the user of the portal.
Search:Most if not all portals, offer some form of searching of it's content and sometimes even content from external sources.
Single Sign On:Allows users to authenticate once to the portal and thereby allows access to many other systems without the need for reauthentication.

Do I need a portal server to build a portal ? What is a portal server ?
No, you don't. You can build a portal using any web based technology: J2EE, Dot Net , PHP or plain old CGI.
A portal server however provides a base infrastructure for rapidly developing/deploying portals. It also provides, out of the box implementations of most of the services that any portal would require.

What is a JSR 168 Portlet ?
Prior to JSR 168, almost all portal platforms offered their own proprietary approach to create pluggable portal components. For example, IBM had IBM portlets, Sun(iPlanet) had Providers, SAP had iViews and Plumtree had Gadgets.
JSR 168 aims to standardize these pluggable portal components so that they are independent of the actual portal server that they are written to. What this means is that one can migrate portlets seamlessly from one portal server to another without any code change.

What are the benefits of JSR 168?
Portal integration components based on the new standard will enable interoperability independent of the portal vendor solution — and enable enterprises to more easily use portal platforms for the secure delivery of personalized Web services and aggregated content between multiple internal and external portal deployments.
For Developers:The new standard will allow developers to reuse existing integration methods for faster addition of data, applications, and services from multiple back-end sources. Developers and independent software vendors (ISVs) will benefit from reduced development time and cost since the specification is based on Java APIs and extends J2EE capabilities to portals.
For Customers:Enterprises will benefit from greater efficiency and ROI since personalized, aggregated content can be delivered from portal platforms to end-users from a multitude of sources previously difficult to integrate.
For Integrators:Integrators will have an easier time integrating and aggregating content for their Portal customers, facilitating the delivery of web services.

What is a portlet container and where will I find one?
A portlet container runs portlets and provides them with the required runtime environment. A portlet container contains portlets and manages their lifecycle. It also provides persistent storage for portlet preferences. A portlet container receives requests from the portal to execute requests on the portlets hosted by it.A portlet container is not responsible for aggregating the content produced by the portlets. It is the responsibility of the portal to handle the aggregation.
A portal and a portlet container can be built together as a single component of an application suite or as two separate components of a portal application.

Do I need a portal server to deploy/test my portlets?
Yes, Portlets only generate markup fragments, not complete documents. The Portal aggregates portlet markup fragments into a complete portal page. Also,Portlets are not directly bound to a URL and so web clients interact with portlets through a portal system.

What are the differences between portlets and servlets?
Essentially, Servlets provide content that normally takes up the whole page in a browser (unless you're using frames), and portlets provide content that is wrapped by a window. With portlets, you can have multiple portlets side by side with one another and each one can provide content and functionality that is different from the other. A portlet can provide the complete interaction for one type of application, while another portlet can provide content for another type of application. The portal can provide some house keeping functionality and secured single point of entry to all of the portlets on a page. As for the particulars (similarities/differences) between them, please continue reading.
Here are some similarities:
Servlets and portlets are web based components that utilize Java for their implementation
Portlets are managed by a portlet container similar to a servlet container
Both of these components generate content, which can be static or dynamic
Both portlets and servlets have a lifecycle that is controlled by the container
The client/server model is used for both servlets and portlets
The packaging and deployment are essentially the same
The manner in which the classes are loaded and the class loaders that perform the work are also the same
Lifecycle management is similar
The Request and Response semantics are also similar
Here are some differences:
Servlets can provide complete web pages, whereas portlets only provide fragments. These fragments are then aggregated to form a complete web page by the portal
Portlets aren’t allowed to generated HTML code that contains tags such as base, body, frame, frameset, head, html, or title. The iframe tag can be used with caution.
The user cannot access a portlet directly using a URL in the way that a servlet is accessed. Instead, the URL points to the page containing all of the portlets on one page
Communication between the web client and the portlets is performed through the portal
Portlets can be provided with buttons or controls to manipulate the portlets’ window states or portlet modes
Multiple instances of a single portlet can be placed onto the same page
Portlets support persistent configuration and customization
Portlets also support user profile information
Portlets support two scopes within the session; application scope and portlet scope
There are several things that servlets are allowed to do, but portlets aren’t. These include the following:
Portlet aren’t allowed to set the character set encoding of the response
Portlet also aren’t allowed to set the HTTP headers on the response
Portlet cannot manipulate the URL of the client request to the portal

Developer FAQ
Can I get the HttpServletRequest from a Portlet?
The PortletRequest object is supposed to give you everything you need i.e. parameters, attributes, dispatching, etc. As per the spec, you should not need the HttpServletRequest.
However, some portlet container implementations do provide some kind of hack to get hold of HttpServletRequest e.g. in Pluto you can cast the RenderRequest to HttpServletRequest. But, be aware that this behavior cannot be relied upon.

Can I use sessions in portlets?
Yes, the specification defines a PortletSession interface that allows a portal/portlet-container to use any of the session tracking approaches (such as HTTP Cookies, SSL Sessions or URL rewriting) to track a user’s session. The PortletSession interface defines two scopes for storing objects, APPLICATION_SCOPE and PORTLET_SCOPE.
Use APPLICATION_SCOPE, if you want to access attributes which have been placed within the session in external resources like your servlet. The PORTLET_SCOPE attributes, although available to other resources, are used for attributes that are meant for the portlet's use only.

What's difference between PortletConfig.getInitParameter() and PortletContext.getInitParameter()?
Context-wide init-params share the same context space as Servlets and JSPs belonging to the same application and they are defined in the web.xml file. You can get them using PortletContext.getInitParameter() method.
Portlet-wide initialization parameters on the other hand belong in the portlet.xml file and you can get them using PortletConfig.getInitParameter() method.

How can I set/retrieve a cookie from a portlet?
No you cant.There is no direct way to set/retrieve a cookie value from a portlet.
Cookies are used a mechanism for session tracking. The portlet specification does not mandate the portal server to use any particular session tracking mechanism. In fact, the portal server is free to use whatever mechanism it chooses: Cookies, URL rewriting, Https Sessions etc. Portlet developers are expected to use the PortletSession object and leave it to the portal server to deal with the underlying mechanism.

Can I set a cookie from an included Servlet/ JSP ?
This will not work. The Portlet Spec (PLT 16.3.3) mandates that the addCookie() call on an included Servlet or JSP does no operation. If this does work on some containers, then it should be considered a bug and should not be relied upon.

Is there a hack to get/set cookies ?
PortletRequest Properties:The getProperties() method of the PortletRequest would return the HTTP headers,if available. This can be used to retrieve the cookie values in most containers. This behavior cannot be relied upon as there might be circumstances where they are unavailable.
Javascript:You can embed javascript functions in a JSP page and include that JSP in your response. In the javascript,you can have code that can set/retrieve cookies and if needed, pass it over to the portlet

How do I achieve inter-portlet communication ?
Inter-portlet communication refers to the ability by which portlets can communicate with each other in a spec compliant way. There are currently two approaches to achieve inter-portlet communication. The exact approach you choose would depend on the problem you are trying to address
Using the PortletSession:
A PortletSession is created for each user per portlet application. This makes the PortletSession useful for communicating all user related information among different portlets in the same portlet application.
When you set attributes in a PortletSession you have two options: To use a PORTLET scope (this is the default) or to use an APPLICATION scope. If you want the particular attribute to be shared among portlets, you need to use the APPLICATION scope.
For example, consider CityPortlet and WeatherPortlet, two portlets in the same application.In processAction() of CityPortlet: portletSession.setAttribute("cityName", newCityName, PortletSession.APPLICATION_SCOPE);
In the WeatherPortlet, you can retrieve the changed city name by getting it from the PortletSession:In doView() of WeatherPortlet: currentCityName=(String)portletSession.getAttribute("cityName",PortletSession.APPLICATION_SCOPE); showWeatherForThisCity(currentCityName);
Pretty simple, but here is a caveat. The portlet spec does not mandate any order in which the doView() (or for that matter doEdit() or doHelp()) be called for multiple portlets on the same portal page. This means if you were to set an attribute in the doView() method of CityPortlet you may or may not get the attribute in the doView() of WeatherPortlet (depending on the portal server and perhaps the layout that you are using). The spec, however, does mandates that the processAction() be called before any rendering method is called. Therefore you need to ensure that any state change that needs to be propagated across multiple portlets in the same portlet application is confined to the processAction() method.
Using the PortletContext:
A PortletContext (very similar to a ServletContext) is shared between all users and all portlets in a portlet application. You can get and set attributes from the PortletContext and this can be used as a global point of communication.
For example, if the WeatherPortlet uses a webservice which is currently unavailable. You might have code like this:In doView() of WeatherPortletif(portletContext.getAttribute("errorMessage") = null) { displayErrorMessage();}
In this case, all instances of WeatherPortlet irrespective of which user is seeing it, would see the error message.
While inter-portlet communication can be done using any of the above stated methods, one must be careful about the dependencies that are introduced when utilizing interportlet communication.
In the CityPortlet/WeatherPortlet example, what would happen if the user decides to remove the CityPortlet from his page? Would the WeatherPortlet still be functional? Should we force the user to remove the WeatherPortlet as well? These are some of the design considerations that need to be taken in account before using inter-portlet communication.

What if I need two portlets from two different portlet applications to communicate with each other ?
This situation occurs rarely and if it does, you may need to review your packaging structure. Do you really want to couple two unrelated portlets? If they are dependent wouldn't you rather package them in the same application?
If you still need the portlets to communicate, you will have to use some other standard J2EE communication mechanisms like JNDI , Database with JDBC, messaging through JMS etc

But there should be a way to communicate between portlets in different wars, right ???
Yea. It's called "remoting". The fact is that when two portlets are in two different wars, they are consider to be essentially in two different applications. One war = one wep app. The only exception to this rule is when the two wars happen to be actually the same application (meaning the same war) spread across a cluster (running in different JVMs).
That said, if you want two different portlets in two different applications to communicate with each other, there is nothing to stop you from using any of the other J2EE remote communications mechanisms to make it happen. You have your choice of EJBs, RMI, or Messaging. There is nothing in the Portlet spec that would keep you from doing so.
Before you attempt to go this route, there are two questions you should be asking yourself:
How do you go about refreshing the appearance of portlet2 based on the state change? For example, if portlet1 and portlet2 are in two different applications and possibly two different windows, how do you cause portlet2 render method to be called. Normally, this is called on a pull operation (not a push). The only way around this is to use an applet on the client to keep a communication link open, allowing the portlet to push content down to the client.
How do you go about placing two portlets from different web apps in one window if this is the look you desire?
You could also possibly solve these issues using WSRP. However, you are adding more to the layers and therefore taking away from your performance when it just might not be necessary.
It sounds like you're going about this all wrong. One of the possible uses for Portals is to bring together content from multiple sources. If you have two applications producing output that you wish to bring together in one portal application, the best thing to do (and one of the reasons that portals were designed to begin with) is to create an application that provides the portlets with each portlet pointing to their respective applications. That way you can gather the content from their respective sources easily and effiently and provide their output through the same portlet app. So, essentially, in your case you might have three applications. Two provide content that is channeled and rendered to the user through the third, which happens to be the portlet app.
In this case, you could still use the APPLICATION_SCOPE session attributes to pass content from one portlet to the other. As portlet1 interacts with the user, it places content into the session during its processAction call, and portlet2 uses the content in its doView call. During the doView call of portlet2, it can communicate with whatever application or resource it needs to, in order to gather the content and then produce it back to the portal page in its rendition.