Tuesday, 26 July 2016

What is IDE

 
IDE : integrated development environment also known as integrated design environment or integrated debugging environment, Which is a software application that provides comprehensive facilities to computer programmers for software development.

An IDE normally consists of:
• a source code editor
• a compiler and/or an interpreter
• build automation tools
• a debugger  

Language support
Some IDEs support multiple languages Such as Eclipse or NetBeans That all are support Java, C, C++, PHP etc  

NetBeans IDE:
NetBeans refers to both a platform framework for Java desktop , Web applications and an integrated development environment (IDE) for developing with Java, JavaScript, PHP, Python, Ruby, Groovy, C, C++, Scala, Clojure, and others. The NetBeans IDE is written in Java and can run anywhere a JVM is installed, including Windows, Mac OS, Linux, and Solaris. A JDK is required for Java development functionality, but is not required for development in other programming languages. The NetBeans Platform allows applications to be developed from a set of modular software components called modules. Applications based on the NetBeans platform  

Eclipse IDE: 
Eclipse is a multi-language software development environment comprising an integrated development environment (IDE) and an extensible plug-in system. It is written mostly in Java and can be used to develop applications in Java and, by means of various plug-ins, other programming languages including Ada, C, C++, COBOL, Perl, PHP, Python, Ruby (including Ruby on Rails framework), Scala, Clojure, and Scheme. The IDE is often called Eclipse ADT for Ada, Eclipse CDT for C/C++, Eclipse JDT for Java, and Eclipse PDT for PHP.  

Visual Studio :
Visual Studio is another Powerful IDE Such as Visual Studio .NET IDE Visual Studio .NET IDE (Integrated Development Environment) is the Development Environment for all .NET based applications which comes with rich features. VS .NET IDE provides many options and is packed with many features that simplify application development by handling the complexities. Visual Studio .NET IDE is an enhancement to all previous IDE’s by Microsoft.

Extending Servlets



Extending  Servlets

#: What is Session?
Answer: when a user makes a page request to the server, the server creates a temporary session to identify that user. So when that same user goes to another page on that site, the server identifies that user. So a session is a small and temporary unique connection between a server and the user enabling it to identify that user across multiple page requests or visits to that site

Session Management:
Session management is to use the API provided by your application server to identify the user across multiple page requests. Note that every server has it's own set of API for session management, since we are talking about 'Managing Sessions with Java Servlets', we will be making use of the Servlet API 2.2 which almost all of the Java application servers support.
HttpSession Interface
Managing sessions has been made extremely easy by the Servlet API since there is just a single interface involved and that interface is
HttpSession interface. You then invoke methods of this interface to interact with the user.
Methods of HttpSession Interface
Before going into the details of using different methods of this interface, lets first see what are different methods available to us.
  • getAttribute(), getAttributeNames(), setAttribute(), removeAttribute() These methods are used to set, get and remove objects from a user session. We will see later how to use them.
  • getId() Every session created by the server has a unique 'id' associated with it in order to identify this session from other sessions. This method returns the 'id' of this session.
  • getCreationTime() Simple returns a long value indicating the date and time this session was created, meaning there by that you get the time this user first accessed your site.
  • getLastAccessedTime() Returns a long value indicating the last time user accessed any resource on this server.
# The Stateless Environment
Answer: Stateless VS Stateful In ususal interactive programming, you deal with a stateful environments. That means, your app is in a session with the user. You have multiple queries and responses during this single session and you keep some sort of processing state (usually in main memory).
A typical example is a mailorder application. Following is a typical pseudo-code for such an application:
log on user
do
      allow user to browse database
      add new selection to set of selections
until user has finished selection phase
if any products were selected
      ask for shipping/billing information
      enter selection as an order
log off user
This is a typical sample in a procedure oriented environment. Not really neat for an event driven GUI interface, but one thing is common to such applications: the application keeps state information of the user session. This processing state is preserved across multiple interactions (here the product selection phase). The preservation of the processing state is done by the environment itself, typically by letting you application staying loaded during the multiple requests. Your application is always in control of what's going on and can handle it. This is a typical example of a stateful environment.
A stateless environment, on the other hand, does not offer these benefits to your application. The environment won't do anything to preserve the session state. Each request and response is a new one and not related to any other.
As you might guess, there are of course ways to implement stateful sessions in stateless environements. This is what this document is all about.

# Solutions to providing state
Answer:  When the Hyper-Text Transfer Protocol (HTTP) was developed, its designers chose to create a protocol which does not maintain a persistent connection. Each request made by a Web browser, for an image, an HTML page, or other Web object, is made via a new connection. It would have been handy if Web browsers established a single connection, through which multiple requests could be made. Indeed, this feature has been introduced in HTTP 1.1, with the keep-alive feature. This feature comes too late though for server-side programmers, as support for legacy browsers and Web servers must be maintained. Without an ongoing session, however, it is difficult for developers to maintain state across HTTP requests. This ability is critical though for all but the simplest of server-side applications. A shopping cart, for example, needs to maintain a list of items and have this list associated with a specific user.
 Developers are an inventive bunch and quickly found solutions. The simplest of all was to encode hidden parameters inside an HTML form, such as the username and type of transaction being made. Though not evident to the user, additional state information has been added to the form, which will be passed when the form is submitted. If every form included a hidden field indicating the user, then it would be possible to track user actions across HTTP requests. Of course, additional information can also be included, such as the
