Saturday, March 16, 2013

JSP Life Cycle


A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
The following are the paths followed by a JSP
  • Compilation
  • Initialization
  • Execution
  • Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:
JSP Life Cycle

JSP Compilation:

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
  • Parsing the JSP.
  • Turning the JSP into a servlet.
  • Compiling the servlet.

JSP Initialization:

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method:
public void jspInit(){
  // Initialization code...
}
Typically initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.

JSP Execution:

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request, 
                 HttpServletResponse response)
{
   // Service handling code...
}
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.

JSP Cleanup:

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
   // Your cleanup code goes here.
}

JSP Architecture


The web server needs a JSP engine ie. container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.
JSP Architecture

JSP Processing:

The following steps explain how the web server creates the web page using JSP:
  • As with a normal page, your browser sends an HTTP request to the web server.
  • The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
  • The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code that implements the corresponding dynamic behavior of the page.
  • The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.
  • A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response.
  • The web server forwards the HTTP response to your browser in terms of static HTML content.
  • Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
JSP Processing
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's contents. This makes the process more efficient than with other scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet

Friday, March 15, 2013

Servlet Life Cycle


A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet
  • The servlet is initialized by calling the init () method.
  • The servlet calls service() method to process a client's request.
  • The servlet is terminated by calling the destroy() method.
  • Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.

The init() method :

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException {
  // Initialization code...
}

The service() method :

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request, 
                    ServletResponse response) 
      throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here are the signature of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet code
}

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet code
}

The destroy() method :

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:
  public void destroy() {
    // Finalization code...
  }

Architecture Digram:

The following figure depicts a typical servlet life-cycle scenario.
  • First the HTTP requests coming to the server are delegated to the servlet container.
  • The servlet container loads the servlet before invoking the service() method.
  • Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
Servlet Life Cycle

Thursday, March 14, 2013

Shallow Cloning and Deep Cloning in Java

Cloning is of 2 Types:

1. Shallow Cloning  2. Deep Cloning

Whenever clone() method is used 2 different objects are created in 2 different memory locations. So
separate memory is occupied.

If a class contains  X, Y variable and clone is applied two different objects are created in two different situations.

In Shallow Cloning  main problem is instance variables are common for both objects , so if one object is modifed then automatically second object is also modified.

In deep cloning 2 different objects are created in 2 different memory locations , if in case original object is modified then also its duplicate object won't effect , why because there is  no relation between original and duplicate object.



KNOWLEDGE HUB: How many ways can you create an object in Java

KNOWLEDGE HUB: How many ways can you create an object in Java

Wednesday, March 13, 2013

different ways to create an object in Java

There are 4 ways of creating objects in Java.

1. Using new operator

Employee emp = new Employee();

Here , we are creating Employee class object  'emp' using new operator.

2. Using factrory methods:

NumberFormat nf  = NumberFormat.getNumberInstace();

Here, we are creatig NumberFormat object using the factory method getNumberInstacne().

3. Using newInstance() method .

(a) First,store the class name  'Employee' as string into an  object. For this purpose , factory method
forName() of the class 'Class' will be useful.

Class c = Class.forName("Employee");

Note: class with the name 'Class' in java.lang package.
(b) create another object to the class whose name is in the object c . For this purpose , we need
newInstance()  method of the class 'Class' . as:

Employee obj = (Employee)c.newInstance();

4. By cloning an already available object, we can create another object . Creating exact copy of an
existing object is called 'cloning':

Employee obj1 = new Employee();
Employee obj2 = (Employee)obj1.clone();

Constructor VS Method in Java

Constructor
 Method
A constructor is used to initialize the instance variables of a class.
A Method is used for any general purpose processing or calculations.
A constructors name and class name should be same.
A method’s name and class name can be same or different.
A constructor is called at the time of creating the object.
A method can be called after creating the object.
A Constructor  is called only once per object.
A method can be called several times on the object.
A constructor is called and executed automatically.
A method is executed only when we call it.