How will you write an own immutable class in java ?

Writing an immutable class is generally easy but there can be some tricky situations. Follow the following guidelines:

1. A class is declared final (i.e. final classes cannot be extended).
public final class MyImmutable { ? }

2. All its fields are final (final fields cannot be mutated once assigned).
private final int[] myArray; //do not declare as Æ private final int[] myArray = null;

3. Do not provide any methods that can change the state of the immutable object in any way ? not just setXXX
methods, but any methods which can change the state.

4. The ?this? reference is not allowed to escape during construction from the immutable class and the immutable

class should have exclusive access to fields that contain references to mutable objects like arrays, collections
and mutable classes like Date etc by:

Declaring the mutable references as private.

Not returning or exposing the mutable references to the caller (this can be done by defensive copying)

Wrong way to write a constructor:

public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray; // wrong
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller could change the array after calling the
constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
Right way is to copy the array before assigning in the constructor.
public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray.clone(); // defensive copy
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller cannot change the array after calling the constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
After constructing Numbers are: 1 5
As you can see in the output that the ?MyImmutable? object
has been mutated. This is because the object reference gets

After constructing Numbers are: 1 2
As you can see in the output that the ?MyImmutable? object has not
been mutated.

Wrong way to write an accessor. A caller could get the array
reference and then change the contents:
public int[] getArray() {
return myArray;
}
Right way to write an accessor by cloning.
public int[] getAray() {
return (int[]) myArray.clone();
}

Concept : Beware of using the clone() method on a collection like a Map, List, Set etc because they are not only difficult
to implement but also the default behavior of an object?s clone() method automatically
yields a shallow copy. You have to deep copy the mutable objects referenced by your immutable class.
section for deep vs. shallow cloning and for why you will be modifying the original object if you do not
deep copy.

Abstract class concept in Java

Concept :
we know object of abstract class can not be created. but when we create an obj
of subclass of abstract class then the constructer of super class must be run and since constucter run obj must be created then how can we say obj of abst class can not be created.

Explanation:

Regarding the Abstract Class problem, it's not that an object of an abstract class is never created. By saying that an object of an abstract classes can't be created we mean that they can't be created explicitly and independently. That means you can't have any code creating them independently.

But, as you have mentioned that while creating a subclass object the object of superclass is always created first and abstract classes are also no exceptions in this case. Otherwise you can't access the accessible members of an abstract superclass in an object of any of its subclasses. All right?

You might have noticed that any code trying to instantiate an abstract class explicitly throws a compile-time error, which means the compiler checks the corresponding classes for every direct instantiation and reports errors whenever it finds any of them being anything other than a concrete class. The error may be thrown if it's an abstract class or an interface or something of that sort. Right?

The moral is that the objects of abstract classes are certainly created (otherwise the whole concept of superclass-subclass object creation would go awry), but only implicitly :-)

What I understand is that this check is only at the compiler level, so what'll happen if somebody manages to temper the bytecodes somehow with the addition of direct instantiation code of an abstract class without disturbing the allowed bytecodes format (otherwise the Verifier component of Linker would throw an error)? I'm not sure if that's possible at all. The Verifier is quite conservative in nature and I believe it should be able to recognize even a slight bytecode tempering.

Why wait(), notify() and notifyAll() methods have been defined in the Object class?

Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.

wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.

As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.

Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.

The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.

Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).

Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.

Use of Equals() method in ArrayList in C# | Importance of Equals() method in C# .NET

ArrayList contains method  in c#

Concept : Use of Equals()  method in C#

Look the below code and output

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class employee
    {
        public string name;
        public string id;
        public employee(String name, String id)
        {
            this.name = name;
           
            this.id = id;
        }
      
    }
   
    class ArrayTest
    {
    static void Main()
        {
            ArrayList ar = new ArrayList();
           ar.Add("kumud");
           ar.Add("Raju");
           ar.Add("yugdeep");
      
          Console.WriteLine("Array Contain " + ar.Contains("kumud");
    }

    }
}


Output :
 
   Array Contain  True