type of operation being performed, as well as the focus of the operation. The following HTML code illustrates the use of hidden fields:
<form action="/servlet/order" method=post>
<input type="hidden" name=userid value="5532211">
<input type="hidden" name=operation  value="add">
<input type="hidden" name=product_id value="4432A">
Product ID : 4432A
Quantity   : <input type="quantity" value=1>
<input type=submit>
</form>
A variation on this theme is to use hyperlinks, which generate HTTP GET requests. Often a hyperlink is better than an HTML form, as most users are more comfortable with hyperlinks than buttons. Parameters can be added to the end of each URL, so that state information is passed when the next connection is made. For example, every hyperlink on the page could contain a userID code to allow user activity to be tracked. This information can be fetched by a servlet using
javax.servlet.http.HttpServletRequest.getParameter(String)
just as a standard CGI parameter would.
<a href="/servlet/shopping?userID=5532211>View Shopping Cart</a>
Whether a hyperlink or an HTML form is used, this state information must be included every time a request is made, so that subsequent requests can gain access to it. If your servlet misses a URL or a hidden variable is missed from a form, the state information is lost. Such solutions are crude but effective. They do the job but are an inelegant and overly complex way of maintaining state across HTTP requests. A better way of maintaining state information is to use persistent client state cookies.


NOTE: Stateless and Stateful  Stateless protocol (like HTTP) A protocol that can't remember previous connections and can't distinguish one client's  request from that of another.  Stateful protocol (like FTP)   does not require you to create a new   connection for every request  maintains the user's credentials throughout  the session

# Session Management with cookies
Answer:  The HTTP state management mechanism specifies a way to create a stateful session with HTTP requests and responses.
Generally, HTTP request/response pairs are independent of each other. However, the state management mechanism enables clients and servers that can exchange state information to put these pairs in a larger context, which is called a session. The state information used to create and maintain the session is called a cookie.
Note: A cookie is a piece of data that can be stored in a browser's cache. If you visit a web site and then revisit it, the cookie data can be used to identify you as a return visitor. Cookies enable state information, such as an online shopping cart, to be remembered. A cookie can be short term, holding data for a single web session, that is, until you close the browser, or a cookie can be longer term, holding data for a week or a year.
 Web browsers and e-commerce sites use HTTP to communicate. Since HTTP is a stateless protocol (meaning that each command is executed independently without any knowledge of the commands that came before it), there must be a way to manage sessions between the browser side and the server side.
WebSphere Commerce supports two types of session management: cookie-based and URL rewriting.
Cookie-based session management
When cookie-based session management is used, a message (cookie) containing user's information is sent to the browser by the Web server. This cookie is sent back to the server when the user tries to access certain pages. By sending back the cookie, the server is able to identify the user and retrieves the user's session from the session database; thus, maintaining the user's session. A cookie-based session ends when the user logs off or closes the browser. Cookie-based session management is secure and has performance benefits. Cookie-based session management is secure because it uses an identification tag that only flows over SSL (Secure Sockets Layer).  Cookie-based session management offers significant performance benefits because the WebSphere Commerce caching mechanism only supports cookie-based sessions, and not URL rewriting. Cookie-based session management is recommended for customer sessions.

If you are not using URL rewriting and you want to ensure that users have cookies enabled on their browsers, check Cookie acceptance test on the Session Management page of Configuration Manager. This informs the customer that if their browser does not support cookies, or if they have turned off cookies, they need a browser that supports cookies to browse the WebSphere Commerce site.

For security reasons, cookie-based session management uses two types of cookies:
Non-secure session cookie
Used to manage session data. Contains the session ID, negotiated language, current store and the customers preferred currency when the cookie is constructed. This cookie can flow between the browser and server under either SSL or non-SSL connection. There are two types of non-secure session cookies:

1.A WebSphere Application Server session cookie is based on the servlet HTTP session standard. WebSphere Application Server cookies persist to memory or to the database in a multinode deployment. For more information.

2.A WebSphere Commerce session cookie is internal to WebSphere Commerce and does not persist to the database.

Secure authentication cookie
Used to manage authentication data. An authentication cookie flow over SSL and is time stamped for maximum security. This is the cookie used to authenticate the user; whenever a sensitive command is executed, for example, the DoPaymentCmd which asks for a users credit card number. There is minimal risk that this cookie could be stolen and used by an unauthorized user. Authentication code cookies are always generated by WebSphere Commerce whenever cookie based session management is in use.

Both the session and authentication code cookies are required to view secure pages.
For cookie errors the CookieErrorView is called under the following circumstances:
·   The user has logged in from another location with the same Logon ID.
·   The cookie became corrupted, or was tampered with or both.
·   If cookie acceptance is set to "true" and the user's browser does not support cookies.
# Session Management with Encoded URLs
Answer:  With URL rewriting, all links that are returned to the browser or that get redirected have the session ID appended to them. When the user clicks these links, the rewritten form of the URL is sent to the server as part of the client's request. The servlet engine recognizes the session ID in the URL and saves it for obtaining the proper object for this user. To use URL rewriting, HTML files (files with .html or .htm extensions) cannot be used for links. To use URL rewriting, JSP files must be used for display purposes. A session with URL rewriting expires when the customer logs off.
Note: WebSphere Commerce dynamic caching and URL rewriting cannot interoperate. With URL rewriting turned on, you need to disable WebSphere Commerce dynamic caching.
The administrator can choose to support either only cookie-based session management or both cookie-based and URL rewriting session management. If WebSphere Commerce only supports cookie-based, customers' browsers must be able to accept cookies. If both cookie-based and URL rewriting are selected, WebSphere Commerce first attempts to use cookies to manage sessions; if the customer's browser is set to not accept cookies then URL rewriting is used.
URL rewriting is the lowest common denominator of session tracking. When a client will not accept a cookie, URL rewriting may be used by the server as the basis for session tracking. URL rewriting involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session.
The session ID must be encoded as a path parameter in the URL string. The name of the parameter must be 'jsessionid' (lowercase !). Here is an example of a URL containing encoded path information:
http://www.myserver.com/catalog/index.html;jsessionid=1234                                             
                                                      
