Wednesday, 27 July 2016

RMI Remote Method Invocation

RMI Remote Method Invocation

The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine. RMI provides for remote communication between programs written in the Java programming language.

Client-Server Review 
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:
1. 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.

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

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

The following illustration depicts an RMI distributed application that uses the RMI registry to obtain a reference to a remote object. The server calls the registry to associate (or bind) a name with a remote object. The client looks up the remote object by its name in the server's registry and then invokes a method on it. The illustration also shows that the RMI system uses an existing web server to load class definitions, from server to client and from client to server, for objects when needed. 

Remote Procedure Calls 
Using RMI to develop a distributed application involves these general steps: 
1. Designing and implementing the components of your distributed application. 
2. Compiling sources. 
3. Making classes network accessible. 
4. Starting the application. 

Remote Method Invocation 
Like any other Java application, a distributed application built by using Java RMI is made up of interfaces and classes. The interfaces declare methods. The classes implement the methods declared in the interfaces and, perhaps, declare additional methods as well. In a distributed application, some implementations might reside in some Java virtual machines but not others. Objects with methods that can be invoked across Java virtual machines are called remote objects. 

An object becomes remote by implementing a remote interface, which has the following characteristics:
1. A remote interface extends the interface java.rmi.Remote.
2. Each method of the interface declares java.rmi.RemoteException in its throws clause, in addition to any application-specific exceptions.

RMI treats a remote object differently from a non-remote object when the object is passed from one Java virtual machine to another Java virtual machine. Rather than making a copy of the implementation object in the receiving Java virtual machine, RMI passes a remote stub for a remote object. The stub acts as the local representative, or proxy, for the remote object and basically is, to the client, the remote reference. The client invokes a method on the local stub, which is responsible for carrying out the method invocation on the remote object.

A stub for a remote object implements the same set of remote interfaces that the remote object implements. This property enables a stub to be cast to any of the interfaces that the remote object implements. However, only those methods defined in a remote interface are available to be called from the receiving Java virtual machine.

First, determine your application architecture, including which components are local objects and which components are remotely accessible. This step includes:

1. Defining the remote interfaces. A remote interface specifies the methods that can be invoked remotely by a client. Clients program to remote interfaces, not to the implementation classes of those interfaces. The design of such interfaces includes the determination of the types of objects that will be used as the parameters and return values for these methods. If any of these interfaces or classes do not yet exist, you need to define them as well.

2. Implementing the remote objects. Remote objects must implement one or more remote interfaces. The remote object class may include implementations of other interfaces and methods that are available only locally. If any local classes are to be used for parameters or return values of any of these methods, they must be implemented as well.

3. Implementing the clients. Clients that use remote objects can be implemented at any time after the remote interfaces are defined, including after the remote objects have been deployed.

RMI Architecture 
The General RMI Architecture
1. The server must first bind its name to the registry
2. The client lookup the server name in the registry to establish remote references.
3. The Stub serializing the parameters to skeleton, the skeleton invoking the remote method and serializing the result back to the stub.
• A client invokes a remote method, the call is first forwarded to stub.
• The stub is responsible for sending the remote call over to the server-side skeleton
• The stub opening a socket to the remote server, marshaling the object parameters and forwarding the data stream to the skeleton.
• A skeleton contains a method that receives the remote calls, unmarshals the parameters, and invokes the actual remote object implementation.

Remote Interfaces

RMI Registry 
Start the RMI registry
1. The RMI applications need install to Registry. And the Registry must start manual by call rmiregisty. 2. The rmiregistry us uses port 1099 by default. You can also bind rmiregistry to a different port by indicating the new port number as :

rmiregistry <new port>

           
            elpis:~/rmi> rmiregistry

3. Remark: On Windows, you have to type in from the command line:
            > start rmiregistry