Now again look the code below :

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class employee
    {
        public string name;
        public string id;
        public employee(String name, String id)
        {
            this.name = name;
           
            this.id = id;
        }
   
    }
   
    class ArrayTest
    {
    static void Main()
        {
              ar.Add(new employee("sandeep","3"));
              ar.Add(new employee("yugdeep", "3"));
              ar.Add(new employee("kumud", "3"));
           
               Console.WriteLine("Array Contain " + ar.Contains(new employee("sandeep","3"));

        }

    }
}
 

Output :

Array Contain False

Concept :  In case of when we adding string object its come true but in case of adding employe and searching for that particular
           object it comes false , reason behind is that string by default override the object's Equal() method in such way that
          it compare two string and return true but in case of employee class object there is no equals() method override
          ArrayList contain method search the Equals() method in object .so in case of employee there is no Equals() method mechanism
          so it coming False

Now we override Equals() method


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class employee
    {
        public string name;
        public string id;
        public employee(String name, String id)
        {
            this.name = name;
           
            this.id = id;
        }
        public override bool Equals(Object o)
        {
           
            employee e = (employee)o;
          return (e.name.Equals(this.name));
          
        }
      
    }
   
    class ArrayTest
    {
    static void Main()
        {
             ArrayList ar = new ArrayList();
           ar.Add(new employee("sandeep","3"));
             ar.Add(new employee("yugdeep", "3"));
             ar.Add(new employee("kumud", "3"));
      
              Console.WriteLine("Array Contain " + ar.Contains(new employee("sandeep","3"));    }

    }
}

Output :

Array Contain True

Multiple Scenario of try , catch and finally in exception handling in java

Following Below multiple scenario question related to try, catch and finally block in exception handling in java
Scenario #1: try throwing an exception; catch and finally both having return statements


public class TestFinally {

/**
* @param args
*/
public static void main(String[] args) {

System.out.println("Inside main method!");
int iReturned = new TestFinally().testMethod();
System.out.println("Returned value of i = " + iReturned);

}

public int testMethod(){

int i = 0;
try{
 System.out.println("Inside try block of testMethod!");
 i = 100/0;
 return i;
}catch(Exception e){
 System.out.println("Inside catch block of testMethod!");
 i = 200;
 return i;
}
finally{
 System.out.println("Inside finally block of testMethod!");
 i = 300;
 return i;
}
}
}


Output: a return (or any control transfer for that matter) in finally always rules!



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenarios #2: try having exception-free code and a return; catch and finally both have return




...
try{
System.out.println("Inside try block of testMethod!");
i = 100;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
...


Output: did you get the first one right? This is a cakewalk then. With the same logic that any control transfer in finally always rules we can easily predict the output to be similar to that of Scenario #1 with the only difference that in this case the catch block won't be executed as no exception thrown... all right? Here is the output:



Inside main method!
Inside try block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenario #3: try having exception; finally doesn't have a return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: no return in finally means whatever executable return encountered on the way to finally will be executed once finally completes its execution, so the output would be:



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 200


Scenario #4: try and catch both having exception; finally having a return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
...


Output: control transfer in finally overrules the exceptions thrown in try/catch, hence the output would be:



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenario #5: try and catch both having exception; finally NOT having any return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: since no return in finally, hence after the execution of the finally block the sheer need to have an executable return statement (which doesn't exist in this case as catch also has an exception) would throw the exception encountered right before the finally execution started, which would be the exception in catch block in our case...right? So, the output would be:



Exception in thread "main" java.lang.ArithmeticException: / by zero
 at TestFinally.testMethod(TestFinally.java:24)
 at TestFinally.main(TestFinally.java:10)
Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!


Scenario #6: try, catch, and finally all three having exceptions



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i/0;
}
...


Output: evidently the exception would be thrown, but which one? The one which was encountered last i.e., the one encountered in the finally block. Output would be:



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Exception in thread "main" java.lang.ArithmeticException: / by zero
 at TestFinally.testMethod(TestFinally.java:30)
 at TestFinally.main(TestFinally.java:10)


Scenario #7: try and catch both fine; finally doesn't have any return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: well... first thing first. If try is fine, do we need to even think about catch? A BIG No... right? Okay, so we have try and finally blocks to focus on. Let me first show you the output and then we would discuss if you have any doubts. Here is it:



Inside main method!
Inside try block of testMethod!
Inside finally block of testMethod!
Returned value of i = 100