package javax.servlet.http;

public interface HttpServletRequest extends javax.servlet.ServletRequest {
       
        public boolean isRequestedSessionIdFromCookie();
        public boolean isRequestedSessionIdFromURL();
        public boolean isRequestedSessionIdValid();
}                                    
There are 2 methods in the HttpServletResponse for URL rewriting:
  • encodeURL(String)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary. For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.
  • encodeRedirectURL(String)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. Because the rules for making this determination can differ from those used to decide whether to encode a normal link, this method is separated from the encodeURL method. All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.
package javax.servlet.http;
                                     
public interface HttpServletResponse extends javax.servlet.ServletResponse {

        public java.lang.String encodeURL(java.lang.String url);
        public java.lang.String encodeRedirectURL(java.lang.String url)

}
                                     
public void doGet(HttpServletRequest req, HttpServletResponse res)
               throws IOException, ServletException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
       
        out.print("<form action='");
        out.print(response.encodeURL("SessionExample"));
        out.print("' ");
        out.println("method='post'>");
}



# Session Management in Servlets
Answer: Developing session management in servlets : This information, combined with the coding example SessionSample.java,  provides a programming model for implementing sessions in your own servlets.

Procedure   
1. Get the HttpSession object. To obtain a session, use the getSession() method of the javax.servlet.http.HttpServletRequest object in the Java Servlet 2.3 API.

When you first obtain the HttpSession object, the Session Management facility uses one of three ways to establish tracking of the session: cookies, URL rewriting, or Secure Sockets Layer (SSL) information.
Assume the Session Management facility uses cookies. In such a case, the Session Management facility creates a unique session ID and typically sends it back to the browser as a cookie. Each subsequent request from this user (at the same browser) passes the cookie containing the session ID, and the Session Management facility uses this ID to find the user's existing HttpSession object.

In Step 1 of the code sample, the Boolean(create) is set to true so that the HttpSession object is created if it does not already exist. (With the Servlet 2.3 API, the javax.servlet.http.HttpServletRequest.getSession() method with no boolean defaults to true and creates a session if one does not already exist for this user.)

2. Store and retrieve user-defined data in the session.  After a session is established, you can add and retrieve user-defined data to the session. The HttpSession object has methods similar to those in java.util.Dictionary for adding, retrieving, and removing arbitrary Java objects.

 In Step 2 of the code sample, the servlet reads an integer object from the HttpSession, increments it, and writes it back. You can use any name to identify values in the HttpSession object. The code sample uses the name sessiontest.counter.

Because the HttpSession object is shared among servlets that the user might access, consider adopting a site-wide naming convention to avoid conflicts.
3. (Optional) Output an HTML response page containing data from the HttpSession object.

4. Provide feedback to the user that an action has taken place during the session. You may want to pass HTML code to the client browser indicating that an action has occurred. For example, in
step 3 of the code sample, the servlet generates a Web page that is returned to the user and displays the value of the sessiontest.counter each time the user visits that Web page during the session.
5.(Optional) Notify Listeners. Objects stored in a session that implement the javax.servlet.http.HttpSessionBindingListener interface are notified when the session is preparing to end and become invalidated. This notice enables you to perform post-session processing, including permanently saving the data changes made during the session to a database.
6. End the session. You can end a session: * Automatically with the Session Management facility if a session is inactive for a specified time. The administrators provide a way to specify the amount of time after which to invalidate a session. * By coding the servlet to call the invalidate() method on the session object.

Example
import java.io.*;   import java.util.*;   import javax.servlet.*;   import javax.servlet.http.*;

public class SessionSample  extends HttpServlet {
  public void doGet (HttpServletRequest request, HttpServletResponse response) 
       throws ServletException, IOException {

   // Step 1: Get the Session object
      boolean create = true;        
      HttpSession session = request.getSession(create);
   // Step 2: Get the session data value
      Integer ival = (Integer)             
      session.getAttribute ("sessiontest.counter");        
      if (ival == null) ival = new Integer (1);        
      else ival = new Integer (ival.intValue () + 1);          
      session.setAttribute ("sessiontest.counter", ival);      

   // Step 3: Output the page
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<html>"); 
      out.println("<head><title>Session Tracking Test</title></head>");
      out.println("<body>");
      out.println("<h1>Session Tracking Test</h1>");
      out.println ("You have hit this page " + ival + " times" + "<br>");
      out.println ("Your " + request.getHeader("Cookie"));
      out.println("</body></html>");   
   }
}

Monday, 25 July 2016

Extending java Sever Pages and Servlets


# What is Java Beans?
Answer: Java Beans are reusable components. They are used to separate Business logic from the Presentation logic. Internally, a bean is just an instance of a class.
 JSP’s provide three basic tags for working with Beans.  
<jsp:useBean id=“bean name”  
class=“bean class”
scope = “page | request | session |application ”/>

# How to use Java Beans
Answer: To use a bean in a JSP page, three attributes must be supplied - an id, which provides a local name for the bean, the bean's class name, which is used to instantiate the bean if it does not exit, and a scope, which specifies the lifetime of the bean.
There are four scopes available - page, request, session, and application. A page-scoped bean is available only within the JSP page and is destroyed when the page has finished generating its output for the request. A request-scoped bean is destroyed when the response is sent. A session-scoped bean is destroyed when the session is destroyed. An application-scoped bean is destroyed when the web application is destroyed.
This example retrieves a session-scoped bean and makes it available using the id myBean. The bean is automatically created if it does not exist:
    <jsp:useBean id="myBean" class="com.mycompany.MyBean" scope="session" />
