Saturday, May 21, 2011

The Servlet init Vs Constructor

Generally Servlets don’t have the Constructor, because a servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should be place in the init(), since it get called when the servlet is first loaded.

You cann’t use a Constructor instead of init() method to initialize a servlet.The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext. 

Even while you trying to override the init() method you should pass the argument a ServletContext object because the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.

Servlet Life Cycle

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

The methods which are used to initialize a servlet, to service requests, and to remove a servlet from the server are called servlet life cycle methods. These are three methods namely init(), service(), destroy().

Init(): The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests
It Contains all information code for servlet and is invoked when the servlet is first loaded.
You can override this method to write initialization code that needs to run only once, such as loading a driver, initializing values and soon, another case you can leave normally blank.

public void init(ServletConfig config)throws ServletException

Service() : is called by the Servlet container after the init method to allow the servlet to respond to a request. Service method receives the request from the client and identifies the type of request and delegates them to doGet() or doPost() for processing.

public void service(ServletRequest request,ServletResponce response) throws ServletException,  IOException

Destroy() : The Servlet Container calls the destroy( ) before removing a Servlet Instance from Sevice. Executes only once when the Servlet is removed from Server.

public void destroy() 


Click here to know about Servlets

Java Servlets

Servlet is a Java 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(like HTTP, FTP), they are commonly used to extend the applications hosted by Web servers.


Servlets runs at Server side typically Web Server or Application server, and respond to request by giving the response to user after processing the request. 


A servlet that implements SingleThreadModel means that for every request, a single servlet instance is created. This implementation helps in implementing the business applications like bank transactions. 


A multi-threaded servlet means that one servlet is capable of handling many requests which is the way most servlets should be implemented. This allows servlets to support systems such as on-line conferencing.


A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets.


As Servlet are written in java, they can make use of extensive power of the JAVA API,such as networking and URL access, multithreading, databaseconnectivity, RMI object serialization.

A Servlet implementation can be done in three ways:

  1. By implementing the Sevlet interface into your class. The class which implementing the Servlet interface, should implement all the servlet life cycle methods defined in the Servlet interface.
  2. By writing a subclass to GenricServlet present in the javax.servlet package. The subclass must override the abstract service method present in the Generic servlet class.
  3. By writing a subclass to HttpServlet present in javax.servlet.http package. The subclass of HttpServlet must override any of the methods in doGet(), doPost(), doDelete(), doPut(), init(), destroy(), getServletInfo().


In general most of the cases Servlet implementation can done by sub classing to GenericServlet or HttpServlet.
Below are the differences between HttpServlet and GenericServlet:
  1. HttpServlet is the subclass of GenericServlet.
  2. Generic Servlet defines a generic, protocol-independent servlet. HttpServlet provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site.
  3. A sub class which extends GenericServlet must implement the abstract service() method. A subclass of HttpServlet must override at least one method, usually one of these: doGet(), doPost(), doDelete(), doPut(), init(), destroy(), getServletInfo().

Click here to know Servlet Life cycles

Abstract class in Java

Abstract class is class which has more than one abstract method which doesn’t have method body but at least one of its methods need to be implemented  in derived Class.  
Abstract classes can be used to implement the inheritance relationship between the classes that belongs same hierarchy.
  1. Classes and methods can be declared as abstract.
  2. Abstract class can extend only one Class.
  3. If a Class is declared as abstract , no instance of that class can be created.
  4. If a method is declared as abstract, the sub class gives the implementation of that class.
  5. Even if a single method is declared as abstract in a Class ,  the class itself  can be declared as abstract.
  6. Abstract class have at least one abstract  method and others may be concrete.
  7. In abstract Class the keyword abstract must be used for method.
  8. Abstract classes have sub classes.
  9. Combination of modifiers Final and Abstract is illegal in java.
The general form of abstract class is :     
    abstract type name (parameter list);

