ServletConfig


  • Request parameters are used by the servlet  to receive data from client to process the request.
  • Some specific data must be supplied to the servlet at the time of initialization of the servlet and this data is specific to the client.But data is not supplied by the client via request parameters
  • Use initialization parameters to supply the data to the servlet at the time of initialization of the servlet. initialization parameters are set in deployment descriptor   (Web.xml).
  • Servlet can access these parameters during the run time
  • Request parameters change form Request to request 
  • Initialization parameters change from servlet to servlet.
ServletConfig

Configure  Initialization parameters in Web.xml file:

ServletConfig

ServletConfig Methods :

  1. public String getInitParameter(String name): Returns a String containing value of the named parameter, or null if the parameter does not exist.
  2. public Enumeration getInitParameterNames(): Returns names of the servlets initialization parameters as an enumeration of String objects, or an empty enumeration if servelt has no initialization
  3. public String getServletName():Returns the name of the servlet.
  4. public ServletContext getServletContext():Returns an object of ServletContext.

 

How to get Initialization parameters:

  • To access initialization parameters of a servlet we use servelt config object.
  • ServletConfig is an interface defined by javax.servlet package and this interface is implemented by container.
  • ServletConfig is the object of the class that implements ServletConfig interface and this object is created by servlet conatainer with servlet init() method parameters.
  • For each servlet One ServletConfig object is created by the container.
        ServletConfig sc=getServletConfig();
        String s=sc.getInitParameter("email");
     
To get all values:

       ServletConfig config=getServletConfig(); 
       Enumeration<String> e=config.getInitParameterNames(); 
       String names=""; 
       while(e.hasMoreElements()){ 
       str=e.nextElement(); 
       out.print("<br>Name: "+str); 
       out.print(" value: "+config.getInitParameter(names)); 
    }








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
    Select Menu