Wednesday, December 31, 2008

Servelets

Servlets are simple Java classes which extend the capabilities of the server that host the application using the request-response programming model.

All servlets must implement the Servlet interface which defines the servlet life cycle methods.

Lifecycle of a servlet

First of all the servlet class is loaded by the web container.

Container calls the init () method of servlet and must be called before servlet can service any request.

The service () method determines the kind of request being made and forwards it to an appropriate method to handle it.

Finally container calls destroy () method which indicates end of lifecycle of servlet. It takes servlet out of service

init () and destroy method are called only once in a servlet’s lifecycle.

The GenericServlet class can be extended by the servlet when it wants to provide any generic service.

The HTTPServlet class provides the methods for the HTTP related operations like get (doGet method), post (doPost method).

Usually the output of a servlet is in form of html.

The common methods of a servlet are:

init:

signature - public void init (ServletConfig sc) throws ServletException{}

usual semantic - The first line of this method is super.init (this); this makes a call to the super class’ init method. This call must be done through every servlet’s init method.

service:

signature - public void service (ServletRequest req, ServletResponse resp) throws ServletException, IOException{}

usual semantic - This method is used when we want to fulfill the request sent by client.

destroy:

signature- public void destroy(){}

usual semantic- This function contains the logic to free up the held up resources                                     when the servlet is going to be destroyed, i.e. its going to be out of scope.

The common service methods provided by HTTPServlet class for the four HTTP commands are:

doGet:

 signature - public void doGet (HTTPServletRequest req,HTTPServletResponse resp){}

 usual semantic - This method is invoked when the servlet encounters the HTTP “GET” command.

doPost:

signature- public void doPost (HTTPServletRequest req,HTTPServletResponse resp){}

usual semantic- This method is invoked when the servlet encounters the HTTP “Post” command.

Apart from these methods there are also other methods namely doPut and the doDelete method.

 

Servlet Container

A servlet is managed by a servlet container.

The servlet container together with the web server provides the HTTP interface to the world.

It is the servlet container who calls service () method  and passes an instance of ServletRequest and ServletResponse. Depending on this method service calls doGet () or doPost ().

Servlet container can get details about the remote user is and can generate appropriate response. It is responsible for loading and instantiating the servlets and calling init().

Following is an example of a simple genric servlet class:

 

import javax.servlet.*;

import java.io.*;

//the list of other files to be imported goes here.

public  class Myservlet extends Servlet{

                // declaration of variables goes here.

public void init() throws ServletException{

// the code that has to be executed when the Servlet initializes goes here.

}

public void Service(ServletRequest req, ServletRespoinse) throws ServletException, IOException{

// The code that needs to be executed when a request comes to this servlet comes here.

}

public void destroy(){

// The code that needs to be executed when the servlet is about to go out of scope comes here. Usually all the resources that the servlet used is freed from here.

}

//similarly other member functions of the servlet apart from these mandatory methods comes here.

}

J2EE

The Java2 platform Enterprise Edition is a java environment for developing and deploying enterprise applications by providing set of services, API and protocols that provides functionality to develop multi-tiered applications and web based application.

J2EE architecture supports component based development of multitier application. J2EE applications mainly consist of following tiers:

Client Tier: It provide interface to middle tier through web components such as Servlets and JSP or standalone applications.

Middle Tier: Here the business logic of our application resides. Components in middle server consist of some of web services and enterprise beans. These components are installed on server inside J2EE Application server. It is a place where components perform actions.

Enterprise Data Tier: Enterprise data is stored over here, typically relational database.

The major technologies of J2EE are:

--Servlets.

--Java Server Pages (JSP).

--Java Database Connectivity (JDBC).

--Java Naming and Directory Interface (JNDI).

--Enterprise Java Bean (EJB).

--Extensible markup language (XML).

--Java Messaging Services (JMS).

--JavaMail.

--JAF (JavaBeans Activation Framework)

--Java IDL.

--Java RMI (Remote Method Invocation) / IIOP (Internet Inter-ORB Protocol).

--Java Transaction Service (JTS) and Java Transaction API (JTA)

Wednesday, December 3, 2008

Exception handling in java

Exception handling is one very good feature provided by Java.

Handling exceptions is a very easy task in Java and can be utilized to the best.