The Number class in the java.lang package represents the abstract concept of numbers. It makes sense to model numbers in a program, but it doesn't make sense to create a generic number object.

Sample Abstract Classes: HttpServlet, GenericServlet 

You can more avout Interface here 
Click here for Difference between Abstract class and Iterface

Interface in Java

Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy.  Using Interface, you can specify what a class must do but not how it does.
  1. A class can implement more than one Interface.
  2. An Interface can extend one or more interfaces, by using the keyword extends.
  3. All the data members in the interface are public, static and Final by default.
  4. An Interface method can have only Public, default and Abstract modifiers.
  5. An Interface is loaded in memory only when it is needed for the first time.
  6. A Class, which implements an Interface, needs to provide the implementation of all the methods in that Interface.
  7. If the Implementation for all the methods declared in the Interface are not provided , the class itself has to declare abstract, other wise the Class will not compile.
  8. If a class Implements two interface and both the Intfs have identical method declaration, it is totally valid. 
  9. If a class implements two interfaces both have identical method name and argument list, but different return types, the code will not compile.
  10. An Interface can’t be instantiated. Intf Are designed to support dynamic method resolution at run time.
  11. An interface can not be native, static, synchronize, final, protected or private.
  12. The Interface fields can’t be Private or Protected.
  13. A Transient variables and Volatile variables can not be members of  Interface.
  14. The extends keyword should not used after the Implements keyword, the Extends must always come before the Implements keyword.
  15. A top level Interface can not be declared as static or final.
  16. If an Interface species an exception list for a method, then the  class implementing the interface need not declare the method with  the exception list.
  17.  If an Interface can’t specify an exception list for a method, the class can’t throw an exception.
  18.  If an Interface does not specify the exception list for a method, the class can not throw any exception list.
The general form of Interface is
Access interface name {
         return-type method-name1(parameter-list);
            type final-varname1=value;
          }
-----------------------
Marker Interfaces :  Serializable, Clonable, Remote, EventListener

Marker Interface is an Interface which does not have any method declarations. They are used to mark/tag the nature of the class. 

Click here to More about Abstract class
Click here for more about Difference between Abstract class and Interface

Need of Real beauty to my second part of my life

I am in need of a Real Beauty to be with me in my second part of the life as I have going to cross my bachelor life. At this point i am very happy to share my views about My Real beauty. The real beauty is not just a human being; it might be the place, object, animal etc… Here I am going to write about a beautiful lady, who should have real beauty characteristics to become part of my life.


Dove Real Beauty on Yahoo! India
I have used the word beauty on ladies by looking at their face so many times in the past. But once I decided to choose a real beauty as part of my life, then I used to think about how can I define a real beauty and  what a real beauty is?. Sometimes I found that it is a hard to define or describe about the beauty of women. But, after understanding of real beauty I would expecting few of the characters as part of my partner. 


The concept of beauty, in fact, is different from person to person. Anyone can tell you their personal definition of beauty: who they think is beautiful and who isn’t. 


Small Definition of Beauty…..


So what is Beauty? Beauty is a characteristic of a person, place, object or idea that provides a perceptual experience of pleasure, meaning or satisfaction. Beauty may occur in different form, physical beauty of female, inner beauty of kind man, graceful beauty of grandeur dame and even ordinary beauty of common people.


As we seeing every day, beauty contests like Miss Universe and shows like Extreme Makeover, as well as People Magazine featuring the most beautiful people in the world. If we observe clearly the competitions, we can have a true definition of a real beauty?.The concept of these shows is, the competitors should have internal beauty including the external beauty. As per this assumption only winner will be decided.


So, beauty is just not a person face or person body structure; it is also a characteristic of a person. 


True beauty doesn't need any kind of ornaments. It is a gift from God to Human beings. The person who gets blessed by nature gets blessed with precious beauty.