Session tracking in Java application | session concept in java

Plainly because HTTP is a stateless protocol. That means a Web Server handling HTTP requests doesn't maintain contextual info about the client requests coming to it. Putting it differently, the Web Server doesn't have a built-in way to recognize whether the current request is coming from a new client or from a client which has been communicating with it for a while now. This happens because every HTTP request is treated as an altogether new request.


As we can easily imagine that such a behavior can cause so many problems - for example, if a user has logged into his Bank Account and after a successful login if he wishes to go to the Funds Transfer page then he would be required to login again as Funds Transfer would be a login-protected page and the Web Server doesn't have any built-in support for recognizing if the clinet requesting this page is the one who is alraedy logged in or if it's coming from a new client. This is just a simple example... we can easily imagine how difficult will it be to develop a Web-Application without maintaining contextual information about the clients.


What are the various ways of tracking Sessions?


There are three ways of tracking sessions. In other words, there are three ways of maintaining contextual information about clients as a session is nothing but a collection of various information about the particular client the session has been built and maintained for. Three ways of session tracking in servlets are:-

    Using Cookies - Cookies are stored at the client side (in the browser's cache) and they are used to maintain the current session. Every cookie object stores contextual information for that particular session and it's always associated with a unique Session ID, which is sent to the server on creation of the cookie. The server uses that Session ID to locate the cookie at the clinet machine and then it uses the contextual information stored in that cookie object for various purposes including client authentication, client authorization, retrieving/saving data which the client may require in subsequent steps, etc. A timeout period for the cookie objects can be set after which they will become expired. Cookies may be a security threat as the Session ID may be used to track the particular cookie and then to retrieve secure information from it. This is the reason why all the browsers provide options to either enable or disable cookies at the user's discretion. You can simply disable Cookies by updating your browser options.

    Using URL Rewriting - This approach of maintaining sessions requires an extra peice of data to be appended to each URL. This extra info is used to identify the session and the server associates this identifier with the data it has stored for that particular session. The advantage of this approach is that it works even in those cases where the user has disabled cookied for their browsers. In this approach nothing is actually stored at the client side and all the sessio tracking info travels via URLs back and forth. SO, you may obviously lose the session information (the session would have been invalid due to timeout) if you bookmark an URL first and then try to access that later on.

    Using Hidden Form Fields - This is another approach of maintaining session where the contextual data travels via hidden form fields (<INPUT TYPE="hidden" ...). There are two main disadvantages of this approach: One, one can easily see all the data (maybe some secret info) by looking at the HTML Source of the page and Two, this approach will probaly work only for dynamic web pages (how would we maintain different session with unique identifiers otherwise?).

Exception Concept in Java | how try , catch and finally block work in java during exception found

Exception Concept in java

Exception

    +--------+
                    | Object |
                    +--------+
                |
                |
                   +-----------+
           | Throwable |
                   +-----------+
                    /         \
           /           \
          +-------+          +-----------+
          | Error |          | Exception |
          +-------+          +-----------+
       /  |  \           / |        \
         \________/      \______/         \
                            +------------------+
    unchecked     checked    | RuntimeException |
                    +------------------+
                      /   |    |      \
                     \_________________/
                      
                       unchecked


Exception hadling using try, catch, finally


    try {
       // statements that might cause exceptions
       // possibly including function calls
    } catch ( exception-1 id-1 ) {
       // statements to handle this exception
    } catch ( exception-2 id-2 ) {
       // statements to handle this exception
    .
    .
    .
    } finally {
       // statements to execute every time this try block executes
    }

concept:

    Each catch clause specifies the type of one exception, and provides a name for it (similar to the way a function header specifies the type and name of a parameter). Java exceptions are objects, so the statements in a catch clause can refer to the thrown exception object using the specified name.

    The finally clause is optional.

    In general, there can be one or more catch clauses. If there is a finally clause, there can be zero catch clauses.


concept 1;


what will output :

package com.exception;
import java.util.ArrayList;
public class exceptionTest {
   
    public String getName() {
  
    try{
   
     return "kumud";
   
    }
    catch(Exception ex)
    {
    System.out.println("Finally Exception##  try in getName method");
       
    }
    finally
    {
        System.out.println("Finally Exception## finally in getName method");
        return "kumud5";
    }
   
   
    }
   
    public static void main(String [] args)
    {
        ArrayList ar= new ArrayList();
        exceptionTest exp= new exceptionTest();
        try
        {
            System.out.println("Exception is"+exp.getName());
           
               
        }
        catch(Exception ex)
        {
            System.out.println("Exception##"+ex);
           
        }
        finally
        {
            System.out.println("Finally Exception##");
        }
       
    }

}

Output:

Finally Exception## finally in getName method
Exception iskumud5
Finally Exception##

Exp:
    in try block there is return method as well as in finally block also . but output is return from finally block reason behind that finally will execute either
    exception is found or not in any any condition while return value is given in try or catch block.


concept 2:

In which case finally block will not executed

package com.exception;
import java.util.ArrayList;
public class exceptionTest {
   
    public String getName() {
 
    try{
   
        System.exit(0);
     return "kumud";
   
    }
    catch(Exception ex)
    {
    System.out.println("Finally Exception##  try in getName method");
       
    }
    finally
    {
        System.out.println("Finally Exception## finally in getName method");
        return "kumud5";
    }
   
   
    }
   
    public static void main(String [] args)
    {
        ArrayList ar= new ArrayList();
        exceptionTest exp= new exceptionTest();
        try
        {
            System.out.println("Main Try block");
            System.out.println("Exception is"+exp.getName());
           
               
        }
        catch(Exception ex)
        {
            System.out.println("Exception##"+ex);
           
        }
        finally
        {
            System.out.println("Finally Exception##");
        }
       
    }

}


Output:

Main Try block

Expl: if you written System.exit(0) in try block in only that condition finally block will not execute

Thread Creation in Java by Implement Runnable interface

Hi

To create Multiple thread by implement runnable interface in java
Code:


public class Threadtest implements Runnable{
   
    public static void main(String [] args)

    {
        Threadtest t= new Threadtest();
        Thread t1= new Thread(t);
        Thread t2=new Thread(t);
        Thread t3= new Thread(t);
        t1.setName("kumud1");
        t2.setName("kumud2");
        //t3.setName("kumud3");
        t1.start();
        t2.start();
        //t3.start();
       
    }

    public void run() {
        for (int a=0; a<4;a++)
       
        System.out.println("The Current Thread is"+Thread.currentThread().getName());
        try{
        Thread.sleep(5*60*1000000000);
        }
        catch(Exception ex)
        {
           
        }
    }
   
   

}

Searching button using Ajax | How Ajax use in Search and combo list populate in application in Java

Hi Friend
There is Scenario in my application where in Jsp page there is Search button and two combo list ,when we search for department by entering any starting  value populate the all department starting from enter string, and when we select the department . all doctor list will populate doctor list in particular department,
when we select doctor name from list detail of doctor list display in Jsp page



Code:
    DoctorDetail.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
var httpRequest;
function getDepartment()
    {
   
    var searchDep=document.loginform.attachToCaseNo.value;
    if (searchDep==""){
        alert("Please enter Departement to search..");
        document.loginform.attachToCaseNo.focus();
        return;
    }
    var searchKey = "mac";
    searchDep = searchDep.toUpperCase();
    //alert(searchDep);
    var url = "getDep?fano="+searchDep+"&searchKey="+searchKey;
//alert (url);
    if (window.ActiveXObject)
    {

        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {

        httpRequest = new XMLHttpRequest();
    }
    
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function() {processRequest(); } ;
    httpRequest.send(null); 

    }
 function processRequest()
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
       
        {
//alert(httpRequest.responseText)
         var FanoListXML = httpRequest.responseXML.getElementsByTagName("FanoList")[0];
         var comboSize=FanoListXML.childNodes.length;
           
            if (comboSize==0) {
                alert("Please Enter Departement Number");
              
                document.loginform.attachToCaseNo.value="";
                document.loginform.attachToCaseNo.focus();
               var CrListXML = new Array();
                    //updateHTML4(CrListXML);
                FanoListXML=new Array();
                updateHTML(FanoListXML);

                return;
            }
            updateHTML(FanoListXML);
           
        }
        else
        {
            alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
}
 

function updateHTML(FanoListXML)
{

   var len = window.document.loginform.case_id_in_temp.options.length;

    while(len>0) {
        len = len -1;
        window.document.loginform.case_id_in_temp.options[len] = null;
    }//end while       

var CrListXML = new Array();
window.document.loginform.case_id_in_temp.options[0] = new Option("Select","0");

      for (loop = 0; loop < FanoListXML.childNodes.length; loop++) {

       var SNS = FanoListXML.childNodes[loop];
       var fanoId = SNS.getElementsByTagName("FanoId")[0];
       var fanos = SNS.getElementsByTagName("Fano")[0];

        eval(window.document.loginform.case_id_in_temp).options[loop+1] = new Option(fanos.childNodes[0].nodeValue,fanoId.childNodes[0].nodeValue);
 

      
       }
    window.document.loginform.case_id_in_temp.value=window.document.loginform.case_id_in_temp.options[1].value ;
    updateHTML4(CrListXML);
}

//for complainant_respondent name filter
function getDoclist()
    {

    var searchFano=document.loginform.case_id_in_temp.value;
            //searchFano = searchFano.toUpperCase();

         var cr = "C";
           var url = "getDoc?fano="+searchFano+"&cr="+cr;


     if (window.ActiveXObject)
    {
   // alert("jegan");
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
    //alert("jegan1");
        httpRequest = new XMLHttpRequest();
    }
    
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function() {processRequest1(); } ;
    httpRequest.send(null); 

    }
 function processRequest1()
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
       
        {

            var CrListXML = httpRequest.responseXML.getElementsByTagName("CrList")[0];

            updateHTML1(CrListXML);
        }
        else
        {
            alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
}
   
function updateHTML4(CrListXML)
{


   var len = window.document.DealAssistForm.complntNameTemp.options.length;

    while(len>0) {
        len = len -1;
        window.document.DealAssistForm.complntNameTemp.options[len] = null;
}//end while       
// alert(StateNamesXML.childNodes.length);

  window.document.loginform.complntNameTemp.options[0] = new Option("Select","0");
   document.loginform.complntName.value="";
   document.loginform.complntEmail.value="";
   document.loginform.complntFaxNo.value="";
  

return;
}



function updateHTML1(CrListXML)
{

   var len = window.document.loginform.complntNameTemp.options.length;

    while(len>0) {
        len = len -1;
        window.document.loginform.complntNameTemp.options[len] = null;
    }//end while       
// alert(StateNamesXML.childNodes.length);

window.document.loginform.complntNameTemp.options[0] = new Option("Select","0");

      for (loop = 0; loop < CrListXML.childNodes.length; loop++) {

       var SNS = CrListXML.childNodes[loop];
       var crId = SNS.getElementsByTagName("CrId")[0];
       var crn= SNS.getElementsByTagName("CrName")[0];

    eval(window.document.loginform.complntNameTemp).options[loop+1] = new Option(crn.childNodes[0].nodeValue,crId.childNodes[0].nodeValue);
    //window.document.DealAssistForm.fano.options[loop+1] = new Option(fanos,fanoId);

       }
   document.loginform.complntName.value="";
   document.loginform.complntEmail.value="";
   document.loginform.complntFaxNo.value="";
   document.loginform.complntAddress.value="";
  
   
}


//For Getting details of Complainant and Respondent
function getDoclistdetail()
    { //alert("kumud");
    //document.loginform.case_id_in.value=document.loginform.case_id_in_temp.value;
    var fano = document.loginform.case_id_in_temp.value;
    var crSeq=document.loginform.complntNameTemp.value;
            //searchFano = searchFano.toUpperCase();
//alert(crSeq);
if (crSeq=="0") {
alert("Please Select Doctor Name");
return;
}
         var cr = "C";
           var url = "getDocDetail?fano="+fano+"&crSeq="+crSeq+"&cr="+cr;


     if (window.ActiveXObject)
    {
   // alert("jegan");
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
    //alert("jegan1");
        httpRequest = new XMLHttpRequest();
    }
    
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function() {processRequest2(); } ;
    httpRequest.send(null); 

    }
 function processRequest2()
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
       
        {
//alert(httpRequest.responseText)
            var CrListXML = httpRequest.responseXML.getElementsByTagName("CrList")[0];

            updateHTML2(CrListXML);
        }
        else
        {
            alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
}
   

function updateHTML2(CrListXML)
{


       for (loop = 0; loop < CrListXML.childNodes.length; loop++) {

       var SNS = CrListXML.childNodes[loop];

       var crName = SNS.getElementsByTagName("CrName")[0];
               crName = crName.childNodes[0].nodeValue;

     
       var crMail = SNS.getElementsByTagName("CrMail")[0];
            crMail=crMail.childNodes[0].nodeValue;          
       var crFax = SNS.getElementsByTagName("CrFax")[0];
               crFax = crFax.childNodes[0].nodeValue;
           
      
                if (crName == "N/A") {
                        window.document.loginform.complntName.value = "";
                        } else {
                        window.document.loginform.complntName.value = crName;
                        }
       
                if (crMail=="N/A") {
                        window.document.loginform.complntEmail.value = "";
                        } else {
                        window.document.loginform.complntEmail.value = crMail;
                        }
                if (crFax=="N/A") {
                    window.document.loginform.complntFaxNo.value = "";
                } else {
                    window.document.loginform.complntFaxNo.value = crFax;
                }
               
               

       }
   
   
}       

</script>

</head>
<body>


<form name="loginform" method="post">

<table align="center">

<tr>
<td align="center">Enter Departement: <input type="text" name="attachToCaseNo"/><a href="javascript:getDepartment()"><b>Search</b></a> <br/>
                   Select Department:<select name="case_id_in_temp" onchange="getDoclist()">
                                    <option value="">select</option>
                                    </select> <br/>
                 Select Doctor: <select name="complntNameTemp" onchange="getDoclistdetail()">
                                 <option value="">select</option>
                                </select>
</td>                             

</tr>

<tr>
<td align="center">
Doctor Name :<input type="text" name="complntName" value=""/><br/>
Doctor Dep :<input type="text" name="complntFaxNo" value=""/><br/>
Doctor Email :<input type="text" name="complntEmail" value=""/><br/>

</td>


</tr>

</form>



</body>
</html>


Now we create a servlet for every call mention in Jsp page through using AJAX
getDep.java

package com.doc;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class getDep
 */
public class getDep extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public getDep() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(
            HttpServletRequest requestObj,
            HttpServletResponse responseObj)
            throws IOException {
            //set the content type
            responseObj.setContentType("text/xml");

            responseObj.setHeader("Cache-Control", "no-cache");

            //get the PrintWriter object to write the html page
            PrintWriter writer = responseObj.getWriter();

            //get parameters store into the hashmap
            HashMap paramsMap = new HashMap();
            Enumeration paramEnum = requestObj.getParameterNames();
            while (paramEnum.hasMoreElements()) {
                String paramName = (String) (paramEnum.nextElement());
                paramsMap.put(paramName, requestObj.getParameter(paramName));
            }

            String fano = (String) paramsMap.get("fano");
            // for Daily Order, Court Hearing Modification, ,Cause Title, deal Assist , Notices search key
            String searchKey = (String) paramsMap.get("searchKey");
           
            String cond = "";

            ArrayList fanoDtoh = new ArrayList();
            ArrayList caseNos = new ArrayList();
            ArrayList dtoh = new ArrayList();
            ArrayList comboList = new ArrayList();
            Connection con = null;
            //ArrayList districtList=new ArrayList();
            try {
                DAO crDao = new DAO();

                caseNos = crDao.loadCaseListAjax(fano, searchKey);
//                if (caseNos.size()==0) {
//                    requestObj.setAttribute("CasesCombo",comboList);
//                }
            } catch (Exception e) {
                System.out.println(e);
            }

            Iterator it = caseNos.iterator();

            writer.println("<FanoList>");
            while (it.hasNext()) {

                org.apache.struts.util.LabelValueBean l = (org.apache.struts.util.LabelValueBean) it.next();
                String temp = l.getValue();
                writer.println("<FanoD>");

                writer.println("<FanoId>" + l.getValue() + "</FanoId>");
                //writer.println("<Fano>" + l.getLabel() + "</Fano>");
                writer.println("<Fano><![CDATA["+ l.getLabel()+"]]></Fano>");
                writer.println("</FanoD>");

            }
            //    writer.println("<Profile><![CDATA[" + "Jegan1" + "]]></Profile>");
            //close the write
            writer.println("</FanoList>");
            writer.close();
        }

}

getDocDetail.java
package com.doc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class getDocDetail
 */
public class getDocDetail extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public getDocDetail() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(
            HttpServletRequest requestObj,
            HttpServletResponse responseObj)
            throws IOException {
            //set the content type
            responseObj.setContentType("text/xml");

            responseObj.setHeader("Cache-Control", "no-cache");

            //get the PrintWriter object to write the html page
            PrintWriter writer = responseObj.getWriter();

            //get parameters store into the hashmap
            HashMap paramsMap = new HashMap();
            Enumeration paramEnum = requestObj.getParameterNames();
            while (paramEnum.hasMoreElements()) {
                String paramName = (String) (paramEnum.nextElement());
                paramsMap.put(paramName, requestObj.getParameter(paramName));
            }
            String fano = (String) paramsMap.get("fano");
            String crSeq = (String) paramsMap.get("crSeq");
            String cr = (String) paramsMap.get("cr");
            String cond = "";

            ArrayList fanoDtoh = new ArrayList();
            ArrayList caseNos = new ArrayList();
            ArrayList dtoh = new ArrayList();
           
            try {
            DAO daDao = new DAO();

            DocForm da=daDao.loadCaseListAjax2(fano, crSeq);
                   
                   
                String crname = da.getDocName();
                if (crname==null) {
                    crname="";
                }
               
               
               
                String crmail = da.getDocMail();
                if (crmail==null) {
                    crmail="";
                }
               
                String crfax = da.getDocFax();
                if (crfax==null) {
                    crfax="";
                }
               
  
                if (crname.equals("")) {
                    crname = "N/A";
                }
               
               
                if (crmail.equals("") ) {
                    crmail = "N/A";

                }
                if (crfax.equals("")) {
                    crfax = "N/A";
                }
               
               
                writer.println("<CrList>");
               
                writer.println("<CrDesc>");
               
                writer.println("<CrName><![CDATA[" + crname + "]]></CrName>");
               
               
                writer.println("<CrMail><![CDATA[" + crmail + "]]></CrMail>");
               
                writer.println("<CrFax><![CDATA[" + crfax + "]]></CrFax>");
               
               
                writer.println("</CrDesc>");
                writer.println("</CrList>");
                writer.close();
               
            } catch (Exception e) {
                System.out.println(e);
            }
                finally
                {
                   
                   
                }
             
        }
}