When an exception occurs the program must do either of the two things:

Return to safe state and allow the user to execute other commands.

Allow the user to save all his work and terminate the program gracefully.

In Java all classes that handle exceptions are derived from throwable.

Also one can create one’s own exception class by extending either of the exception classes available.

Following is a figure depicting the hierarchy of Exception classes in Java:

 

 

 







Exception Class Hierarchy

As is clearly visible from the diagram, the hierarchy of errors splits into Errors and Exception.

Error

Exception

The Error hierarchy describes the internal errors and the errors that occur due to resource exhaustion in the Java runtime system.

The Exception hierarchy describes the errors happening due violation of some rule of Java language or due to violation of some constraints of Java Runtime Environment.

Difference of Error and Exceptions.

Error hierarchy describes the internal errors and resource exhaustion inside the Java runtime system.

One should not throw an object of this type.

One cannot do much but to inform user and try terminate the program gracefully when such an internal errors occur which is a case that happens very rarely.

Exception hierarchy is the one that we focus on mostly when programming in java.

Exceptions are of two types, checked exception and unchecked exception:

Checked exception

Unchecked Exception

Checked exceptions are instances of Exception classes or its sub-classes (excluding RuntimeException and its subclasses).

The compiler expects all checked exceptions to be appropriately handled.

Checked exception must be declared in throws clause of method throwing exception.

The calling method must take care of these exceptions by either catching or declaring them in its throws clause.

These Exceptions are not derived from the Runtime class hierarchy and include exceptions such as:

 Trying to read after the end of file.

Opening a malformed URL.

Accessing a non existing class.

Unchecked Exceptions are instances of RuntimeException class or one of its sub classes.

We don’t need to declare unchecked exception in the throws clause of the throwing method.

Also, the calling method doesn’t have to handle them.

Mostly, unchecked exceptions throw only problems arising in JVM

These Exceptions are derived from Runtime class and include exceptions such as:

Illegal Typecasting.

Array index out of bound.

Null Pointer Exception.

Difference between Checked and Unchecked exceptions.

In Java we can also declare our own Exception class if the standard inbuilt classes do not suit our needs.

All we need to do is just extend any of the base class of Exception under which our class can best fall and describe our own exception handling mechanism in that class’ method.

Following is an example of a simple Exception class which extends IOException class.

import java.exception.*;

import java.io.*;

//the list of other files to be imported goes here.

public class MyException extends IOException {

public MyException (){

                                                // the codes go here.

                }

public MyException( String msg){

 super (msg);

//other codes come here.

}

}             

In Java Exception handling is done mostly using either or all of the following:

Throws keyword.

Throw keyword.

Try-catch-finally block.

