RequestDispatcher in servlet


  • One servlet delegating request processing duty to other servlet is known as request dispatching.
  • To implement inter-servlet communication and servlet -jsp communication we need request dispatching.
  • When servlet receives a simple client request it need to communicate with any other servlet. if the incoming client request is complex one.
  • A servlet process some portion of the request and remaining portion it need to communicate with other servlet known as inter-servlet communication.

Implementing Request dispatching:

Step 1: Creating RequestDispatcher object.
    
   RequestDispatcher rd=request.getRequestDispatcher("other servlet url name");

Step 2: Dispatching the request to the other servlet.
         
  RequestDispatcher having two methods to switch the control from one servelt to other
  1. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
  2. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
By calling any of the above two methods request dispatching is implemented

           rd.forward(req, res) or rd.include(req, res)

forward();

  • In case of forward mechanism of  request dispatching one servlet receives the control , performs a portion of processing and switches the control to another servlet for the remaining portion of the processing
  •  That second servlet performs remaining portion of the request processing , produces the response page and handle over to the same web server.

Include():



  • In case of include mechanism of  request dispatching one servlet receives the control , performs a portion of processing and switches the control to another servlet for the remaining portion of the processing. gets control back from the next servlet and produces the dynamic web page on the web server.



Servlet Life Cycle


Servlet life cycle Methods:

  • Servlet engine controls the life cycle of servlet
  • Servlet life cycle is described by three life cycle methods under 5 life cycle phases
  • life cycle methods are
  1. init(ServletConfig obj)
  2. service(servletRequest, servletResponse)
  3. destroy() 

When ever somethings happens in the life of servlet. servlet engine calls these methods on the servlet
instance and hence the name.

Life cycle phases :

  1. Does not exist phase
  2. Instantiation phase
  3. Initialization phase
  4. Servicing  phase
  5. Destruction phase


Doesn't Exist:

  • Servlet class is made available to the servlet engine but not yet its instance is created.
  • It is known as doesn't exist phase of a servlet.

Instatiation:

  • The process of creating the object of a class is known as instantiation.
  • Servlet engine loads user user defined servlet class file from secondary memory into
    primary memory dynamically

    class c= class.forName("name");
    c.newInstance();
  • Servlet engine creates the instance of loaded servlet class.
  • Servlet engine uses the following piece of code to load the servlet clas  dynamically to instantiate it.
    Class c= class.forName("Servlet class name");
    c.newInstance();



Initialization:

  • Servlet engine creates servletConfig object
  • Servlet engine calls the init() method on the servlet instance by supplying servletconfig object
    as argument.
  • Once init method completely executed servlet is ready to serve the client request.

Servicing : 

  • Servlet engine creates servlet request and servlet response object based on the web server
    provided client information.
  • Servlet engine calls service method on the servlet instance by supplying two object reference as arguments
  • Once service method is completely executed , client request is served and request-response cycle is complete.
  • Within the service method request object is used to capture the user input
  • Response object is used to build the dynamic page and hand over the same to the web server

Destruction:

  • Destruction phase of servlet represents servlet being removed from use by container

Write a program to sort object using comparable ?

Check this one also
Sort employee object in descending order
Here I am taking class Employee:

package com.instanceofjava;

import java.util.Comparable;
public class Employee implements Comparable<Employee> {
 int id;
 String name;
 public Employee(int id, String name) {
  this.id=id;
  this.name=name;
 }
  public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @Override
 public int compareTo(Employee e) {
 Integer i= this.getId();
 Integer j=e.getId();
     if (this.getId() == e.getId())
       return 0;
      if (this.getId() < e.getId())
        return 1;
      if (this.getId() > e.getId())
       return -1;
      return 0;
 }

}

Here I am taking another class Main.Here I am adding objects to the My list

package com.oops;
import java.util.ArrayList;  
import java.util.Collections;
import java.util.Iterator;
import java.io.*;  
  
class Main{  
public static void main(String args[]){  
  
ArrayList al=new ArrayList();  
al.add(new Employee(101,"Indhu"));  
al.add(new Employee(106,"Sindhu"));  
al.add(new Employee(105,"Swathi"));  
  
Collections.sort(al);  
Iterator itr=al.iterator();  
while(itr.hasNext()){  
Employee st=(Employee)itr.next();  
System.out.println(st.id +" "+st.name );  
  }  
}  
}  

Output:
Indhu
Swathi

Servlet Architecture


  • Servlets read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.
  • Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.
  • Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
  • Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
  • Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

Servlet API:

  • Servelt API contains three packages 
  • javax.servlet: Package contains a number of classes and interfaces that describe the contract
    between a servlet class and the runtime environment provided for an instance of such a class a
    conforming servelt container.
  • javax.servlet.aanotation: Package contains a number of annotations that allow users to use
    annotations to declare servlets , filters, listeners and specify the metadata for the declared component
  • javax.servlet.http: Package contains a number of classes and interfaces that describe and define the contract between a servlet class rnning under the HTTP protocal and the runtime environment provided for an instance of such class by a confirming servlet container.

Interfaces present in javax.servlet:

  • AsyncContext
  • AsyncListener
  • Filter
  • FilterChain
  • FilterConfig
  • RequestDispatcher
  • Servlet
  • ServletConfig
  • ServletContext
  • ServletContextAttributeListener
  • ServletContextListener
  • ServletRequest
  • ServletRequestAttributeListener
  • ServletRequestListener
  • ServletResponse
  • SingleThreadModel

Classes present in javax.servlet:

  • AsyncEvent
  • ServletInputStream
  • ServletOutputStream
  • GenericServlet
  • ServletContextEvent
  • ServletContextAttributeEvent
  • ServletRequestAttributeEvent
  • ServeltRequestEvent
  • ServletRequestWrapper
  • ServeletResponseWrapper
  • SessionCookieConfig