Expectations of My Real Beauty characters: 
  • She should have well outside beauty like The Moon.
  • She should have cool mind like an Ice.
  • She should have a kindly heart like The Ocean.
  • She should too kind like Mother.
  • She should help to others like Tree.
  • Her thoughts should be cleaner like Milk. 
This is my view about the real beauty. Different persons will have different views. So, others might have not consider all these points.

Thank you.

Wednesday, May 18, 2011

Java Singleton Design pattern

A class which must create only one object (ie. One instance) irrespective of any number of object creations based on that class.

Steps to develop single ton class:- 
1.Create a Private construcor, so that outside class can not access this constructor. And declare a private static reference of same class
2.Write a public Factory method which creates an object. Assign this object to private static Reference and return the object

Sample Code:-


public class SingleTonExample

{
private static SingleTonExample st=null;
private SingleTonExample()
{
System.out.println(“\nIn constructor”);
}
public static SingleTonExample getInstance()
{
if(st==null)
st=new SingleTonExample();
return st;
}
}

How to use the Singleton class created above is described in below class:

public class UsingSingletonClass{
             public void testMethod(){
               SingleTonExample st = SingleTonExample.hetInstance();
               //you can use the SingleTonExample object st for your requirements
}

}

Tuesday, May 17, 2011

More about Static variable & Static method

Static variables & methods are instantiated only once per class. In other words they are class variables,   not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.

Static methods can be referenced with the name of the class. It may not access the instance variables of that class, only its static variables. Further it may not invoke instance (non-static) methods of that class unless it provides them with some object.

--> When a member is declared a static it can be accessed before any object of its class are created.
--> Instance variables declared as static are essentially global variables.
--> If you do not specify an initial value to an instance & Static variable a default value will be assigned   automatically.
--> Methods declared as static have some restrictions they can access only static data, they can only call other static data, they cannot refer this or super.
--> Static methods cant be overriden to non-static methods.
--> Static methods is called by the static methods only, an ordinary method can call the static methods, but static methods cannot call ordinary methods.
--> Static methods are implicitly "final", because overriding is only done based on the type of the objects
--> They cannot refer “this” are “super” in any way.

About Ip Addresses..................

Do you know about IP addresses?

In daily life we hear the word IP address. Generally we might get a question like what is IP address. How its implemented? How to find/know system ip? Here I am planning to share about the system Ip address.

What's an IP address ?

IP (Internet Protocol) address is a unique 32 bit number assigned to each machine connected to the Internet (or an IP network), either permanently or temporarily (by dial up connection or similar).
A typical IP address looks like - 207.153.234.217

How to find IP Address of My system?

The systems which are connected to internet will have an IP address. To know about your system IP addresses go to command prompt and type a command “ipconfig”, This will display the below information. So IP Address of this system is 115.241.3.171.
 Connection-specific DNS Suffix  . :
        IP Address. . . . . . . . . . . . : 115.241.3.171
        Subnet Mask . . . . . . . . . . . : 255.255.255.255
        Default Gateway . . . . . . . . . : 115.241.3.171

Do you want to know more about IP Address?

IP addresses are usually denoted as 4 decimal numbers (also called octets), separated by dots. This format of representing an IP address is known as "dotted quad" or "dotted decimal" notation. (There are also base 10 notations, but it is rather uncommon). Each octect is represented in binary format by a single byte or 8 bits, thus 4 octets form a 32 bit IP address as shown above. (Note: This is valid for IP version 4 only). Theoretically, 32 bit IP addresses can accommodate almost 232 = 4,294,967,296 (approximately 4.3 billion) machines on an IP network, such as Internet. In reality however, the number is much less than this number because many IP address ranges are reserved for special purpose and should not be used for another purpose.

What an IP address contains?

An IP address consists of two parts, one identifying the network and one identifying the node or host. Each network can have "X" number of nodes or hosts under it. In the class system, the class of the address determines which part belongs to the network address, and which part belongs to the host address. In newer CIDR (Classless Inter-Domain Routing) system, this information is specified along with the IP address itself, thus allowing more efficient and practical allocation of IP addresses.