When we need to throw an exception from a function, we do it using the throw command, and declare that a function throws such an exception which the user of the function should catch using the throws command.

 public void somefunction () throws SomeException {

// the codes go here.

                                ………

                                if( a > b){ throw new SomeException ();

                                …………..

}

We can catch exceptions and provide a mechanism which will function when an Exception occurs using the try-catch block.

The code which can throw an Exception goes in the try block and the code for what we need to do if the Exception is caught goes in the catch block.

We can have multiple try catch blocks.

For every catch block there must be one and only one try block.

For every try block there must be at least one catch block or a finally block.

We can also have nested try-catch blocks if need arises.

Following is an example showing the syntax of a general try catch block:

                                ……………………………

try{

                //the code which is capable of throwing an Exception comes here.

                …………………………………..

}

catch (SomeException1 se1) {

                // the code for handling when the Exception of type SomeException1 in the try block comes here.

}

catch (SomeException2 se2) {

// the code for handling when the Exception of type SomeException2 in the try block comes here.

}

                                                ……………………………

 

If we want that some code should execute compulsorily even if the exceptions occur or not, then we can put in the finally block.

                ……………………………

try{

                //the code which is capable of throwing an Exception comes here.

                                …………………………………..

}

catch (SomeException1 se1) {

                                // the code for handling when the Exception of type SomeException1 in the try block comes here.

}

catch (SomeException2 se2) {

                // the code for handling when the Exception of type SomeException2 in the try block comes here.

}

finally{

                // the code that needs to be executed compulsorily comes here.

}

 

The best programming practice says that we must put all the code that requires exception handling in try catch block and should not skip or ignore any such thing.

The best Exception handling practice says that when we catch exceptions, we must provide the catch blocks for those exceptions first that is most specific and then goes up the hierarchy and provide a catch block for more general exceptions.

Monday, December 1, 2008

Class Loader of Java


In Java class loaders are used to load a class from the local disk when JVM needs it.

The class loader obtains the information related to the class from the .class file which is formed once we compile the code from the local machine.

We can provide our own implementation of the class loader which will load a class from the remote machine but still the class file is first copied to the local disk and then the data is loaded.

Every class’ objects contain a reference to the class loader.

Class objects for array classes are not created by class loaders, but are created automatically as required by the Java runtime. The class loader for an array class, as returned by Class.getClassLoader () is the same as the class loader for its element type; if the element type is a primitive type, then the array class has no class loader.

Class loaders are used by security managers to indicate the security domain.

Class loader class uses delegation model to search information about the classes.

Each instance of a class has a parent which calls the class loader to load it and becomes the parent of the class.

There is an exception to this rule

The JVM’s built in class loader “bootstrap class loader” does not have a parent but has classes to which it acts as a parent. (This is usually loaded from the file rt.jar)

Apart from this the other class loaders of the JVM are the “Extension class loader” (found usually from the jre/lib/ext directory) and the “System/Application class loader” (normally found in the CLASSPATH)

Additionally this class files are not loaded into memory all at once, but instead are loaded on demand, as and when required. Here comes Class Loader into the picture, it loads classes into memory.

Class Loader is simply a class written in JAVA language only. So in this way java gives you one more chance to create your own class loader rather than using the one that is already provided. 

How is java OOP

Since Java came into existence there is a buzz relates to whether Java is an OOP or not. Still there are many criticizes java for its OOP concepts.

Java supports all the concepts and properties of OOP, this is shown as below:


Basic Concepts of OOP

Abstraction:

In Java we can have as much number of classes as we want and put them all in a package. In this way we can have a package having all set of functionality each of which is a standalone class.

Encapsulation:

Java supports encapsulation by introducing the concept of interfaces.

Interfaces are an agreement between the class designer and the programmer.

Interfaces just provide the functionality that needs to be present in the class and not the actual implementation.

The best Java programming practice says that we should program to an interface.

An interface can be implemented by any number of classes and at the same time two classes implementing the same interface need not be worried about how the other provides the implementation of a particular method; all it knows is that the other class does provide a certain method.

For example:

public interface myinterface{

// declaration of methods and variables.

}

public class myclass implements myinterface{

//implementation of class goes here

}

Polymorphism:

We can call the child class methods having the same name using the base class object. The child classes may have the same signatures of a method but the base class object decides which one to call. This way polymorphism is achieved in Java.

The syntax of this is:

baseobj = new childobj ();

baseobj.childfunc ();

Properties of OOP

Class:

In Java all the attributes and methods are declared inside a class only. Nothing can be outside the boundaries of class in Java. For example:

public class Myclass{

// all the declaration of variables, functions etc go here.

}

Object:

In Java a before we can use the functionality of the class; its object needs to be instantiated. Using the following syntax:

Myobject obj = new Myobject (); or

Myobject obj = new Myobject (list of parameters);

Method:

A class may have several functionalities which are implemented as methods. Methods are the only means by which we can make use of the functionalities provided by the class. For example:

public class Myclass{

                // declaration of variables.

public returntype func1(the list of parameters separated by comma){

                                //the code goes here.

}

private void func2(){

                                //the code goes here.

}

//similarly a class can have any number of functions.

}

 

 

Inheritance:

In java we can inherit a class and make use of the functionality it provides. Java supports only multilevel inheritance and not multiple inheritance. For example:

public class myclass extends baseclass {

                //implementation goes here

}

Message Passing:

We can invoke a different class’ method on that class’ object. This takes care of message passing between one active object and other. The syntax for this is:

Obj.methodname (); or

Obj.methodname (list of comma separated parameters);

/* Here the object obj is already instantiated*/

Thus we can see that as Java supports all the concepts and properties of the Object Oriented Programming paradigm it is an Object Oriented Programming Language.