Exceptions:

  • ServletException
  • UnavilableException

 Interfaces present in javax.servlet.http:  

  • HttpServletRequest 
  • HttpServletResponse
  • HttpSession
  • HttpSessionBindingListener
  • HttpSessionContext
  • HttpSessionListener
  • HttpSessionActivationListener
  • HttpSessionAttributeListener

Classes present in javax.servlet.http:

  • Cookie
  • HttpServlet
  • HttpServletRequestWrapper
  • HttpServletResponseWrapper
  • HttpSessionBindingEvent
  • HttpSessionEvent
  • HttpUtils

Annotation types declared in javax.servlet.annotation package

  • InitParam
  • ServletFilter
  • WebServlet
  • WebservletContextListener
Servlet







    write a program to create singleton class?






    Check this singleton design pattern explained with programs and steps

    public class Singleton {

    static Singleton obj;
    private  Singleton(){
    }

    public static Singleton getInstance(){
    if(obj!=null){
    return  obj;
    }
    else{
    obj=new Singleton();
    return obj;
    }
    }

    public static void main(String[] args) {

    Singleton obj=Singleton.getInstance();
    Singleton obj1=Singleton.getInstance();

    if(obj==obj1){
    System.out.println("indhu");
    }
    else{
    System.out.println("Sindhu");
    }
                   System.out.println(obj==obj1);

    }
    }


    Output:
    indhu
    true

    What is servlet

    • Servlet is a web technology from Sun microsystems(On January 27, 2010, Sun was acquired by Oracle Corporation)
    • Servlets is a Java based web technology to develop server side programs to make a website interactive.
    • Servlet is an API.
    • Servlet is aspecification.
    • Any java based interactive website can be loaded into any brand web servlet without changing the single line of source code as web server is developed according to servlet specification.
    • Servlet is a J2EE technology.

      Web container:

    • Web container is a software that comprises of three modules 
    1. web server
    2. Servlet Engine/ servlet container
    3. Jsp  Engine / Jsp container


    Servlet engine:

    • servlet  java engine is specialized software developed according to  specification
    • A jsp engine is a  specialized software developed according to  specification
    • jsp engine execute s jsps

    General duties of servlet:

    • To make website interactive a servlet performs the folowing duties in general
    1. Capturing the user input
    2. communicating with database
    3. processing of data
    4. producing a dynamic page
    5. Handling over the dynamic page to the webserver

    Swap two numbers in java example

    This is a Java program that illustrates situations where two numbers will be swapped.

    Explaining Different Swapping Methods: 

    Using a Temporary Variable
    • Store a number in a temporary variable.
    • Swap the values by assigning them correctly as follows exactly the same workmethod 
    Without a Temporary Variable (Using Arithmetic):
    • Adding and subtracting to swap in arithmetic
    • Risk: Possible overflow for large number if that number you see is right due to introduction extra space (for temporary variable)
    Using Bitwise XOR:
    • XOR is an efficient solution to swapping numbers.
    • Applies to int types
    Using a Single Statement:
    • use of arithmetic.
    • Single line swap, no extra variable required.

    Swap two numbers in Java example program 

    1. import java.util.Scanner;

    2. public class SwapNumbers {
    3.     
    4.     // Swap two numbers in java using a temporary variable
    5.     public static void swapWithTemp(int a, int b) {
    6.         System.out.println("Before Swap: a = " + a + ", b = " + b);
    7.         int temp = a;
    8.         a = b;
    9.         b = temp;
    10.         System.out.println("After Swap: a = " + a + ", b = " + b);
    11.     }

    12.     // Swap two numbers without using a temporary variable (using arithmetic operations)
    13.     public static void swapWithoutTemp(int a, int b) {
    14.         System.out.println("Before Swap: a = " + a + ", b = " + b);
    15.         a = a + b;
    16.         b = a - b;
    17.         a = a - b;
    18.         System.out.println("After Swap: a = " + a + ", b = " + b);
    19.     }
    20.     
    21.     // Swap two numbers using bitwise XOR operator
    22.     public static void swapWithXOR(int a, int b) {
    23.         System.out.println("Before Swap: a = " + a + ", b = " + b);
    24.         a = a ^ b;
    25.         b = a ^ b;
    26.         a = a ^ b;
    27.         System.out.println("After Swap: a = " + a + ", b = " + b);
    28.     }

    29.     // Swap two numbers in java using a single statement (tuple swap)
    30.     public static void swapSingleStatement(int a, int b) {
    31.         System.out.println("Before Swap: a = " + a + ", b = " + b);
    32.         b = (a + b) - (a = b);
    33.         System.out.println("After Swap: a = " + a + ", b = " + b);
    34.     }

    35.     public static void main(String[] args) {
    36.         Scanner scanner = new Scanner(System.in);
    37.         System.out.print("Enter first number: ");
    38.         int num1 = scanner.nextInt();
    39.         System.out.print("Enter second number: ");
    40.         int num2 = scanner.nextInt();

    41.         System.out.println("\nSwapping using a temporary variable:");
    42.         swapWithTemp(num1, num2);

    43.         System.out.println("\nSwapping without using a temporary variable:");
    44.         swapWithoutTemp(num1, num2);

    45.         System.out.println("\nSwapping using XOR operator:");
    46.         swapWithXOR(num1, num2);
    47.         
    48.         System.out.println("\nSwapping using a single statement:");
    49.         swapSingleStatement(num1, num2);

    50.         scanner.close();
    51.     }
    52. }


    Select Menu