If it is necessary to initialize the bean after it is created, the initialization code can be placed in the body of the jsp:useBean action. The body will not be executed if the bean already exists. Here is an example:
    <jsp:useBean id="myBean2" class="com.mycompany.MyBean" scope="session">
        <%-- this body is executed only if the bean is created --%>
   
        <%-- intialize bean properties --%>
        <jsp:setProperty name="myBean2" property="prop1" value="123" />
    </jsp:useBean>
The value of a bean property can be included in the generated output using the jsp:getProperty action:
    <jsp:getProperty name="myBean" property="prop1" />
    <jsp:getProperty name="myBean" property="prop2" />
The jsp:useBean action also declares a local Java variable to hold the bean object. The name of the local variable is exactly the value of the id attribute. Here is an example that accesses the bean within a scriptlet:
    <%
        if (myBean.getProp1() % 2 == 0) {
            out.println("<font color=\"red\">"+myBean.getProp1()+"</font>");
        } else {
            out.println("<font color=\"green\">"+myBean.getProp1()+"</font>");
        }
    %>
Here is the bean used in the example:
    package com.mycompany;
   
    public class MyBean {
        // Initialize with random values
        int prop1 = (int)(Integer.MAX_VALUE*Math.random());
        String prop2 = ""+Math.random();
   
       public int getProp1() {
            return prop1;
        }
       public void setProp1(int prop1) {
            this.prop1 = prop1;
        }
       public String getProp2() {
            return prop2;
        }
       public void setProp2(String prop2) {
            this.prop2 = prop2;
        }
    }


# Java Beans and Servlets/JSPs
Answer: Integrating Servlets and JSP Pages
The JSP specification presents two approaches for building web applications using JSP pages: JSP Model 1 and Model 2 architectures. These two models differ in the location where the processing takes place. In Model 1 architecture, as shown in Figure 2, the JSP page is responsible for processing requests and sending back replies to clients.

Figure 2: JSP Model 1 Architecture

The Model 2 architecture, as shown in Figure 3, integrates the use of both servlets and JSP pages. In this mode, JSP pages are used for the presentation layer, and servlets for processing tasks. The servlet acts as a controller responsible for processing requests and creating any beans needed by the JSP page. The controller is also responsible for deciding to which JSP page to forward the request. The JSP page retrieves objects created by the servlet and extracts dynamic content for insertion within a template.

Figure 3: JSP Model 2 Architecture

This model promotes the use of the Model View Controller (MVC) architectural style design pattern. Note that several frameworks already exist that implement this useful design pattern, and that truly separate presentation from content. The Apache Struts is a formalized framework for MVC. This framework is best used for complex applications where a single request or form submission can result in substantially different-looking results.


# The Java Bean Specification
Answer:  As software developers, we are constantly being asked to build applications in less time and with less money. And, of course, these applications are expected to be better and faster than ever before. Object-oriented techniques and component software environments are in wide use now, in the hope that they can help us build applications more quickly. Development tools like Microsoft's Visual Basic have made it easier to build applications faster by taking a building-block approach to software development. Such tools provide a visual programming model that allows you to include software components rapidly in your applications.

The Component Model

Components are self-contained elements of software that can be controlled dynamically and assembled to form applications. But that's not the end of it. These components must also interoperate according to a set of rules and guidelines. They must behave in ways that are expected. It's like a society of software citizens. The citizens (components) bring functionality, while the society (environment) brings structure and order.
JavaBeans is Java's component model. It allows users to construct applications by piecing components together either programmatically or visually (or both). Support of visual programming is paramount to the component model; it's what makes component-based software development truly powerful.
The model is made up of an architecture and an API (Application Programming Interface). Together, these elements provide a structure whereby components can be combined to create an application. This environment provides services and rules, the framework that allows components to participate properly. This means that components are provided with the tools necessary to work in the environment, and they exhibit certain behaviors that identify them as such. One very important aspect of this structure is containment. A container provides a context in which components can interact. A common example would be a panel that provides layout management or mediation of interactions for visual components. Of course, containers themselves can be components.
As mentioned previously, components are expected to exhibit certain behaviors and characteristics in order to participate in the component structure and to interact with the environment, as well as with other components. In other words, there are a number of elements that, when combined, define the component model. These are described in more detail in the following sections.

Discovery and Registration

Class and interface discovery is the mechanism used to locate a component at run-time and to determine its supported interfaces so that these interfaces can be used by others. The component model must also provide a registration process for a component to make itself and its interfaces known. The component, along with its supported interfaces, can then be discovered at run-time. Dynamic (or late) binding allows components and applications to be developed independently. The dependency is limited to the "contract" between each component and the applications that use it; this contract is defined by interfaces that the component supports. An application does not have to include a component during the development process in order to use it at run-time; it only needs to know what the component is capable of doing. Dynamic discovery also allows developers to update components without having to rebuild the applications that use them.
This discovery process can also be used in a design-time environment. In this case, a development tool may be able to locate a component and make it available for use by the designer. This is important for visual programming environments, which are discussed later.

Raising and Handling of Events

An event is something of importance that happens at a specific point in time. An event can take place due to a user action such as a mouse clickwhen the user clicks a mouse button, an event takes place. Events can also be initiated by other means. Imagine the heating system in your house. It contains a thermostat that sets the desired comfort temperature, keeps track of the current ambient temperature, and notifies the boiler when its services are required. If the thermostat is set to keep the room at 70 degrees Fahrenheit, it will notify the boiler to start producing heat if the temperature dips below that threshold. Components will send notifications to other objects when an event takes place in which those objects have expressed an interest.