IP addresses have been classified into 5 classes and special purpose addresses, depending upon the value in the first octet. Viz-
Class A - This is a class for very large networks, such as IBM which holds IP addresses in the range - 9.0.0.0 - 9.255.255.255. (almost 16,777,216 IP addresses).
First Octet - - The first octet is between 1 to 126. (Starts with binary bit - 0).
Network Address - The n/w address is denoted by first 8 bits or first octet.
Host/Node Address - Host address is denoted by last 24 bits or last 3 octets.
This Network-Host IP configuration for class A can be shown as -
network.host.host.host
and each can have 1 to 3 decimals. Thus forming 126 network addresses (27 - 1) and each of them capable of having 16,777,214 (224 -2) host addresses. 

Class B - This is a class for medium-sized networks.
First Octet - - The first octet is between 128 to 191. (Starts with binary bits - 10).
Network Address - The n/w address is denoted by first 16 bits or first 2 octets.
Host/Node Address - Host address is denoted by last 16 bits or last 2 octets.
This Network-Host IP configuration for class B can be shown as -
network.network.host.host
and each can have 1 to 3 decimals. Thus forming 16,384 network addresses (214) and each of them capable of having 65,534 (216 -2) host addresses. 

Class C - This is a class for small-sized networks.
First Octet - - The first octet is between 192 to 223. (Starts with binary bits - 110).
Network Address - The n/w address is denoted by first 24 bits or first 3 octets.
Host/Node Address - Host address is denoted by last 8 bits or last octet.
This Network-Host IP configuration for class C can be shown as -
network.network.network.host
and each can have 1 to 3 decimals. Thus forming 2,097,152 network addresses (221) and each of them capable of having 254 (28 -2) host addresses. 

Class D - This is a class meant for multicasting only, for sending multicast messages to other groups of host machines.
First Octet - - The first octet is between 224 to 239. (Starts with binary bits - 1110).
The class D is a special purpose reserved class, and addresses in this range are not assigned as IP addresses on an IP network, including Internet. 

Class E - This is a class meant for experimental purpose only.
First Octet - - The first octet is between 240 to 255. (Starts with binary bits - 1111).
The class E is also a special purpose reserved class, and addresses in this range are not assigned as IP addresses on an IP network, including Internet. The IP address 255.255.255.255 in this range is also known as Broadcast.

How the IP Address allocation will be done?

Loopback:
Addresses 127.0.0.0 to 127.255.255.255 are reserved for loopback, for internal testing on a local machine. 127.0.0.1 typically refers to your own local machine, you can test this - you should always be able to ping 127.0.0.1, irrespective of connectivity to the network, as it represents your own machine.
IP addresses in this range are never valid Internet addresses.

Private Networks:
There are 3 IP network addresses reserved for private networks.
10.0.0.0 to 10.255.255.255
172.16.0.0 to 172.31.255.255
192.168.0.0 to 192.168.255.255
They may be used by anyone setting up internal IP networks, such as organization LAN behind a proxy server or a router. It is recommended to use them because routers on the Internet should (and will) never forward packets coming from these addresses. These addresses are meaningful only for the network to which they belong (Intranet). Due to this, two or more organizations may have same IP address falling in this range assigned to two or more individual machines without any conflict.

How to write image into jsp?


WriteIamge.jsp
<%
byte[] imagedata=(byte[])request.getAttribute("imageData");
OutputStream output = null;
if(imagedata!=null){ response.setContentType("image/gif"); try{
output = response.getOutputStream();
output.write(imagedata);
out.clear ();
out = pageContext.pushBody ();
}
catch(Exception e)
{
System.out.println("ERROR OCCURED IN Image jsp");
e.printStackTrace();
}
finally
{
output.flush();
output.close();
}
}else{
out.println("

Image not available

");
}
%>