GetDoc.java
package com.doc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.util.LabelValueBean;

public class getDoc extends HttpServlet {

    protected void doGet(HttpServletRequest requestObj, HttpServletResponse responseObj)
       throws IOException
{
//set the content type
responseObj.setContentType("text/xml");
responseObj.setHeader("Cache-Control", "no-cache");
PrintWriter writer = responseObj.getWriter();
HashMap paramsMap = new HashMap();
Enumeration paramEnum = requestObj.getParameterNames();
while(paramEnum.hasMoreElements())
{
String paramName = (String)(paramEnum.nextElement());
paramsMap.put(paramName, requestObj.getParameter(paramName));
}

String fano= (String)paramsMap.get("fano");
String cr = (String)paramsMap.get("cr");
ArrayList dtoh = new ArrayList();


//ArrayList districtList=new ArrayList();
try
{
DAO   daDao = new DAO();               
dtoh = daDao.loadCaseListAjax1(fano,cr);
}
catch(Exception e)
{
System.out.println(e);
}

Iterator it =dtoh.iterator();

writer.println("<CrList>");
while(it.hasNext())
{
   
LabelValueBean l=(LabelValueBean)it.next();
String temp=l.getValue();
writer.println("<CrDesc>");

writer.println("<CrId>"+ l.getValue()+"</CrId>");
writer.println("<CrName><![CDATA["+ l.getLabel()+"]]></CrName>");
writer.println("</CrDesc>");


}
writer.println("</CrList>");
writer.close();                    
}        

}