Deployment and Implementation Steps for Developing an RMI System
1. Define the remote interface
2. Develop the remote object by implementing the remote interface.
3. Develop the client program.
4. Compile the Java source files.
5. Generate the client stubs and server skeletons.
6. Start the RMI registry.
7. Start the remote server objects.
8. Run the client
1. To create an RMI application, the first step is the defining of a remote interface between the client and server objects.
/* SampleServer.java */
import java.rmi.*;
public interface SampleServer extends Remote
{
public int sum(int a,int b) throws RemoteException;
}
2. Develop the remote object and its interface
• The server is a simple unicast remote server.
• Create server by extending java.rmi.server.UnicastRemoteObject.
• The server uses the RMISecurityManager to protect its resources while engaging in remote communication.
/* SampleServerImpl.java */
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
public class SampleServerImpl extends UnicastRemoteObject
implements SampleServer
{
SampleServerImpl() throws RemoteException
{
super();
}
• Implement the remote methods
/* SampleServerImpl.java */
public int sum(int a,int b) throws RemoteException
{
return a + b;
}
}
• The server must bind its name to the registry, the client will look up the server name.
• Use java.rmi.Naming class to bind the server name to registry. In this example the name call “SAMPLE-SERVER”.
• In the main method of your server object, the RMI security manager is created and installed.
/* SampleServerImpl.java */
public static void main(String args[])
{
try
{
System.setSecurityManager(new RMISecurityManager());
//set the security manager
//create a local instance of the object
SampleServerImpl Server = new SampleServerImpl();
//put the local instance in the registry
Naming.rebind("SAMPLE-SERVER" , Server);
System.out.println("Server waiting.....");
}
catch (java.net.MalformedURLException me) {
System.out.println("Malformed URL: " + me.toString()); }
catch (RemoteException re) {
System.out.println("Remote exception: " + re.toString()); }
}
3. Develop the client program
• In order for the client object to invoke methods on the server, it must first look up the name of server in the registry. You use the java.rmi.Naming class to lookup the server name.
• The server name is specified as URL in the from ( rmi://host:port/name )
• Default RMI port is 1099.
• The name specified in the URL must exactly match the name that the server has bound to the registry. In this example, the name is “SAMPLE-SERVER”
• The remote method invocation is programmed using the remote interface name (remoteObject) as prefix and the remote method name (sum) as suffix.
import java.rmi.*; import java.rmi.server.*;
public class SampleClient
{
public static void main(String[] args)
{
// set the security manager for the client
System.setSecurityManager(new RMISecurityManager());
//get the remote object from the registry
try
{
System.out.println("Security Manager loaded");
String url = "//localhost/SAMPLE-SERVER";
SampleServer remoteObject = (SampleServer)Naming.lookup(url);
System.out.println("Got remote object");
System.out.println(" 1 + 2 = " + remoteObject.sum(1,2) );
}
catch (RemoteException exc) {
System.out.println("Error in lookup: " + exc.toString()); }
catch (java.net.MalformedURLException exc) {
System.out.println("Malformed URL: " + exc.toString()); }
catch (java.rmi.NotBoundException exc) {
System.out.println("NotBound: " + exc.toString());
} } }
4&5. Compile the Java source files & Generate the client stubs and server skeletons
• Assume the program compile and executing at elpis on ~/rmi
• Once the interface is completed, you need to generate stubs and skeleton code. The RMI system provides an RMI compiler (rmic) that takes your generated interface class and procedures stub code on its self.
elpis:~/rmi> set CLASSPATH=”~/rmi”
elpis:~/rmi> javac SampleServer.java
elpis:~/rmi> javac SampleServerImpl.java
elpis:~/rmi> rmic SampleServerImpl
elpis:~/rmi> javac SampleClient.java
6. Start the RMI registry
• The RMI applications need install to Registry. And the Registry must start manual by call rmiregisty.
• The rmiregistry us uses port 1099 by default. You can also bind rmiregistry to a different port by indicating the new port number as : rmiregistry
elpis:~/rmi> rmiregistry
• Remark: On Windows, you have to type in from the command line:
> start rmiregistry
7&8. Start the remote server objects & Run the client
• Once the Registry is started, the server can be started and will be able to store itself in the Registry.
• Because of the grained security model in Java 2.0, you must setup a security policy for RMI by set java.security.policy to the file policy.all
elpis:~/rmi> java –Djava.security.policy=policy.all SampleServerImpl
elpis:~/rmi> java –Djava.security.policy=policy.all SampleClient

Tuesday, 26 July 2016

JNI-CORBA

JNI/CORBA

In computing, the Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call and be called by native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.

The Common Object Request Broker Architecture (CORBA) is a standard defined by the Object Management Group (OMG) designed to facilitate the communication of systems that are deployed on diverse platforms.

JNI Basics

The Java Native Interface (JNI) is a programming framework that allows Java code running in a Java Virtual Machine (JVM) to call and to be called by native applications (programs specific to a hardware and operating system platform) and libraries written in other languages, such as C, C++ and assembly.
Native methods are functions written in a language other than Java. it could be C, C++, or even assembly. These function implementation are compiled into a dynamic link library(on Solaris, called shared objects.(.os's) ; on Win32, called dynamic link libraries(dlls)), which the operating system magically loads and links into the process that is running the Java Virtual Machine.

Why use JNI?

Answer: JNI is an acronym of Java Native Interface. Using JNI, we can call functions which are written in other languages from Java. Advantages and disadvantages of this method are as follows:
The standard Java class libraries do not support the platform-dependent features needed by the application.

You might need to set some device-specific properties under program control, or access a device-specific API.
The Java Native Interface (JNI) comes with the standard Java Development Kit (JDK) from Sun Microsystems. It permits Java programmers to integrate native code (currently C and C++) into their Java applications.

JNI allows one to write native methods to handle situations when an application cannot be written entirely in the Java programming language e.g. when the standard Java Class Library does not support the platform-specific features or program library. It is also used to modify an existing application, written in another programming language, to be accessible to Java applications. Many of the standard library classes depend on JNI to provide functionality to the developer and the user, e.g. I/O file reading and sound capabilities. Including performance- and platform-sensitive API implementations in the standard library allows all Java applications to access this functionality in a safe and platform-independent manner. Before resorting to using JNI, developers should make sure the functionality is not already provided in the standard libraries.
The JNI framework lets a native method utilize Java objects in the same way that Java code uses these objects. A native method can create Java objects and then inspect and use these objects to perform its tasks. A native method can also inspect and use objects created by Java application code.
JNI is sometimes referred to as the "escape hatch" for Java developers because it allows them to add functionality to their Java application that the standard Java APIs cannot otherwise provide. It can be used to interface with code written in other languages, such as C and C++. It is also used for time-critical calculations or operations like solving complicated mathematical equations, since native code can be faster than

JVM code. class Test1
{
static
{
System.loadLibrary("TestDll");
}
public static void main(String ar[])
{
System.out.println("Hello world from Java");
Test1 t=new Test1();
t.inDll();
}
public native void inDll();
}
In static block, we are loading a DLL named TestDll.dll which should be placed in /SYSTEM32 directory. I am not saying you cannot put this DLL in other directories, you can, but then you will have to register that path in JVM. Here you can call another method as well, instead of loadLibrary().

The Java Code (Native Keyword)

Answer: Native is a Java keyword that is used in method declarations to specify that the method will not be implemented in another language, not in Java. This keyword signals to the Java compiler that the function is a native language function i.e. its implementation for is written in another programming language because of the native keyword. For example you can write machine-dependent C code and invoke it from Java.
# JNI Architecture
# The C/C++ Side
# Type Encoding
# Name Resolution
# Name Munging
# Native Method Arguments
# The JNIEnv*
Answer: In each native call JNIEnv argument is only valid during the call. To use the argument outside the call you need to use AttachCurrentThread and DetachCurrentThread, like so:
JNIEnv *env;
(*g_vm)->AttachCurrentThread (g_vm, (void **) &env, NULL);
// do stuff
(*g_vm)->DetachCurrentThread (g_vm);
# Field Access
# Method Callbacks

Practice Lab (JNI)

Answer: In the JNI framework, native functions are implemented in separate .c or .cpp files. (C++ provides a slightly cleaner interface with JNI). When the JVM invokes the function, it passes a JNIEnv pointer, a jobject pointer, and any Java arguments declared by the Java method. A JNI function may look like this:
JNIEXPORT void JNICALL Java_ClassName_MethodName
(JNIEnv *env, jobject obj)
{
/*Implement Native Method Here*/
}
The env pointer is a structure that contains the interface to the JVM. It includes all of the functions necessary to interact with the JVM and to work with Java objects. Example JNI functions are converting native arrays to/from Java arrays, converting native strings to/from Java strings, instantiating objects, throwing exceptions, etc. Basically, anything that Java code can do can be done using JNIEnv, albeit with considerably less ease.
For example, the following converts a Java string to a native string:
//C++ code
JNIEXPORT void JNICALL Java_ClassName_MethodName
(JNIEnv *env, jobject obj, jstring javaString)
{
//Get the native string from javaString
const char *nativeString = env->GetStringUTFChars(javaString, 0);
//Do something with the nativeString
//DON'T FORGET THIS LINE!!!
env->ReleaseStringUTFChars(javaString, nativeString);
} /*C code*/
JNIEXPORT void JNICALL Java_ClassName_MethodName
(JNIEnv *env, jobject obj, jstring javaString)
{
/*Get the native string from javaString*/
const char *nativeString = (*env)->GetStringUTFChars(env,
javaString, 0);
/*Do something with the nativeString*/
/*DON'T FORGET THIS LINE!!!*/
(*env)->ReleaseStringUTFChars(env, javaString, nativeString);
}
Note that C++ JNI code is syntactically slightly cleaner than C JNI code because like Java, C++ uses object method invocation semantics. That means that in C, the env parameter is dereferenced using (*env)-> and env has to be explicitly passed to JNIEnv methods. In C++, the env parameter is dereferenced using env-> and the env parameter is implicitly passed as part of the object method invocation semantics.
Native data types can be mapped to/from Java data types. For compound types such as objects, arrays and strings the native code must explicitly convert the data by calling methods in the JNIEnv.

# CORBA
# The CORBA Architecture
# Interface Definition Language

Java IDL

Answer: The Interface Definition Language provides the primary way of describing data types in CORBA. IDL is independent of any particular programming language. Mappings, or bindings, from IDL to specific programming languages are defined and standardized as part of the CORBA specification. At the time of this writing, standard bindings for C, C++, Smalltalk, Ada, COBOL, and Java have been approved by the OMG. The Java IDL API, introduced in Version 1.2 of the Java 2 platform, provides an interface between Java programs and distributed objects and services built using the Common Object Request Broker Architecture (CORBA). CORBA is a standard defined by the Object Management Group (OMG). It describes an architecture, interfaces, and protocols that distributed objects can use to interact with each other. Part of the CORBA standard is the Interface Definition Language (IDL), which is an implementation-independent language for describing the interfaces of remote-capable objects. There are standard mappings defined by the OMG for converting IDL interfaces into C++ classes, C code, and Java classes, among other things. These generated classes use the underlying CORBA framework to communicate with remote clients and give you the basis for implementing and exporting your own distributed objects. Java IDL is an implementation of the standard IDL-to-Java mapping and is provided by Sun with the standard Java SDK in the org.omg.CORBA and org.omg.CosNaming packages and their subpackages

# Practice Lab (CORBA)

JNDI Java Naming and Directory Interface

JNDI Java Naming and Directory Interface

The Java Naming and Directory Interface (JNDI) is part of the Java platform, providing applications based on Java technology with a unified interface to multiple naming and directory services. You can build powerful and portable directory-enabled applications using this industry standard.

Naming Services

JNDI (Java Naming and Directory Interface) enables Java platform-based applications to access multiple naming and directory services. Part of the Java Enterprise application programming interface (API) set, JNDI makes it possible for developers to create portable applications that are enabled for a number of different naming and directory services, including: file Ssystems; Directory services such as Lightweight Directory Access Protocol (LDAP), Novell Directory Services, and Network Information System (NIS); and distributed object systems such as the Common Object Request Broker Architecture (CORBA), Java Remote Method Invocation (RMI), and Enterprise JavaBeans (EJB). 

As an illustration of what JNDI does, Todd Sundsted (in a JavaWorld article, JNDI overview, Part 1: An introduction to naming services) uses the analogy of a library's file system. Sundsted says that JNDI organizes and locates components within a distributed computing environment similarly to the way that card catalogs (and increasingly computer applications) organize and represent the locations of books within a library. A distributed application needs a means of locating components in the same way that the library patron needs a means of locating the book: just rummaging around inside a library - or an application - is not an efficient way to find a particular object. JNDI makes it possible for application components to find each other. Because different naming and directory service providers can be seamlessly connected through the API, Java applications using it can be easily integrated into various environments and coexist with legacy applications. The current version, JNDI 1.2, was specified with input from Netscape, Novell, Tarantella, Sun, and BEA. JNDI is considered an industry standard. 

The Java Naming and Directory Interface (JNDI) is a Java API for a directory service that allows Java software clients to discover and look up data and objects via a name. Like all Java APIs that interface with host systems, JNDI is independent of the underlying implementation. Additionally, it specifies a service provider interface (SPI) that allows directory service implementations to be plugged into the framework. The implementations may make use of a server, a flat file, or a database; the choice is up to the vendor. 

The Java Naming and Directory Interface (JNDI) is part of the Java platform, providing applications based on Java technology with a unified interface to multiple naming and directory services. Powerful and portable directory-enabled applications can be built using this industry standard.

# Directory Services
# Why use Directory Services?
# The JNDI API
# The Context

Java Swing Application

Java Swing Application

Swing (Java) is a platform-independent, Model-View-Controller GUI framework for Java and implementation of (Look-and-Feel). 

Model–View–Controller (MVC) is a software architecture, currently considered an architectural pattern used in software engineering.

Swing is a highly partitioned architecture, which allows for the "plugging" of various custom implementations of specified framework interfaces: Users can provide their own custom implementation(s) of these components to override the default implementations. In general, Swing users can extend the framework by extending existing (framework) classes or providing alternative implementations of core components.

Swing is a component-based framework. 
The distinction between objects and components is a fairly subtle point: concisely, a component is a well-behaved object with a specified characteristic pattern of behavior. Swing objects asynchronously fire events, have "bound" properties, and respond to a well-known set of commands (specific to the component.) Specifically, Swing components are Java Beans components, compliant with the Java Beans Component Architecture specifications.

Since early versions of Java, a portion of the Abstract Window Toolkit (AWT) has provided platform-independent APIs for user interface components. In AWT, each component is rendered and controlled by a native peer component specific to the underlying windowing system.

By contrast, Swing components are often described as lightweight because they do not require allocation of native resources in the operating system's windowing toolkit. The AWT components are referred to as heavyweight components.

Example
import javax.swing.*; public class FirstSwingApplication extends JFrame { public static void main(String args[]) { new FirstSwingApplication(); } FirstSwingApplication() { JLabel jlbSwing = new JLabel("This is My First Swing Application Test"); add(jlbSwing); this.setSize(300, 300); setVisible(true); } } 

# To Run The Example Just Create a java Class named FirstSwingApplication.java and Copy The Code to The Class and Run the Class You Can Use jCreator or NetBeans IDE To Practice # 

There I Will Show A Complete Desktop Application With JavaSwing

J2EE Java Enterprise Edition

J2EE (Java Enterprise Edition)

The Java 2 Platform, Enterprise Edition (J2EE) is a set of coordinated specifications and practices that together enable solutions for developing, deploying, and managing multi-tier server-centric applications. Building on the Java 2 Platform, Standard Edition (J2SE), the J2EE platform adds the capabilities necessary to provide a complete, stable, secure, and fast Java platform to the enterprise level. It provides value by significantly reducing the cost and complexity of developing and deploying multi-tier solutions, resulting in services that can be rapidly deployed and easily enhanced.
Java 2 Enterprise Edition. A development environment which is independent of hardware systems and operating systems. The idea is that software developers need only write applications once and these applications can then be run unchanged on any computer or operating system.
J2EE is an open standard, pioneered by Sun Microsystems, for creating and delivering multi-tiered enterprise applications in the Java language.
Benefits
Complete Web services support. The J2EE platform provides a framework for developing and deploying web services on the Java platform
Faster solutions delivery time to market. The J2EE platform uses "containers" to simplify development. J2EE containers provide for the separation of business logic from resource and lifecycle management, which means that developers can focus on writing business logic -- their value add -- rather than writing enterprise infrastructure. For example, the Enterprise JavaBeans (EJB) container (implemented by J2EE technology vendors) handles distributed communication, threading, scaling, transaction management, etc. Similarly, Java Servlets simplify web development by providing infrastructure for component, communication, and session management in a web container that is integrated with a web server.
Simplified connectivity. J2EE technology makes it easier to connect the applications and systems you already have and bring those capabilities to the web, to cell phones, and to devices. J2EE offers Java Message Service for integrating diverse applications in a loosely coupled, asynchronous way. The J2EE platform also offers CORBA support for tightly linking systems through remote method calls. In addition, the J2EE platform has J2EE Connectors for linking to enterprise information systems such as ERP systems, By offering one platform with faster solution delivery time to market, freedom of choice, and simplified connectivity

The primary technologies in the J2EE

The primary technologies in the J2EE platform are: Java API for XML-Based RPC (JAX-RPC), JavaServer Pages, Java Servlets, Enterprise JavaBeans components, J2EE Connector Architecture, J2EE Management Model, J2EE Deployment API, Java Management Extensions (JMX), J2EE Authorization Contract for Containers, Java API for XML Registries (JAXR), Java Message Service (JMS), Java Naming and Directory Interface (JNDI), Java Transaction API (JTA), CORBA, and JDBC data access API And Hibernate
Client-server Review
Java originally made its debut in browsers and client machines; at the time, many questioned whether it was suitable for server-side development. Now, with increasing third-party support for the Java 2 Platform, Enterprise Edition (J2EE), Java has become a widely accepted alternative for developing enterprise-strength server-side solutions.
The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered Web-based applications.
In this article, we will examine the 13 core technologies that make up J2EE: JDBC, JNDI, EJBs, RMI, JSP, Java servlets, XML, JMS, Java IDL, JTS, JTA, JavaMail, and JAF. We will describe where and when it is appropriate to use each technology; we will also describe how the different technologies interact with each other.
In the past, two-tier applications -- also known as client/server applications -- were commonplace. Figure 1 illustrates the typical two-tier architecture. In some cases, the only service provided by the server was that of a database server. In those situations, the client was then responsible for data access, applying business logic, converting the results into a format suitable for display, displaying the intended interface to the user, and accepting user input. The client/server architecture is generally easy to deploy at first, but is difficult to upgrade or enhance, and is usually based on proprietary protocols -- typically proprietary database protocols. It also makes reuse of business and presentation logic difficult, if not impossible. Finally, and perhaps most important in the era of the Web, two-tier applications typically do not prove very scalable and are therefore not well suited to the Internet.
Client: Presentation Logic, Business Logic, Data Access Logic
Server: Business Logic, Data Access Logic
Sun designed J2EE in part to address the deficiencies of two-tier architectures. As such, J2EE defines a set of standards to ease the development of n- tier enterprise applications. It defines a set of standardized, modular components; provides a complete set of services to those components; and handles many details of application behavior -- such as security and multithreading -- automatically.
Using J2EE to develop n- tier applications involves breaking apart the different layers in the two-tier architecture into multiple tiers. An n- tier application could provide separate layers for each of the following services:
• Presentation: In a typical Web application, a browser running on the client machine handles presentation.
• Dynamically generated presentation: Although a browser could handle some dynamically generated presentation, for the widest support of different browsers much of the action should be done on the Web server using JSPs, servlets, or XML (Extensible Markup Language) and XSL (Extensible Stylesheet Language).
• Business logic: Business logic is best implemented in Session EJBs (described later).
• Data access: Data access is best implemented in Entity EJBs (described later) and using JDBC.
Backend system integration: Integration with backend systems may use a variety of technologies. The best choice will depend upon the exact nature of the backend system.
n-tiered Applications ( Deployment Architecture )
An n-tier application program is one that is distributed among three or more separate computers in a distributed network. The most common form of n-tier (meaning 'some number of tiers') is the 3-tier application , in which user interface programming is in the user's computer, business logic is in a more centralized computer, and needed data is in a computer that manages a database .
N-tier application structure implies the client/server program model. Where there are more than three distribution levels or tiers involved, the additional tiers in the application are usually associated with the business logic tier.
In addition to the advantages of distributing programming and data throughout a network, n-tier applications have the advantages that any one tier can run on an appropriate processor or operating system platform and can be updated independently of the other tiers. Communication between the program tiers uses special program interfaces such as those provided by the Common Object Request Broker Architecture ( CORBA ).

J2EE Overview

Java 2 Enterprise Edition (J2EE) provides an object-oriented, distributed and cross-platform framework for developing and deploying robust, secure and scalable E-Business and E-Commerce applications. J2EE enables efficient development of enterprise applications, while leveraging investments in existing business resources such as Database Systems, Messaging Systems and Naming and Directory Services. Using J2EE, enterprise developers may implement business objects using the Enterprise JavaBeans (EJB) technology and deploy them across a wide range of J2EE compliant application servers. Enterprise developers may also build sophisticated clients for their E-Business applications using the Java Servlet, Java Server Pages (JSP), XML or the Java Applet technologies. These clients may be packaged and deployed on a Web Container. J2EE enables component-based development of both the business logic and the presentation logic. Using this approach, enables the development of thin HTML, DHTML and JavaScript based clients. J2EE also supports the development of complex clients as regular Java applications and applets.
The J2EE platform provides access to a host of enterprise services using well-defined and standard Java Enterprise APIs that are listed below.
* Enterprise JavaBeans (EJB)
* extensible Markup Language (XML)
* Servlets
* Java Server Pages (JSP)
* Java Messaging Service (JMS)
* Java Database Connectivity (JDBC)
* JavaMail
* JavaIDL
* Java Naming and Directory Interface (JNDI)
* Java RMI/IIOP
* Java Transaction Services (JTS) and Java Transaction API (JTA)
Note: Two of the common and proven architectures for Java-based web applications.
1. Page Centric(Model -1) : all the display logic, business logic, and data are contained in JSP page

2. MVC (Model-2)

Model View Controller (Application Architecture)

Model Layer Technologies

Model A model represents an application's data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The services that a model exposes must be generic enough to support a variety of clients. By glancing at the model's public method list, it should be easy to understand how to control the model's behavior. A model groups related data and operations for providing a specific service; these group of operations wrap and abstract the functionality of the business process being modeled.
A model's interface exposes methods for accessing and updating the state of the model and for executing complex processes encapsulated inside the model. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model

View Layer Technologies

Controller The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations

Controller Layer Technologies

View The view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients. The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller

“Glue” Technologies (Multi- Layer)

Glue is a distributed computing platform for Java, Glue Technology, delivers an open, Java and XML-based platform for seamlessly integrating distributed applications and Web services
GLUE, a simple, fast and comprehensive Java platform for creating, deploying and consuming web services, now includes many new features, including:
- Support for JAX/RPC enumerations
- Improved Wsdl2java and Java2wsdl utilities
- Source code for JBuilder plugin
- Support for com.sun.java.util collections
- JMS adaptor for Sonic MQ
- Enhanced .NET interoperability
- Native DOM support
- Fresh new look for user guide
- Support for UDDI version 2 operations
- iPlanet integration
Built 100% on standards like XML, SOAP, WSDL and UDDI, you can use GLUE to create software building blocks that are language, platform and location independent. GLUE can be used standalone or hosted in a third party application server.

GLUE can publish a Java object as a web service with just one line of code, and invoke remote web services as if they were local Java objects. GLUE generates proxies and WSDL on the fly, so you don't have to mess around with old-fashioned static development utilities.
GLUE standard ships as a 580K .jar file and is free for most commercial uses. GLUE professional adds enterprise features such as EJB integration, JMS integration and a UDDI server.
Glueware is Glue Technology's premier software engine that enables interoperability between partner and customer legacy systems and applications for real-time collaboration and business process automation.
Glueware enables non-intrusive integration with backend-systems and existing IT infrastructures, and makes it possible for existing IT infrastructures to provide Web services and to collaborate in P2P processes
Glue's READI (Rapid Enterprise Application Development for the Internet) methodology covers the entire development lifecycle from business analysis to architecture design to development and deployment

J2EE Application Servers

There are Many Application Server as like Apache Tomcat, GlassFish, Sun Java System Application Server, BEA Web Logic Server, IBM Web Sphere Application Server, JBoss Application Server
Introduction to Servlets

What are Servlets?

Servlets are snippets of Java programs which run inside a Servlet Container. A Servlet Container is much like a Web Server which handles user requests and generates responses. Servlet Container is different from a Web Server because it can not only serve requests for static content like HTML page, GIF images, etc. it can also contain Java Servlets and JSP pages to generate dynamic response. Servlet Container is responsible for loading and maintaining the lifecycle of the a Java Servlet. Servlet Container can be used standalone or more often used in conjunction with a Web server. Example of a Servlet Container is Tomcat and that of Web Server is Apache.
Servlets are actually simple Java classes which must implement the javax.servlet.Servlet interface. This interface contains a total of five methods. Most of the time you don't need to implement this interface. Why? Because javax.servlet package already provides two classes which implement this interface i.e. GenericServlet and HttpServlet . So all you need to do is to extend one of these classes and override the method(s) you need for your Servlet. GenericServlet is a very simple class which only implements the javax.servlet.Servlet interface and provides only basic functionality. On the other hand, HttpServlet is a more useful class which provides methods to work with the HTTP protocol. So if your Servlet works with HTTP protocol (in most cases this will be the case) then you should extend javax.servlet.http.HttpServlet class to build Servlets
Servlets once initialized are kept in memory. So every request which the Servlet Container receives, is delegated to the in-memory Java Servlet which then generates the response. This 'kept in memory' feature makes Java Servlets, a fast and efficient method of building Web Applications.
Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls, receive all the benefits of the mature java language including portability, performance, reusability, and crash protection. Today servlets are the popular choice for building interactive web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually the components of web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server and others.
Servlets are not designed for a specific protocols. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http. Servlets provides a way of creating the sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language.

HTTP Servlet typically used to:

* Priovide dynamic content like getting the results of a database query and returning to the client.
* Process and/or store the data submitted by the HTML.
* Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers.

HTTP Requests

HTTP is a simple, stateless protocol. A client, such as a web browser, makes a request, the web server responds, and the transaction is done. When the client sends a request, the first thing it specifies is an HTTP command, called a method , that tells the server the type of action it wants performed. This first line of the request also specifies the address of a document (a URL) and the version of the HTTP protocol it is using. For example: GET /intro.html HTTP/1.0
This request uses the GET method to ask for the document named intro.html , using HTTP Version 1.0. After sending the request, the client can send optional header information to tell the server extra information about the request, such as what software the client is running and what content types it understands. This information doesn't directly pertain to what was requested, but it could be used by the server in generating its response. Here are some sample request headers:
The User-Agent header provides information about the client software, while the Accept header specifies the media (MIME) types that the client prefers to accept. (We'll talk more about request headers in the context of servlets After the headers, the client sends a blank line, to indicate the end of the header section. The client can also send additional data, if appropriate for the method being used, as it is with the POST method that we'll discuss shortly. If the request doesn't send any data, it ends with an empty line.
After the client sends the request, the server processes it and sends back a response. The first line of the response is a status line that specifies the version of the HTTP protocol the server is using, a status code, and a description of the status code. For example: HTTP/1.0 200 OK
This status line includes a status code of 200, which indicates that the request was successful, hence the description "OK". Another common status code is 404, with the description "Not Found"--as you can guess, this means that the requested document was not found.
After the status line, the server sends response headers that tell the client things like what software the server is running and the content type of the server's response. For example:
The Server header provides information about the server software, while the Content-type header specifies the MIME type of the data included with the response. The server sends a blank line after the headers, to conclude the header section. If the request was successful, the requested data is then sent as part of the response. Otherwise, the response may contain human-readable data that explains why the server couldn't fulfill the request.
In addition to GET and POST, there are several other lesser-used HTTP methods. There's the HEAD method, which is sent by a client when it wants to see only the headers of the response, to determine the document's size, modification time, or general availability. There's also PUT, to place documents directly on the server, and DELETE, to do just the opposite. These last two aren't widely supported due to complicated policy issues. The TRACE method is used as a debugging aid--it returns to the client the exact contents of its request. Finally, the OPTIONS method can be used to ask the server which methods it supports or what options are available for a particular resource on the server.

DoGet() vs doPost()

When a client connects to a server and makes an HTTP request, the request can be of several different types, called methods. The most frequently used methods are GET and POST. Put simply, the GET method is designed for getting information (a document, a chart, or the results from a database query), while the POST method is designed for posting information (a credit card number, some new chart data, or information that is to be stored in a database). To use a bulletin board analogy, GET is for reading and POST is for tacking up new material.
The GET method, although it's designed for reading information, can include as part of the request some of its own information that better describes what to get--such as an x, y scale for a dynamically created chart. This information is passed as a sequence of characters appended to the request URL in what's called a query string . Placing the extra information in the URL in this way allows the page to be bookmarked or emailed like any other. Because GET requests theoretically shouldn't need to send large amounts of information, some servers limit the length of URLs and query strings to about 240 characters.
The POST method uses a different technique to send information to the server because in some cases it may need to send megabytes of information. A POST request passes all its data, of unlimited length, directly over the socket connection as part of its HTTP request body. The exchange is invisible to the client. The URL doesn't change at all. Consequently, POST requests cannot be bookmarked or emailed or, in some cases, even reloaded. That's by design--information sent to the server, such as your credit card number, should be sent only once.
In practice, the use of GET and POST has strayed from the original intent. It's common for long parameterized requests for information to use POST instead of GET to work around problems with overly-long URLs. It's also common for simple forms that upload information to use GET because, well--why not, it works! Generally, this isn't much of a problem. Just remember that GET requests, because they can be bookmarked so easily, should not be allowed to cause damage for which the client could be held responsible. In other words, GET requests should not be used to place an order, update a database, or take an explicit client action in any way.

Sending the response

After the client sends the request, the server processes it and sends back a response. The first line of the response is a status line that specifies the version of the HTTP protocol the server is using, a status code, and a description of the status code.
The HttpServletResponse class
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("");
out.println("Hello World");
out.println("");
out.println("Hello World");
out.println("");
} }
This servlet uses two methods and a class that have been only briefly mentioned before. The setContentType() method of ServletResponse sets the content type of the response to be the specified type:
public void ServletResponse.setContentType(String type)
In an HTTP servlet, this method sets the Content-Type HTTP header.
The getWriter() method returns a PrintWriter for writing character-based response data:
public PrintWriter ServletResponse.getWriter() throws IOException

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>");   
   }
}