Persistence

Generally, all components have state. The thermostat component has state that represents the comfort temperature. If the thermostat were a software component of a computer-based heating control system, we would want the value of the comfort temperature to be stored on a non-volatile storage medium (such as the hard disk). This way if we shut down the application and brought it back up again, the thermostat control would still be set to 70 degrees. The visual representation and position of the thermostat relative to other components in the application would be restored as well.
Components must be able to participate in their container's persistence mechanism so that all components in the application can provide application-wide persistence in a uniform way. If every component were to implement its own method of persistence, it would be impossible for an application container to use components in a general way. This wouldn't be an issue if reuse weren't the goal. If we were building a monolithic temperature control system we might create an application-specific mechanism for storing state. But we want to build the thermostat component so that it can be used again in another application, so we have to use a standard mechanism for persistence.

Visual Presentation

The component environment allows the individual components to control most of the aspects of their visual presentation. For example, imagine that our thermostat component includes a display of the current ambient temperature. We might want to display the temperature in different fonts or colors depending on whether we are above, below, or at the comfort temperature. The component is free to choose the characteristics of its own visual presentation. Many of these characteristics will be properties of the component (a topic that will be discussed later). Some of these visual properties will be persistent, meaning that they represent some state of the control that will be saved to, and restored from, persistent storage.
Layout is another important aspect of visual presentation. This concerns the way in which components are arranged on the screen, how they relate to one another, and the behavior they exhibit when the user interacts with them. The container object that holds an assembly of components usually provides some set of services related to the layout of the component. Let's consider the thermostat and heating control application again. This time, the user decides to change the size of the application window. The container will interact with the components in response to this action, possibly changing the size of some of the components. In turn, changing the size of the thermostat component may cause it to alter its font size.
As you can see, the container and the component work together to provide a single application that presents itself in a uniform fashion. The application appears to be working as one unit, even though with the component development model, the container and the components probably have been created separately by different developers.

Support of Visual Programming

Visual programming is a key part of the component model. Components are represented in toolboxes or palettes. The user can select a component from the toolbox and place it into a container, choosing its size and position. The properties of the component can then be edited in order to create the desired behavior. Our thermostat control might present some type of user interface to the application developer to set the initial comfort temperature. Likewise, the choice of font and color will be selectable in a similar way. None of these manipulations require a single line of code to be written by the application developer. In fact, the application development tool is probably writing the code for you. This is accomplished through a set of standard interfaces provided by the component environment that allow the components to publish, or expose, their properties. The development tool can also provide a means for the developer to manipulate the size and position of components in relation to each other. The container itself may be a component and allow its properties to be edited in order to alter its behavior.

The JavaBeans Architecture

JavaBeans is an architecture for both using and building components in Java. This architecture supports the features of software reuse, component models, and object orientation. One of the most important features of JavaBeans is that it does not alter the existing Java language. If you know how to write software in Java, you know how to use and create Beans. The strengths of Java are built upon and extended to create the JavaBeans component architecture.
Although Beans are intended to work in a visual application development tool, they don't necessarily have a visual representation at run-time (although many will). What this does mean is that Beans must allow their property values to be changed through some type of visual interface, and their methods and events should be exposed so that the development tool can write code capable of manipulating the component when the application is executed.
Creating a Bean doesn't require any advanced concepts. So before I go any further, here is some code that implements a simple Bean:
public class MyBean implements java.io.Serializable
{
   protected  int theValue;
 
   public MyBean()
   {
   }
 
   public void setMyValue(int newValue)
   {
      theValue = newValue;
   }
 
   public int getMyValue()
   {
      return theValue;
   }
}
This is a real Bean named MyBean that has state (the variable theValue) that will automatically be saved and restored by the JavaBeans persistence mechanism, and it has a property named MyValue that is usable by a visual programming environment. This Bean doesn't have any visual representation, but that isn't a requirement for a JavaBean component.
JavaSoft is using the slogan "Write once, use everywhere." Of course "everywhere" means everywhere the Java run-time environment is available. But this is very important. What it means is that the entire run-time environment required by JavaBeans is part of the Java platform. No special libraries or classes have to be distributed with your components. The JavaBeans class libraries provide a rich set of default behaviors for simple components (such as the one shown earlier). This means that you don't have to spend your time building a lot of support for the Beans environment into your code.
The design goals of JavaBeans are discussed in Sun's white paper, "Java Beans: A Component Architecture for Java." This paper can be found on the JavaSoft web site at http://splash.javasoft.com/beans/WhitePaper.html. It might be interesting to review these goals before we move on to the technology itself, to provide a little insight into why certain aspects of JavaBeans are the way they are.

Compact and Easy

JavaBeans components are simple to create and easy to use. This is an important goal of the JavaBeans architecture. It doesn't take very much to write a simple Bean, and such a Bean is lightweightit doesn't have to carry around a lot of inherited baggage just to support the Beans environment. If a Bean does not require the advanced features of the architecture, it doesn't get them, nor does it get the code that goes with them. This is an important concept. The JavaBeans architecture scales upward in complexity, not downward like other component models. This means it really is easy to create a simple Bean. (The previous example shows just how simple a Bean can be.)

Portable

Since JavaBeans components are built purely in Java, they are fully portable to any platform that supports the Java run-time environment. All platform specifics, as well as support for JavaBeans, are implemented by the Java virtual machine. You can be sure that when you develop a component using JavaBeans it will be usable on all of the platforms that support Java (version 1.1 and beyond). These range from workstation applications and web browsers to servers, and even to devices such as PDAs and set-top boxes.

