You are on page 1of 35

SUMMER TRAINING REPORT

JAVA ADVANCE FOR WEB DEVELOPMENT

-VERTIKA SRIVASTAVA COMPUTER SCIENCE AND ENGG.


ANAND ENGINEERING COLLEGE

ACKNOWLEDGEMENT
I owe a great many thanks to a great many people who helped and supported me during the writing of this book. My deepest thanks to Lecturer, [LECTURER NAME] the Guide of the project for guiding and correcting various documents of mine with attention and care. He has taken pain to go through the project and make necessary correction as and when needed. I express my thanks to the Principal of, [UNIVERSITY NAME & PLACE], for extending his support. My deep sense of gratitude to [RESPECTIVE NAME] (DESIGNATION), [COMPANY NAME WHERE THE PROJECT WAS UNDERTAKEN] support and guidance. Thanks and appreciation to the helpful people at [COMPANY NAME WHERE THE PROJECT WAS UNDERTAKEN], for their support. I would also thank my Institution and my faculty members without whom this project

would have been a distant reality. I also extend my heartfelt thanks to my family and well

wishers.

INDEX
INTRODUCTION TO JAVA J2EE SWING EVENT HANDLING JAVA DATABASE CONNECTIVITY JAVA BEANS REMOTE METHOD INVOCATION SERVLETS INTER SERVLET COMMUNICATION SESSION TRACKING JAVA SERVER PAGES INTRODUCTION TO ENTERPRISE JAVA BEANS

INTRODUCTION TO JAVA
Java is a programming language initially developed by Sun Microsystems and released as a principal component of Sun Microsystems' Java platform. Although the language gets much of its syntax from C and C++ it has a less complicated object model and lesser low-level services. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture.Java is a general-purpose, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere". Java is currently one of the most standard programming languages in use, and is extensively used from application software to web applications. There were five primary goals in the creation of the Java language : 1. 2. 3. 4. 5. It should be "simple, object-oriented and familiar". It should be "robust and secure". It should be "architecture-neutral and portable". It should execute with "high performance". It should be "interpreted, threaded, and dynamic".

J2EE
Short for Java 2 Platform Enterprise Edition, J2EE is a platform-independent, Javacentric environment from Sun for developing, building and deploying Web-based enterprise applications online. The J2EE platform consists of a set of services, APIs, and protocols that provide the functionality for developing multitiered, Web-based applications. Some of the key features and services of J2EE:

At the client tier, J2EE supports pure HTML, as well as Java applets or applications. It relies on Java Server Pages and servlet code to create HTML or other formatted data for the client. Enterprise JavaBeans (EJBs) provide another layer where the platform's logic is stored. An EJB server provides functions such as threading, concurrency, security and memory management. These services are transparent to the author. Java Database Connectivity (JDBC), which is the Java equivalent to ODBC, is the standard interface for Java databases. The Java servlet API enhances consistency for developers without requiring a graphical user interface.

SWING
Swing is the primary Java GUI widget toolkit. It is part of Sun Microsystems' Java Foundation Classes (JFC) an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit. Swing provides a native look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform. It has more powerful and flexible components than AWT. In addition to familiar components such as buttons, check box and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables and lists. Unlike AWT components, Swing components are not implemented by platform-specific code. Instead they are written entirely in Java and therefore are platform-independent. The term "lightweight" is used to describe such an element. Swing introduced a mechanism that allowed the look and feel of every component in an application to be altered without making substantial changes to the application code. The introduction of support for a pluggable look and feel allows Swing components to emulate the appearance of native components while still retaining the benefits of platform independence. Originally distributed as a separately downloadable library, Swing has been included as part of the Java Standard Edition since release 1.2. The Swing classes and components are contained in the javax.swing package hierarchy.

EXAMPLE
creating complete user interface(login screen) using swing : //import all the swing and awt classes

import javax.swing.*; import java.awt.*; public class login { static JFrame f; JPanel p; JLabel lid,lpwd; JTextField tid;

JPasswordField tpwd; JButton b1,b2; public login() //constructor { p=new JPanel(); f.getContentPane().add(p); //adding the panel to the frame p.setLayout(new GridLayout(3,2)); lid=new JLabel("ENTER USER ID"); lpwd=new JLabel("ENTER PASSWORD"); tid=new JTextField(10); tpwd=new JPasswordField(10); b1=new JButton("LOGIN"); b2=new JButton("RESET"); p.add(lid); p.add(tid); p.add(lpwd); p.add(tpwd); p.add(b1); p.add(b2); }

public static void main(String args[]) { f=new JFrame(LOGIN SYSTEM); login obj=new login(); f.setSize(320,160); f.setVisible(true); } }