Leverages the Strengths of the Java Platform

JavaBeans uses the existing Java class discovery mechanism. This means that there isn't some new complicated mechanism for registering components with the run-time system.
As shown in the earlier code example, Beans are lightweight components that are easy to understand. Building a Bean doesn't require the use of complex extensions to the environment. Many of the Java supporting classes are Beans, such as the windowing components found in java.awt.
The Java class libraries provide a rich set of default behaviors for components. Use of Java Object Serialization is one examplea component can support the persistence model by implementing the java.io.Serializable interface. By conforming to a simple set of design patterns (discussed later in this chapter), you can expose properties without doing anything more than coding them in a particular style.

Flexible Build-Time Component Editors

Developers are free to create their own custom property sheets and editors for use with their components if the defaults aren't appropriate for a particular component. It's possible to create elaborate property editors for changing the value of specific properties, as well as create sophisticated property sheets to house those editors.
Imagine that you have created a Sound class that is capable of playing various sound format files. You could create a custom property editor for this class that listed all of the known system sounds in a list. If you have created a specialized color type called PrimaryColor, you could create a color picker class to be used as the property editor for PrimaryColor that presented only primary colors as choices.
The JavaBeans architecture also allows you to associate a custom editor with your component. If the task of setting the property values and behaviors of your component is complicated, it may be useful to create a component wizard that guides the user through the steps. The size and complexity of your component editor is entirely up to you.

JavaBeans Overview

The JavaBeans white paper defines a Bean as follows:
A Java Bean is a reusable software component that can be manipulated visually in a builder tool.
Well, if you have to sum it up in one sentence, this is as good as any. But it's pretty difficult to sum up an entire component architecture in one sentence. Beans will range greatly in their features and capabilities. Some will be very simple and others complex; some will have a visual aspect and others won't. Therefore, it isn't easy to put all Beans into a single category. Let's take a look at some of the most important features and issues surrounding Beans. This should set the stage for the rest of the book, where we will examine the JavaBeans technology in depth.

Properties, Methods, and Events

Properties are attributes of a Bean that are referenced by name. These properties are usually read and written by calling methods on the Bean specifically created for that purpose. A property of the thermostat component mentioned earlier in the chapter could be the comfort temperature. A programmer would set or get the value of this property through method calls, while an application developer using a visual development tool would manipulate the value of this property using a visual property editor.
The methods of a Bean are just the Java methods exposed by the class that implements the Bean. These methods represent the interface used to access and manipulate the component. Usually, the set of public methods defined by the class will map directly to the supported methods for the Bean, although the Bean developer can choose to expose only a subset of the public methods.
Events are the mechanism used by one component to send notifications to another. One component can register its interest in the events generated by another. Whenever the event occurs, the interested component will be notified by having one of its methods invoked. The process of registering interest in an event is carried out simply by calling the appropriate method on the component that is the source of the event. In turn, when an event occurs a method will be invoked on the component that registered its interest. In most cases, more than one component can register for event notifications from a single source. The component that is interested in event notifications is said to be listening for the event.

Introspection

Introspection is the process of exposing the properties, methods, and events that a JavaBean component supports. This process is used at run-time, as well as by a visual development tool at design-time. The default behavior of this process allows for the automatic introspection of any Bean. A low-level reflection mechanism is used to analyze the Bean's class to determine its methods. Next it applies some simple design patterns to determine the properties and events that are supported. To take advantage of reflection, you only need to follow a coding style that matches the design pattern. This is an important feature of JavaBeans. It means that you don't have to do anything more than code your methods using a simple convention. If you do, your Beans will automatically support introspection without you having to write any extra code. Design patterns are explained in more detail later in the chapter.
This technique may not be sufficient or suitable for every Bean. Instead, you can choose to implement a BeanInfo class which provides descriptive information about its associated Bean explicitly. This is obviously more work than using the default behavior, but it might be necessary to describe a complex Bean properly. It is important to note that the BeanInfo class is separate from the Bean that it is describing. This is done so that it is not necessary to carry the baggage of the BeanInfo within the Bean itself.
If you're writing a development tool, an Introspector class is provided as part of the Beans class library. You don't have to write the code to accomplish the analysis, and every tool vendor uses the same technique to analyze a Bean. This is important to us as programmers because we want to be able to choose our development tools and know that the properties, methods, and events that are exposed for a given component will always be the same.

Customization

When you are using a visual development tool to assemble components into applications, you will be presented with some sort of user interface for customizing Bean attributes. These attributes may affect the way the Bean operates or the way it looks on the screen. The application tool you use will be able to determine the properties that a Bean supports and build a property sheet dynamically. This property sheet will contain editors for each of the properties supported by the Bean, which you can use to customize the Bean to your liking. The Beans class library comes with a number of property editors for common types such as float, boolean, and String. If you are using custom classes for properties, you will have to create custom property editors to associate with them.
In some cases the default property sheet that is created by the development tool will not be good enough. You may be working with a Bean that is just too complex to customize easily using the default sheet. Beans developers have the option of creating a customizer that can help the user to customize an instance of their Bean. You can even create smart wizards that guide the user through the customization process.
Customizers are also kept separate from the Bean class so that it is not a burden to the Bean when it is not being customized. This idea of separation is a common theme in the JavaBeans architecture. A Bean class only has to implement the functionality it was designed for; all other supporting features are implemented separately.

Persistence

It is necessary that Beans support a large variety of storage mechanisms. This way, Beans can participate in the largest number of applications. The simplest way to support persistence is to take advantage of Java Object Serialization. This is an automatic mechanism for saving and restoring the state of an object. Java Object Serialization is the best way to make sure that your Beans are fully portable, because you take advantage of a standard feature supported by the core Java platform. This, however, is not always desirable. There may be cases where you want your Bean to use other file formats or mechanisms to save and restore state. In the future, JavaBeans will support an alternative externalization mechanism that will allow the Bean to have complete control of its persistence mechanism.

Design-Time vs. Run-Time

JavaBeans components must be able to operate properly in a running application as well as inside an application development environment. At design-time the component must provide the design information necessary to edit its properties and customize its behavior. It also has to expose its methods and events so that the design tool can write code that interacts with the Bean at run-time. And, of course, the Bean must support the run-time environment.

Visibility

There is no requirement that a Bean be visible at run-time. It is perfectly reasonable for a Bean to perform some function that does not require it to present an interface to the user; the Bean may be controlling access to a specific device or data feed. However, it is still necessary for this type of component to support the visual application builder. The component can have properties, methods, and events, have persistent state, and interact with other Beans in a larger application. An "invisible" run-time Bean may be shown visually in the application development tool, and may provide custom property editors and customizers.

Multithreading

The issue of multithreading is no different in JavaBeans than it is in conventional Java programming. The JavaBeans architecture doesn't introduce any new language constructs or classes to deal with threading. You have to assume that your code will be used in a multithreaded application. It is your responsibility to make sure your Beans are thread-safe. Java makes this easier than in most languages, but it still requires some careful planning to get it right. Remember, thread-safe means that your Bean has anticipated its use by more than one thread at a time and has handled the situation properly.

Security

Beans are subjected to the same security model as standard Java programs. You should assume that your Bean is running in an untrusted applet. You shouldn't make any design decisions that require your Bean to be run in a trusted environment. Your Bean may be downloaded from the World Wide Web into your browser as part of someone else's applet. All of the security restrictions apply to Beans, such as denying access to the local file system, and limiting socket connections to the host system from which the applet was downloaded.
If your Bean is intended to run only in a Java application on a single computer, the Java security constraints do not apply. In this case you might allow your Bean to behave differently. Be careful, because the assumptions you make about security could render your Bean useless in a networked environment.

Using Design Patterns

The JavaBeans architecture makes use of patterns that represent standard conventions for names, and type signatures for collections of methods and interfaces. Using coding standards is always a good idea because it makes your code easier to understand, and therefore easier to maintain. It also makes it easier for another programmer to understand the purpose of the methods and interfaces used by your component. In the JavaBeans architecture, these patterns have even more significance. A set of simple patterns are used by the default introspection mechanism to analyze your Bean and determine the properties, methods, and events that are supported. These patterns allow the visual development tools to analyze your Bean and use it in the application being created. The following code fragment shows one such pattern:
public void setTemperatureColor(Color newColor)
{
   . . .
}
 
public Color getTemperatureColor()
{
   . . .
}
These two methods together use a pattern that signifies that the Bean contains a property named TemperatureColor of type Color. No extra development is required to expose the property. The various patterns that apply to Beans development will be pointed out and discussed throughout this book. I'll identify each pattern where the associated topic is being discussed.
NOTE: The use of the term "design pattern" here may be confusing to some readers. This term is commonly used to describe the practice of documenting a reusable design in object-oriented software. This is not entirely different than the application of patterns here. In this case, the design of the component adheres to a particular convention, and this convention is reused to solve a particular problem.
As mentioned earlier, this convention is not a requirement. You can implement a specific BeanInfo class that fully describes the properties, methods, and events supported by your Bean. In this case, you can name your methods anything you please.

JavaBeans vs. ActiveX

JavaBeans is certainly not the first component architecture to come along. Microsoft's ActiveX technology is based upon COM, their component object model. ActiveX offers an alternative component architecture for software targeted at the various Windows platforms. So how do you choose one of these technologies over the other? Organizational, cultural, and technical issues all come into play when making this decision. ActiveX and JavaBeans are not mutually exclusive of each otherMicrosoft has embraced Java technology with products like Internet Explorer and Visual J++, and Sun seems to have recognized that the desktop is dominated by Windows and has targeted Win32 as a strategic platform for Java. It is not in anyone's best interest to choose one technology to the exclusion of another. Both are powerful component technologies. I think we should choose a technology because it supports the work we are doing, and does so in a way that meets the needs of the customer.
The most important question is how Beans will be used by containers that are designed specifically to contain ActiveX controls. Certainly, all Beans will not also be ActiveX controls by default. To address the need to integrate Beans into the world of ActiveX, an ActiveX Bridge is available that maps the properties, methods, and events exposed by the Bean into the corresponding mechanisms in COM. This topic is covered in detail in Chapter 11, ActiveX.

# Business Logic
Answer:

# A Simple Bean
Answer: In this section you will learn more about beans by performing the following actions:
·         Creating a simple bean
·         Compiling the bean
·         Generating a Java Archive (JAR) file
·         Loading the bean into the GUI Builder of the NetBeans IDE
·         Inspecting the bean's properties and events
Your bean will be named SimpleBean. Here are the steps to create it:
Write the SimpleBean code. Put it in a file named SimpleBean.java, in the directory of your choice. Here's the code:
import java.awt.Color;
import java.beans.XMLDecoder;
import javax.swing.JLabel;
import java.io.Serializable;