EVENT HANDLING
Most programs, to be useful, must respond to commands from the user. To do so, Java programs rely on events that describe user actions. Event Handling is done through the java.awt.*; package of java. Events are the integral part of the java platform. We can see the concepts related to the event handling through this example and used methods through which you can implement the event driven application. public class Beeper ... implements ActionListener { ... //where initialization occurs: button.addActionListener(this); ... public void actionPerformed(ActionEvent e) { ...//Make a beep sound... } } The Beeper class implements the ActionListener interface, which contains one method: actionPerformed. Since Beeper implements ActionListener, a Beeper object can register as a listener for the action events that buttons fire. Once the Beeper has been registered using the Button addActionListener method, the Beeper's actionPerformed method is called every time the button is clicked. The event model, which you saw at its simplest in the preceding example, is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects. For example, a program might create one listener per event source. Or a program might have a single listener for all events from all sources. A program can even have more than one listener for a single kind of event from a single event source.

JDBC
Java DataBase Connectivity, commonly referred to as JDBC, is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. A JDBC-to-ODBC bridge enables connections to any ODBCaccessible data source in the JVM host environment.

JDBC DRIVERS
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests from Java programs to a protocol that the DBMS can understand.

Types
There are commercial and free drivers available for most relational database servers. These drivers fall into one of the following types:

Type 1 that calls native code of the locally available ODBC driver. Type 2 that calls database vendor native library on a client side. This code then talks to database over network. Type 3, the pure-java driver that talks with the server-side middleware that then talks to database. Type 4, the pure-java driver that uses database native protocol.

There is also a type called internal JDBC driver, driver embedded with JRE in Javaenabled SQL databases. It's used for Java stored procedures. This does not belong to the above classification, although it would likely be either a type 2 or type 4 driver (depending on whether the database itself is implemented in Java or not).

FUNCTIONALITY AND IMPLEMENTATION


The JDBC classes are contained in the Java package java.sql and javax.sql. JDBC allows multiple implementations to exist and be used by the same application. The API provides a mechanism for dynamically loading the correct Java packages and registering them with the JDBC Driver Manager. The Driver Manager is used as a connection factory for creating JDBC connections. JDBC connections support creating and executing statements. These may be update statements such as SQL's CREATE, INSERT, UPDATE and DELETE, or they may be query statements such as SELECT. Additionally, stored procedures may be invoked through a JDBC connection. JDBC represents statements using one of the following classes:

Statement the statement is sent to the database server each and every time. PreparedStatement the statement is cached and then the execution path is pre determined on the database server allowing it to be executed multiple times in an efficient manner. CallableStatement used for executing stored procedures on the database.

Update statements such as INSERT, UPDATE and DELETE return an update count that indicates how many rows were affected in the database. These statements do not return any other information. Query statements return a JDBC row result set. The row result set is used to walk over the result set. Individual columns in a row are retrieved either by name or by column number. There may be any number of rows in the result set. The row result set has metadata that describes the names of the columns and their types. There is an extension to the basic JDBC API in the javax.sql. The method Class.forName(String) is used to load the JDBC driver class. Example : Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

used to load the JDBC-ODBC bridge driver. When a Driver class is loaded, it creates an instance of itself and registers it with the DriverManager. Now when a connection is needed, one of the DriverManager.getConnection() methods is used to create a JDBC connection.

Example : try { Connection con = DriverManager.getConnection( "jdbc:somejdbcvendor:other data needed by some jdbc vendor", "myLogin", "myPassword" ); /* you use the connection here */ } con.close(); //closes the connection with the database catch (Throwable ignore) { //action to be taken in case of an exception } The URL used is dependent upon the particular JDBC driver. It will always begin with the "jdbc:" protocol, but the rest is up to the particular vendor. Once a connection is established, a statement can be created. Example : try { Statement stmt = con.createStatement(); stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " ); } con.close(); catch (Throwable ignore) { //action to be taken in case of an exception } Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query : try { Statement st=con.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" );

while ( rs.next() ) { int numColumns = rs.getMetaData().getColumnCount(); for ( int i = 1 ; i <= numColumns ; i++ ) { // Column numbers start at 1. System.out.println( "COLUMN " + i + " = " + rs.getObject(i) ); } } con.close(); catch (Throwable ignore) { //action to be taken in case of an exception }

An example of a PreparedStatement query, using con and class from first example : try { PreparedStatement=con.prepareStatement( "SELECT i.*, j.* FROM Omega i, Zappa j WHERE i.name = ? AND j.num = ?" ); // In the SQL statement being prepared, each question mark is a placeholder // that must be replaced with a value you provide through a "set" method invocation. // The following two method calls replace the two placeholders; the first is // replaced by a string value, and the second by an integer value.

ps.setString(1, "Poor Yorick"); ps.setInt(2, 8008);

// The ResultSet, rs, conveys the result of executing the SQL statement. // Each time you call rs.next(), an internal row pointer, or cursor, // is advanced to the next row of the result. The cursor initially is // positioned before the first row. ResultSet rs = ps.executeQuery();

while ( rs.next() ) { int numColumns = rs.getMetaData().getColumnCount(); for ( int i = 1 ; i <= numColumns ; i++ ) { // Column numbers start at 1. System.out.println( "COLUMN " + i + " = " + rs.getObject(i) ); } // for } // while } con.close(); catch (Throwable ignore) { //action to be taken in case of an exception } If a database operation fails, JDBC raises an SQLException. There is typically very little one can do to recover from such an error, apart from logging it with as much detail as possible. It is recommended that the SQLException be translated into an application domain exception (an unchecked one) that eventually results in a transaction rollback and a notification to the user. Finally to summarize, the following points can be stated : JDBC API provides a database programming interface for Java programs. A Java program can send queries to a database by using the JDBC driver. The java.sql package contains classes that help in connecting to a database, sending SQL ststements to the database and processing the query results. The Connection Object represents a connection with a database. It can be initialized using the getConnection() method of the DriverManager class. The PreparedStatement object allows you to execute parametrized queries. It can be initialized using the prepareStatement() method of the Connection object. The setString() method sets the query parameters of the PreparedStatement object. The executeUpdate() method executes the query statement present in the PreparedStatement object and returns the number of rows affected by the query. The ResultSetMetaData interface is used to obtain information about the columns stored in a ResultSet object.

JAVA BEANS
JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods.

JAVA BEANS CONVENTIONS


In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behaviour. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans. The required conventions are as follows:

The class must have a public default constructor (no-argument). This allows easy instantiation within editing and activation frameworks. The class properties must be accessible using get, set, is (used for boolean properties instead of get) and other methods (so-called accessor methods and mutator methods), following a standard naming-convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. The class should be serializable. It allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion independent of the VM and of the platform.

BASIC BEAN CONCEPTS


Individual Java Beans will vary in functionality, but most share certain common defining features.

Support for introspection allowing a builder tool to analyze how a bean works. Support for customization allowing a user to alter the appearance and behavior of a bean. Support for events allowing beans to fire events, and informing builder tools about both the events they can fire and the events they can handle. Support for properties allowing beans to be manipulated programatically, as well as to support the customization mentioned above. Support for persistence allowing beans that have been customized in an application builder to have their state saved and restored. Typically persistence is used with an application builder's save and load menu commands to restore any work that has gone into constructing an application.

While Beans are intended to be used primarily with builder tools, they need not be. Beans can be manually manipulated by text tools through programatic interfaces. All key APIs, including support for events, properties, and persistence, have been designed to be easily read and understood by human programmers as well as by builder tools. The JavaBeans architecture is based on a component model which enables developers to create software units called components. Components are self-contained, reusable software units that can be visually assembled into composite components, applets, applications, and servlets using visual application builder tools. JavaBean components are known as beans. A set of APIs describes a component model for a particular language. The JavaBeans API specification describes the core detailed elaboration for the JavaBeans component architecture. Beans are dynamic in that they can be changed or customized. Through the design mode of a builder tool you can use the Properties window of the bean to customize the bean and then save (persist) your beans using visual manipulation. You can select a bean from the toolbox, drop it into a form, modify its appearance and behavior, define its interaction with other beans, and combine it and other beans into an applet, application, or a new bean. The following list briefly describes key bean concepts.

Builder tools discover a bean's features (that is, its properties, methods, and events) by a process known as introspection. Beans support introspection in two ways: o By adhering to specific rules, known as design patterns, when naming bean features. The Introspector class examines beans for these design patterns to discover bean features. The Introspector class relies on the core reflection API. The trail Getting Started is an excellent place to learn about reflection. o By explicitly providing property, method, and event information with a related bean information class. A bean information class implements the BeanInfo interface. A BeanInfo class explicitly lists those bean features that are to be exposed to application builder tools. Properties are the appearance and behavior characteristics of a bean that can be changed at design time. Builder tools introspect on a bean to discover its properties and expose those properties for manipulation. Beans expose properties so they can be customized at design time. Customization is supported in two ways: by using property editors, or by using more sophisticated bean customizers. Beans use events to communicate with other beans. A bean that is to receive events (a listener bean) registers with the bean that fires the event (a source bean). Builder tools can examine a bean and determine which events that bean can fire (send) and which it can handle (receive). Persistence enables beans to save and restore their state. After changing a bean's properties, you can save the state of the bean and restore that bean at a later time with the property changes intact. The JavaBeans architecture uses Java Object Serialization to support persistence.

A bean's methods are no different from Java methods, and can be called from other beans or a scripting environment. By default all public methods are exported.

Beans vary in functionality and purpose. You have probably met some of the following beans in your programming practice:

GUI (graphical user interface) Non-visual beans, such as a spelling checker Animation applet Spreadsheet application

BEAN DEVELOPMENT KIT


JavaBeans are reusable software components written in Java. These components may be built into an application using an appropriate building environment. The Bean Development Kit (BDK) from Sun includes a simple example of a building environment which uses beans, called the beanbox, and some sample beans. The BDK The BDK needs to create some directories and copy some files to your filespace before you can use it. So, the first time you want to use the BDK, give the following command: % bdk-user-setup This will create a directory called BDK1.1 and sub-directories BDK1.1/jars and BDK1.1/beanbox together with some links to files in the Bean Development Kit installation directory. Running the BeanBox Change directory to BDK1.1/beanbox and type the command ./run.sh: % cd BDK1.1/beanbox % ./run.sh & The BeanBox starts and loads beans from the JAR (Java Archive) files in the BDK1.1/jars directory. It then displays four windows on the screen:

the ToolBox which lists all beans the BeanBox has found, the BeanBox which is a canvas where you will drop beans and connect them together, the Properties sheet which is used to set the properties of the current bean, the MethodTracer simple debugging facility.

Accessor and mutator methods


JavaBeans require properties to have accessor and mutator methods. A property is another name for a class-wide variable. Accessors provide a standardized way of accessing the value of a property. Mutators provide a standard way to modify the value of a property. In fact, it is good coding practice to provide and use accessor and mutator methods for properties in all Java classes. To make the accessor and mutator methods for a property, the standard practice is to prepend the name of the property with the word 'get' for the get method name and 'set' for the set method name. In the accessor and mutator methods' names, the property name is capitalized, though the property's name should be declared in the lower case. An example of the accessor and mutator methods for a simple variable of type variable_type and name exampleVariable would be:

public void setExampleVariable(variable_type value) public variable_type getExampleVariable()

JAVA BEAN EXAMPLE


1 // The class is serialized for IO operations 2 public class Person implements java.io.Serializable { 3 // attributes declared as private 4 private String name; 5 private boolean deceased; 6 7 8 // Default Constructor 9 public Person() { } 10 11 // getXxxx to access the name attribute 12 public String getName() { 13 return this.name; 14 } 15 16 // setXxxx to mutate the name attribute 17 public void setName(String name) { 18 this.name = name; 19 } 20 21 // isXxxx to access boolean attribute 22 public boolean isDeceased() { 23 return this.deceased; 24 } 25 26 // setXxxx to mutate boolean attribute 27 public void setDeceased(boolean deceased) { 28 this.deceased = deceased; 29 } 30 }

REMOTE METHOD INVOCATION

IDEA :
Rely on the same programming paradigm for distributed applications as for centralized applications In procedural languages, we will rely on the notion of Remote Procedure Call (RPC) In object-oriented language, we will rely on the notion of Remote Method Invocation (RMI)

A remote method (procedure) is transparently invoked (called) across the network, as if it was local

Remote Method Invocation is a powerful technology for developing networked applications without having to worry about the low-level networking details. RMI transcends the client/server model of computing with a more general "remote object" model. In this model, the "server" defines objects that "clients" can use remotely. Clients invoke methods of a remote object exactly as if it were a local object running in the same virtual machine as the client. RMI hides the underlying mechanism for transporting method arguments and return values across the network.

An important limitation of RMI is that it only works when both the client and the server are Java applications. In this way, it is not as general as the CORBA architecture, which is independent of programming language. To develop and execute an RMI application, the following steps are useful: 1. 2. 3. 4. 5. 6. 7. 8. Create the distributed object interface Create and compile the distributed object implementation Generate the "stub" class with rmic Create and compile the server that "hosts" a distributed object Create and compile the client that "binds" to the distributed object Start the RMI naming service (rmiregistry) Start the server Start the client

1. Create the distributed object interface


A Java interface will server as the "IDL" for remote objects. The first step is to create an interface that extends the java.rmi.Remote interface . This interface defines the exported methods that the remote object implements (i.e., the methods the "server" implements and "clients" can invoke remotely). Each method in this interface must be declared to throw a java.rmi.RemoteException (the superclass of many more specific RMI exception classes) . This is necessary because there are quite a few things that can go wrong during the remote method invocation process over a network.

2. Create and compile the distributed object implementation


The first step established an interface only. This second step creates an implementation of that interface. A suggested naming convention uses the same name as the interface with an "Impl" or "_i" suffix. The class extends the java.rmi.server.UnicastRemoteObject class , and, implements the "IDL" interface . This step routinely consists of:

Adding the private attributes necessary to support the public interface Adding constructors and other member functions not intended to be called by distributed clients Defining the implementation of all member functions

Notice that the added constructor must be declared to throws RemoteException . "Other than declaring its remote methods to throw RemoteException objects, the remote object does not need to do anything special to allow its methods to be invoked remotely. The UnicastRemoteObject and the rest of the RMI infrastructure handle this automatically."

3. Generate the "stub" class


With RMI, the client and server do not communicate directly. On the client side, the client's reference to a remote object is implemented as an instance of a "stub" class. When the client invokes a remote method, it is a method of this stub object that is actually called. The stub does the necessary networking to pass that invocation to a "skeleton" class on the server. This skeleton translates the networked request into a method invocation on the server object, and passes the return value back to the stub, which passes it back to the client. This can be a complicated system, but fortunately, application programmers never have to think about stubs and skeletons; they are generated automatically by the rmic tool. Invoke rmic with the name of the distributed object class C:> rmic -v1.2 RMIcountImpl The old 1.1 architecture creates two ".class" files with the suffixes _Stub and _Skel. If you will only ever need support for version 1.2 clients, rmic can be run with the -v1.2 option. This will generate just the _Stub class file (apparently the _Skel class file is no longer necessary).

4. Create and compile the server


The "remote object" is not capable of functioning as a stand-alone, disembodied object. It must be "hosted" by a Java application. This application is called the "server". It creates an instance of the remote object, and then "exports" that object (makes it available for use by clients) by registering the object by name with a registry service. This is usually done with bind() or rebind() from the java.rmi.Naming class and the rmiregistry program (see step 6). The string chosen as the name can be quite arbitrary, as long as the server and all clients use the same string. Using rebind() is usually more convenient because it will not fail if the string chosen already exists in the binding database. This will happen if the server executable goes away for some reason, and then is relaunched while the rmiregistry executable continues to run. A server program may also act as its own registry server by using the LocateRegistry class and Registry interface of the java.rmi.registry package.

5. Create and compile the client


The next step is to write a client program that uses the remote object exported by the server. The client must first obtain a reference to the remote object by using the Naming class to look up the object by name. The name is typically a URL with an "rmi:" protocol prefix. The remote reference that is returned is an instance of the "IDL" interface base class for the object (or more specifically, a "stub" object for the remote object). Once the client has this remote object, it can invoke methods on it exactly as it would invoke the methods of a local object. The only thing that it must be aware of is

that all remote methods can throw RemoteException objects, and that in the presence of network errors, this can happen at unexpected times. RMI uses Java's serialization mechanism to transfer the stub object from the server to the client. Because a client may load an untrusted stub object, it should have a security manager installed to prevent a malicious (or just buggy) stub from deleting files or otherwise causing harm. The RMISecurityManager class is a suitable security manager that all RMI servers and clients should install. [Note: RMI did not work until I opened up all permissions to all users in the file Q:\cpp\java\jdk1.2\jre\lib\security\java.policy.]

6. Start the RMI naming service (rmiregistry)


If the server uses the default registry service provided by the Naming class, you must run the registry server (if it is not already running). The CLASSPATH environment variable needs to reflect the location of the .class files generated so far. The commands below show how to append the current directory to the end of CLASSPATH's current value, and how to launch a new DOS window that is executing rmiregistry. C:> set CLASSPATH=%CLASSPATH%;. C:> start rmiregistry

7. Start the server


The server can be launched in a new DOS window with the first command below. To watch the server activity, start the server with the second command. The CLASSPATH environment variable needs to include the directory containing the stub file when rmiregistry is run, or, the server needs to specify the java.rmi.server.codebase property to indicate the location of the stub file (third command). C:> start java RMIcountServer C:> start java -Djava.rmi.server.logCalls=true RMIcountServer C:> java -Djava.rmi.server.codebase=file:///myDir/mySubDir/ RMIcountServer Note that the trailing '/' is required. This is so that the implementation can resolve (find) the class definition(s) properly. If your server has hung, you can get a monitor dump and thread dump by doing a <Ctrl>-<Break> in Windows.

8. Start the client


It can take up to a minute for the server to successfully register its "remote object" with the registry service. If the client tries to lookup() the remote object before the registration has completed, the client will receive an exception. For this reason, it is a good idea to have the server print a message to standard-out when its registration request has completed. When the message appears, the client can now be started with the comand java RMIcountClient.

RMI FOR DISTRIBUTED APPLICATIONS :


RMI applications often comprise two separate programs, a server and a client. A typical server program creates some remote objects, makes references to these objects accessible, and waits for clients to invoke methods on these objects. A typical client program obtains a remote reference to one or more remote objects on a server and then invokes methods on them. RMI provides the mechanism by which the server and the client communicate and pass information back and forth. Such an application is sometimes referred to as a distributed object application. Distributed object applications need to do the following: Locate remote objects. Applications can use various mechanisms to obtain references to remote objects. For example, an application can register its remote objects with RMI's simple naming facility, the RMI registry. Alternatively, an application can pass and return remote object references as part of other remote invocations. Communicate with remote objects. Details of communication between remote objects are handled by RMI. To the programmer, remote communication looks similar to regular Java method invocations. Load class definitions for objects that are passed around. Because RMI enables objects to be passed back and forth, it provides mechanisms for loading an object's class definitions as well as for transmitting an object's data.

RMI is a distributed object system that enables you to easily develop distributed Java applications. Developing distributed applications in RMI is simpler than developing with sockets since there is no need to design a protocol, which is an error-prone task. In RMI, the developer has the illusion of calling a local method from a local class file, when in fact the arguments are shipped to the remote target and interpreted, and the results are sent back to the callers. Developing a distributed application using RMI involves the following steps: 1. 2. 3. 4. 5. Define a remote interface Implement the remote interface Develop the server Develop a client Generate Stubs and Skeletons, start the RMI registry, server, and client

SERVLETS

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. Thus, it can be thought of as a Java Applet that runs on a server instead of a browser. A Servlet is a Java class in Java EE that conforms to the Java Servlet API, a protocol by which a Java class may respond to requests. They are not tied to a specific client-server protocol, but are most often used with the HTTP protocol. Therefore, the word "Servlet" is often used in the meaning of "HTTP Servlet". Thus, a software developer may use a servlet to add dynamic content to a Web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to non-Java dynamic Web content technologies such as CGI and ASP.NET. Servlets can maintain state in session variables across many server transactions by using HTTP cookies, or URL rewriting. To deploy and run a Servlet, a Web container must be used. A Web container is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. The servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of the Web container and a servlet. A Servlet is an object that receives a request and generates a response based on that request. The basic servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment. The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the Web server and a client. Servlets may be packaged in a WAR file as a Web application. Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler. The difference between Servlets and JSP is that Servlets typically embed HTML inside Java code, while JSPs embed Java code in HTML. While the direct usage of Servlets to generate HTML (as shown in the example below) is relatively rare nowadays, the higher level MVC web framework in Java EE (JSF) still explicitly uses the Servlet technology for the low level request/response handling via the FacesServlet. A somewhat older usage is to use servlets in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model-view-controller pattern.

LIFE CYCLE OF A SERVLET:

1. The container calls the no-arg constructor. 2. The Web container calls the init() method. This method initializes the servlet and must be called before life of a servlet, the init() method is called only once. 3. After initialization, the servlet can service client requests. Each request is serviced in its own separate thread. The Web container calls the service() method of the servlet for every request. The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester. 4. Finally, the Web container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet. Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ). They are implemented by every servlet and are invoked at specific times by the server. Let us consider a typical user scenario to understand when these methods are called. 1. Assume that a user enters a Uniform Resource Locator (URL) to a web browser. o The browser then generates an HTTP request for this URL. o This request is then sent to the appropriate server. 2. The HTTP request is received by the web server. o The server maps this request to a particular servlet. o The servlet is dynamically retrieved and loaded into the address space of the server. 3. The server invokes the init() method of the servlet. o This method is invoked only when the servlet is first loaded into memory. o It is possible to pass initialization parameters to the servlet so it may configure itself. 4. The server invokes the service() method of the servlet. o This method is called to process the HTTP request. o You will see that it is possible for the servlet to read data that has been provided in the HTTP request. o It may also formulate an HTTP response for the client.

5. The servlet remains in the servers address space and is available to process any other HTTP requests received from clients. o The service() method is called for each HTTP request. 6. The server may, at some point, decide to unload the servlet from its memory. o The algorithms by which this determination is made are specific to each server. 7. The server calls the destroy() method to relinquish any resources such as file handles that are allocated for the servlet; important data may be saved to a persistent store. 8. The memory allocated for the servlet and its objects can then be garbage collected.

Example:
The following example servlet prints a "Hello world" HTML page. Note that HttpServlet is a subclass of GenericServlet, an implementation of the Servlet interface. The service() method dispatches requests to the methods doGet(), doPost(), doPut(), doDelete(), and so on; according to the HTTP request. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<html>\n" + "<head><title>Hello World</title></head>\n" +

"<body>\n" + "<h1>Hello, world!</h1>\n" + "</body></html>"); } }

Usage:
Servlets are most often used to

process or store data that was submitted from an HTML form provide dynamic content such as the results of a database query manage state information that does not exist in the stateless HTTP protocol, such as filling the articles into the shopping cart of the appropriate customer

INTER SERVLET COMMUNICAION:


What is Inter Servlet Communication?

A process where two or more servlets communicates with each other to process the client request. A servlet can forward the request to another servlet to process the client request. A servlet can include the output of another servlet to process the client request.

How to do Inter Servlet Communication?


Inter-servlet communication is done using Request Dispatcher A Request Dispatcher: o Is an object of the javax.servlet.RequestDispatcher interface that allows inter-servlet communication. o Object is used to include the content of another servlet. o Object is used to forward the request to another servlet. This interface is present in the javax.servlet package and contains only following two methods : o forward(ServletRequest request, ServletResponse response) Forwards a request to another resource on the same server. That resource can be a Servlet, JSP page or a simple HTML page. o include(ServletRequest request, ServletResponse response) Works like a server-side include ( SSI ) and includes the response from the given resource ( Servlet, JSP page, HTML page ) within the caller response. In order to use forward() or include() methods we discussed above we will have to get a reference to RequestDispatcher interface. There are two ways you can do this : o ServletContext.getRequestDispatcher(String resource)

ServletRequest.getRequestDispatcher(String resource)

SESSION TRACKING
There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce. When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying? There are three typical solutions to this problem. 1. Cookies. You can use HTTP cookies to store information about a shopping session, and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine. This is an excellent alternative, and is the most widely used approach. However, even though servlets have a high-level and easy-to-use interface to cookies, there are still a number of relatively tedious details that need to be handled: o Extracting the cookie that stores the session identifier from the other cookies (there may be many, after all), o Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably should be reset), and o Associating information on the server with the session identifier (there may be far too much information to actually store it in the cookie, plus sensitive data like credit card numbers should never go in cookies).

2. URL Rewriting. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it works with browsers that don't support cookies or where the user has disabled cookies. However, it has most of the same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do. In addition, you have to be very careful that every URL returned to the user (even via indirect means like Location fields in server redirects) has the extra information appended. And, if the user leaves the session and comes back via a bookmark or link, the session information can be lost.

3. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier. Servlets provide an outstanding technical solution: the HttpSession API. This is a highlevel interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies if the browser supports them, but automatically revert to URL-rewriting when cookies are unsupported or explicitly disabled. But the servlet author doesn't need to bother with many of the details, doesn't have to explicitly manipulate cookies or information appended to the URL, and is automatically given a convenient place to store data that is associated with each session.

JAVA SERVER PAGES


Java Server Pages is a technology which permits software developers to create dynamic request like HTML, XML in order to answer to client request in the net. This technology lets Java code and definite pre-defined procedures to be implanted into static content. The syntax in Java Server Pages includes a supplementary XML tag which is known as JSP actions. It is made use to evoke the utility of the built-in functions. Moreover JSP permits to establish and form the JSP tag libraries which operate as an extension to the standard XML or HTML tags. These JSP tag libraries give a good technique to widen the potentiality of the Web server by providing an independent platform. JSP compiler compiles the JSPs into Java Servlets. A JSP compiler may possibly create a servlet in Java code and it is later compiled by the Java compiler. It might even directly produce the byte code for the servlet. Java Server Pages can be examined as a high level abstraction of servlets which is practiced as an extension of the Servlet2.1 API. The Java Server Pages and the Servlets were initially developed at Sun Microsystems. Opening with version 1.2 of the Java Server Page specification the JSPs have been built under the Java Community Process. There are quite a few JSP implicit objects that are represented by the JSP container and it could be mentioned and indicated by the programmers. o Config - It gives the data of the servlet configuration. o Application - Data's are shared by the servlets and Java Server Pages in the application. o Exception - Exceptions are not trapped by the codes in the application. o Out - The data's are written with the help of JSP Writer to the response stream.

o Request - Here the Hypertext Transfer Protocol request the object. o Response - Here the Hypertext Transfer Protocol response the object o Session - It is helpful to trace the data's and information about a user from one request to another request.

There are several actions that are performed in JSP actions. A JSP action is nothing but a XML tags that invokes functionality of the built-in web server. Some of the JSP action is given as follows. Jsp:param - It indicates a parameter which will be added in addition to the request of the existing parameters. It is used inside the jsp:params or jsp:include, jsp:forward blocks Jsp:include - Java Servlet provisionally gives the request and response off to the specific Java Server Page. The Control will later come again to the existing JSP as soon as the other JSP has completed. With the help of this the JSP code will be distributed among several other JSPs rather than replica. Jsp:forward - This JSP action is used to give off the request/response to the other servlet or JSP. The control will not come back to the existing JSP. Jsp:plugin - The ancient version of web browsers like Internet Explorer and Netscape Navigator use various tags to embed an applet. This action creates the definite tags that are required for a browser to include an applet. Jsp:fallback - This action is used to confirm that if the browser never gives support to applets. Jsp:getProperty - It obtains a property from the specific JavaBean. Jsp:setProperty - It sets a property in the specific JavaBean.

JavaServer Pages (JSP) lets you separate the dynamic part of your pages from the static HTML. You simply write the regular HTML in the normal manner, using whatever Web-page-building tools you normally use. You then enclose the code for the dynamic parts in special tags, most of which start with "<%" and end with "%>". For example, here is a section of a JSP page that results in something like "Thanks for ordering Core Web Programming" for a URL of http://host/OrderConfirmation.jsp?title=Core+Web+Programming: Thanks for ordering <I><%= request.getParameter("title") %></I> You normally give your file a .jsp extension, and typically install it in any place you could place a normal Web page. Although what you write often looks more like a regular HTML file than a servlet, behind the scenes, the JSP page just gets converted to a normal servlet, with the static HTML simply being printed to the output stream associated with the servlet's service method. This is normally done the first time the page is requested, and developers can simply request the page themselves when first installing it if they want to be sure that the first real user doesn't get a momentary delay when the JSP page is translated to a servlet and the servlet is compiled and loaded. Note also that many Web servers let you define aliases that so that a URL that appears to reference an HTML file really points to a servlet or JSP page. Aside from the regular HTML, there are three main types of JSP constructs that you embed in a page: scripting elements, directives, and actions. Scripting elements let you specify Java code that will become part of the resultant servlet, directives let you control the overall structure of the servlet, and actions let you specify existing components that should be used, and otherwise control the behavior of the JSP engine. To simplify the scripting elements, you have access to a number of predefined variables such as request in the snippet above.

Syntax Summary:
JSP Element JSP Expression JSP Scriptlet JSP Declaration JSP page Directive JSP include Directive Syntax Interpretation Expression is evaluated and placed in output. Code is inserted in service method. Code is inserted in body of servlet class, outside of service method. Directions to the servlet engine about general setup.

<%= expression %> <% code %> <%! code %> <%@ page att="val" %>

A file on the local system to be included <%@ include file="url" when the JSP page is translated into a %> servlet.

JSP Comment The jsp:include Action

<%-- comment --%> <jsp:include page="relative URL" flush="true"/>

Comment; ignored when JSP page is translated into servlet. Includes a file at the time the page is requested.

The jsp:useBean Action

<jsp:useBean att=val*/> or <jsp:useBean att=val*> Find or build a Java Bean. ... </jsp:useBean> Set bean properties, either explicitly or by designating that value comes from a request parameter.

The jsp:setProperty Action The jsp:getProperty Action The jsp:forward Action

<jsp:setProperty att=val*/> <jsp:getProperty

Retrieve and output bean properties. name="propertyName" value="val"/> <jsp:forward page="relative URL"/> <jsp:plugin attribute="value"*> ... </jsp:plugin> Forwards request to another page. Generates OBJECT or EMBED tags, as appropriate to the browser type, asking that an applet be run using the Java Plugin.

The jsp:plugin Action

JSP Scripting Elements:


JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms: 1. Expressions of the form <%= expression %> that are evaluated and inserted into the output, 2. Scriptlets of the form <% code %> that are inserted into the servlet's service method, and 3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.

JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the following form: <%@ directive attribute="value" %> However, you can also combine multiple attribute settings for a single directive, as follows: <%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %> There are two main types of directive: page, which lets you do things like import classes, customize the servlet superclass, and the like; and include, which lets you insert a file into the servlet class at the time the JSP file is translated into a servlet. The specification also mentions the taglib directive, which is not supported in JSP version 1.0, but is intended to let JSP authors define their own tags. It is expected that this will be the main new contribution of JSP 1.1.

Predefined Variables:
To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined variables, sometimes called implicit objects. The available variables are request, response, out, session, application, config, pageContext, and page. Details for each are given below. request This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never done in practice. response This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client. out

This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly. session This is the HttpSession object associated with the request. Recall that sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session attribute of the page directive to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet. application This is the ServletContext as obtained via getServletConfig().getContext(). config This is the ServletConfig object for this page. pageContext JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher performance JspWriters. The idea is that, if you access them through this class rather than directly, your code will still run on "regular" servlet/JSP engines. page This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java.

Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include:

jsp:include - Include a file at the time the page is requested. jsp:useBean - Find or instantiate a JavaBean. jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the property of a JavaBean into the output.

jsp:forward - Forward the requester to a new page. jsp:plugin - Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.

INTRODUCTION TO EJB
Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular construction of enterprise applications. The EJB specification is one of several Java APIs in the Java EE specification. EJB is a server-side model that encapsulates the business logic of an application. The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999[1] and enhanced under the Java Community Process as JSR 19 (EJB 2.0), JSR 153 (EJB 2.1), JSR 220 (EJB 3.0) and JSR 318 (EJB 3.1). The EJB specification intends to provide a standard way to implement the back-end 'business' code typically found in enterprise applications (as opposed to 'front-end' interface code). Such code addresses the same types of problems, and solutions to these problems are often repeatedly re-implemented by programmers. Enterprise JavaBeans are intended to handle such common concerns as persistence, transactional integrity, and security in a standard way, leaving programmers free to concentrate on the particular problem at hand. Accordingly, the EJB specification details how an application server provides:

Transaction processing Integration with the Persistence services offered by the Java Persistence API (JPA) Concurrency control Events using Java Message Service Naming and directory services (JNDI) Security (Java Cryptography Extension (JCE) and JAAS) Deployment of software components in an application server Remote procedure calls using RMI-IIOP. Exposing business methods as Web Services Asynchronous method invocation Timer service

Additionally, the Enterprise JavaBean specification defines the roles played by the EJB container and the EJBs as well as how to deploy the EJBs in a container. Note that the current EJB specification does not detail how an application server provides persistence (a task delegated to the JPA specification), but instead details how business logic can easily integrate with the persistence services offered by the application server.

To deploy and run EJB beans, a Java EE Application server can be used, as these include an EJB container by default. Alternatively, a standalone container such as OpenEJB can be used.

Types:
An EJB container holds two major types of beans:

Session Beans that can be either "Stateful", "Stateless" or "Singleton" and can be accessed via either a Local (same JVM) or Remote (different JVM) interface or directly without an interface, in which case local semantics apply. All session beans support asynchronous execution for all views (local/remote/no-interface). Message Driven Beans (also known as MDBs or Message Beans). MDBs also support asynchronous execution, but via a messaging paradigm.

REFERENCE: SUN MICROSYSTEMS AND NIIT COURSE MATERIAL FOR JAVA ADVANCE AND INTERNET.

You might also like