public class SimpleBean extends JLabel
                        implements Serializable {
    public SimpleBean() {
        setText( "Hello world!" );
        setOpaque( true );
        setBackground( Color.RED );
        setForeground( Color.YELLOW );
        setVerticalAlignment( CENTER );
        setHorizontalAlignment( CENTER );
    }
}
SimpleBean extends the javax.swing.JLabel graphic component and inherits its properties, which makes the SimpleBean a visual component. SimpleBean also implements the java.io.Serializable interface. Your bean may implement either the Serializable or the Externalizable interface.
Create a manifest, the JAR file, and the class file SimpleBean.class. Use the Apache Ant tool to create these files. Apache Ant is a Java-based build tool that enables you to generate XML-based configurations files as follows:
 <?xml version="1.0" encoding="ISO-8859-1"?>

 <project default="build">

  <dirname property="basedir" file="${ant.file}"/>

  <property name="beanname" value="SimpleBean"/>
 <property name="jarfile" value="${basedir}/${beanname}.jar"/>

               <target name="build" depends="compile">
      <jar destfile="${jarfile}" basedir="${basedir}" includes="*.class">
          <manifest>
              <section name="${beanname}.class">
                 <attribute name="Java-Bean" value="true"/>
              </section>
          </manifest>
      </jar>
  </target>

  <target name="compile">
      <javac destdir="${basedir}">
          <src location="${basedir}"/>
      </javac>
  </target>

  <target name="clean">
      <delete file="${jarfile}">
          <fileset dir="${basedir}" includes="*.class"/>
      </delete>
  </target>

            </project>
It is recommended to save an XML script in the build.xml file, because Ant recognizes this file name automatically.
1.      Load the JAR file. Use the NetBeans IDE GUI Builder to load the jar file as follows:
1.      Start NetBeans.
2.      From the File menu select "New Project" to create a new application for your bean. You can use "Open Project" to add your bean to an existing application.
3.      Create a new application using the New Project Wizard.
4.      Select a newly created project in the List of Projects, expand the Source Packages node, and select the Default Package element.
5.      Click the right mouse button and select New|JFrameForm from the pop-up menu.
6.      Select the newly created Form node in the Project Tree. A blank form opens in the GUI Builder view of an Editor tab.
7.      Open the Palette Manager for Swing/AWT components by selecting Palette Manager in the Tools menu.
8.      In the Palette Manager window select the beans components in the Palette tree and press the "Add from JAR" button.
9.      Specify a location for your SimpleBean JAR file and follow the Add from JAR Wizard instructions.
10.  Select the Palette and Properties options from the Windows menu.
11.  Expand the beans group in the Palette window. The SimpleBean object appears. Drag the SimpleBean object to the GUI Builder panel.



# Using The Bean
Answer:  
 bean name = the name that refers to the bean.
Bean class = name of the java class that defines the bean. 
<jsp:setProperty name = “id” property = “someProperty”    value = “someValue” />
 id = the name of the bean as specified in the useBean tag.
property = name of the property to be passed to the bean.
value = value of that particular property .
An variant for this tag is the property attribute can be replaced by an  “ * ”. What this does is that it accepts all the form parameters and thus reduces the need for writing multiple setProperty tags. The only consideration is that the form parameter names should be the same as that of the bean property names.
<jsp:getProperty name = “id” property = “someProperty” />

BEAN SCOPES :
These defines the range and lifespan of the bean.
The different options are :
Page scope :
Any object whose scope is the page will disappear as soon as the current page finishes generating. The object with a page scope may be modified as often as desired within the particular page but the changes are lost as soon as the page exists.
By default all beans have page scope.
Request scope :
Any objects created in the request scope will be available as long as the request object is.  For example if the JSP page uses an jsp:forward tag, then the bean should be applicable in the forwarded JSP also, if the scope defined is of Request scope.
The Session scope :
In JSP terms, the data associated with the user has session scope. A session does not correspond directly to the user; rather, it corresponds with a particular period of time the user spends at a site. Typically, this period is defined as all the visits a user makes to a site between starting and existing his browser.



# Using The Bean in a Servlet
Answer:  

# Using the Bean in a JSP
Answer: To use a bean in a JSP page, three attributes must be supplied - an id, which provides a local name for the bean, the bean's class name, which is used to instantiate the bean if it does not exit, and a scope, which specifies the lifetime of the bean.
There are four scopes available - page, request, session, and application. A page-scoped bean is available only within the JSP page and is destroyed when the page has finished generating its output for the request. A request-scoped bean is destroyed when the response is sent. A session-scoped bean is destroyed when the session is destroyed. An application-scoped bean is destroyed when the web application is destroyed.
This example retrieves a session-scoped bean and makes it available using the id myBean. The bean is automatically created if it does not exist:
    <jsp:useBean id="myBean" class="com.mycompany.MyBean" scope="session" />
If it is necessary to initialize the bean after it is created, the initialization code can be placed in the body of the jsp:useBean action. The body will not be executed if the bean already exists. Here is an example:
    <jsp:useBean id="myBean2" class="com.mycompany.MyBean" scope="session">
        <%-- this body is executed only if the bean is created --%>
   
        <%-- intialize bean properties --%>
        <jsp:setProperty name="myBean2" property="prop1" value="123" />
    </jsp:useBean>
The value of a bean property can be included in the generated output using the jsp:getProperty action:
    <jsp:getProperty name="myBean" property="prop1" />
    <jsp:getProperty name="myBean" property="prop2" />
The jsp:useBean action also declares a local Java variable to hold the bean object. The name of the local variable is exactly the value of the id attribute. Here is an example that accesses the bean within a scriptlet:
    <%
        if (myBean.getProp1() % 2 == 0) {
            out.println("<font color=\"red\">"+myBean.getProp1()+"</font>");
        } else {
            out.println("<font color=\"green\">"+myBean.getProp1()+"</font>");
        }
    %>

# Loading Properties form a Form

# Issues with Tag Libraries