DAO Layer Explained
: DAO stand for Data Access Object, it is design pattern. The DAO contains a connection to a database and basic operation on the database. The other layer of the application can interact with the database by making an object of DAO class and calling their required method only. It is an important part of the application. It completely hides the data access logic / code from other part of the application. The
user / developer can only access their code through their API.

Data Access Object is a technique which separate the data access logic and object persistence. It also
provides the flexibility to change application prospective without effecting rest of the part of the
application. It provides a very simple and consistence API. Because of its simplicity it has become a
mandatory parts of a web application.

The DAO centralize all the operation on the database.
In the present project the DAO class gets connection from the connection factory class (It holds a
connection). The bean class gives the data on which operation is performed. Finally DAO class
performs the operation on the database and returns the response to the other layer of the application.
The internal processing of Data Access Object is given below.

One of the great advantage of DAO is the, you do not require to write a code for database connection
on every where, you just make an object of DAO class and call the required method to perform
operation on database.

2: What does load-on-startup element mean in web.xml?
– What does the ‘load-on-startup’ element mean in web.xml?
Answer: This element of the Deployment Descriptor (web.xml) is used to determine the order of
initializing the particular servlet when the application server starts up. The content of this element is
expected to be a positive integer and lower the number, earlier the particular servlet will be initialized
during server start up.

If the content is not a positive integer (or if no value is specified as the content) then the application
server is free to initialize the servlet any time it wants during the server start up.
This maybe an application server dependent thing… but, I guess it’s the same for almost all popular
application servers currently being used like WebLogic, WebSphere, Oracle Application Server 10g,
load-on-startup for Servlets:
<servlet id=”servlet1”>
load-on-startup for JSPs:

Note you should always set load-on-startup element to be 0 so the servlet is initialized
when the server is started. This will prevent any delay for the first client which uses the

MVC Architecture
The main aim of the MVC architecture is to separate the business logic and application data from the
presentation data to the user.
Here are the reasons why we should use the MVC design pattern.
1. They are resuable : When the problems recurs, there is no need to invent a new solution, we just have to follow the pattern and adapt it as necessary.
2. They are expressive: By using the MVC design pattern our application becomes more expressive.

5. What is need of DAO? Write one simple DAO example?
DAO(Data Access logic) provide the machanism to saperate our bussiness logic from data access logic and both code can be change independently that lead to flexibility in our application. and it also provide security because when will see spurce code from web page only the business logic can be seen and cant see the data access logic . and it also provide reusability – DAO: Data Access Object. here the main concept of DAO is to

communicate with the database. DAO mainly contains
1.) DAOFactory: this specifies which kind of database (wether MySQL or ORACLE or MSSQL etc…).

2.) SQLFactory: which extends the DAOFactory. Here we do all the connection stuffs.deciding the driver, hostname, URL, username, password etc and also getting the Connection object.

3.) AdminDAO: this is a interface where we declare all the methods which we need in our application to perform all the database related operation.

4.) SQLAdminFactory: this implements the AdminDAO interface, all its method. this also gets the connection from SQLFactory.

5.) TransactionControlDAO: here we keep the commit and rollback methods.

if required…
6) ConnectionConstant: in this file we can mention the file name (.properties file) where we keep the connection detals, like hostname, username, password, etc…

6. Why do we use DAO?
: If i want to hide the persistence logic from other components and reduce the direct dependency  to implementflexible system with less maintenance in future then we use DAO. Using DAO to encapsulates all access to the persistence store and regardless what type of data store you used DAO provide uniform API to its client.

DAO completely hides the data store implementation from its client.When data store implementation is changed, no modification is required in the clients of DAO because DAO will be exposed to the client as an interface which will not be changed.

Only changes is its DAOimplementation. – Access to data varies depending upon the source of data (Relational Database, Object Oriented Database, Flat File and Business to Business integration systems). Such disparate data sources offer challenges to create a direct dependency between application code and data access code. Including the connectivity and data access code within application code introduces a tight coupling between the components (JSP, Servlet or Struts Action) and the data source implementation. Such code dependencies
in components make it difficult and tedious to migrate, the application from one type of data source to another. Data Access Object (DAO) makes abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data. The DAO acts as an adapter between the application components (JSP, Servlet or Struts Action) and the data source.




Question: What is a Session?
Answer: A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications the default time-out value for session variable is 20 minutes, which can be changed as per the requirement.

Question: What is Session ID?
Answer: A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages. 

Question: What is Session Tracking?
Answer: HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called “Session Tracking” which helps the servers to maintain the state to track the series of requests from the same user across some period of time. 

Question: What  are different types of Session Tracking?
Answer: Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions

Question: What is HTTPSession Class?
HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user. 

Question: Why do u use Session Tracking in HttpServlet?
Answer: In HttpServlet you can use Session Tracking to track the user state. Session is required if you are developing shopping cart application or in any e-commerce application.

Question: What are the advantage of Cookies over URL rewriting?
Answer: Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.

Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not.

In url  rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.

Question: What is session hijacking?
If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user’s Web application session while that session is still in progress.

Question: What is Session Migration?
Answer: Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.

Question: How to track a user session in Servlets?
Answer: The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HttpSession session = req.getSession(true);

Question: How you can destroy the session in Servlet?
Answer: You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate();

What is use of serialVersionUID

Reference URL : During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass’s computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:

  • Add fields
  • Change a field from static to non-static
  • Change a field from transient to non-transient
  • Add classes to the object tree

List of incompatible changes:

  • Delete fields
  • Change class hierarchy
  • Change non-static to static
  • Change non-transient to transient
  • Change type of a primitive field

So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly metion the suid using the statement:

private final static long serialVersionUID = <integer value>

then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Reference URL : If you ever implemented Serializable interface, you must encounter this warning message

The serializable class xxx does not declare a static final serialVersionUID 
field of type long

So…what is serialVersionUID?

The serialVersionUID is used as a version control in a Serializable class. If you do not explicitly declare a serialVersionUID, JVM will did it for you automatically, based on various aspects of your Serializable class, as describe in the Java(TM) Object Serialization Specification.

SerialVersionUID Example

The above statement is a bit hard to understand at the beginning (as least i did), let start an example to understand how Serializable class use SerialVersionUID to implement version control.

1. Address.java

A serializable class with a serialVersionUID of 1L.

import java.io.Serializable;

public class Address implements Serializable{

	   private static final long serialVersionUID = 1L;

	   String street;
	   String country;

	   public void setStreet(String street){
		   this.street = street;

	   public void setCountry(String country){
		   this.country = country;

	   public String getStreet(){
		   return this.street;

	   public String getCountry(){
		   return this.country;

	   public String toString() {
    	   return new StringBuffer(" Street : ")
    	   .append(" Country : ")

2. WriteObject.java

A simple class to write / serialize the Address object into a file – “c:\\address.ser”.

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class WriteObject{

	public static void main (String args[]) {

	   Address address = new Address();
	   address.setStreet("wall street");
	   address.setCountry("united state");


	        FileOutputStream fout = new FileOutputStream("c:\\address.ser");
		ObjectOutputStream oos = new ObjectOutputStream(fout);

	   }catch(Exception ex){

3. ReadObject.java

A simple class to read / deserialize the Address object from file – “c:\\address.ser”.

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class ReadObject{

   public static void main (String args[]) {

	   Address address;


		   FileInputStream fin = new FileInputStream("c:\\address.ser");
		   ObjectInputStream ois = new ObjectInputStream(fin);
		   address = (Address) ois.readObject();


	   }catch(Exception ex){


Let do some testing to demonstrate the use of serialVersionUID.

1. Same serialVersionUID

Same serialVersionUID , there are no problem during deserialization process

javac Address.java
javac WriteObject.java
javac ReadObject.java
java WriteObject
java ReadObject
Street : wall street Country : united state

2. Different serialVersionUID

In Address.java, change the serialVersionUID to 2L (it was 1L), and compile it again.

javac Address.java
java ReadObject
java.io.InvalidClassException: Address; local class incompatible:
stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
        at ReadObject.main(ReadObject.java:14)

The “InvalidClassException” will raise, because you write a serialization class with serialVersionUID “1L” but try to retrieve it back with updated serialization class, serialVersionUID “2L”.

The serialVersionUID have to match during the serialization and deserialization process.

Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?
–     It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don’t provide serialVersionUID in our code java compiler will generate it and normally it’s equal to hash code of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.

What is serialVersionUID? What would happen if you don’t define this?
– SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object .  serialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also.  Consequence of not specifying  serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.


package com.serializable_expl;

import java.io.Serializable;
public class NameStore implements Serializable

    private static final long serialVersionUID = 9024561712115377771L;

    private String firstName;
    private transient String middleName;
    private String lastName;

    public NameStore (String fName, String mName, String lName)
        this.firstName = fName;
        this.middleName = mName;
        this.lastName = lName;

    public String toString()
        StringBuffer sb = new StringBuffer(40);
        sb.append("First Name : ");
        sb.append("   Middle Name : ");
        sb.append("   Last Name : ");
        return sb.toString();



package com.serializable_expl;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TransientExample

    public static void main(String args[]) throws Exception 
        NameStore nameStore = new NameStore("Steve","Middle","Jobs");
        ObjectOutputStream o = 
                 new ObjectOutputStream(new FileOutputStream("nameStore"));
        // writing to object
        System.out.println("Serialization of Object is done..!");

        // reading from object
        ObjectInputStream in =
                   new ObjectInputStream(new FileInputStream("nameStore"));
        NameStore nameStore1 = (NameStore)in.readObject();

        System.out.println("DeSerialization of Object is done..!");

Output  :-

Serialization of Object is done..!
First Name : Steve   Middle Name : null   Last Name : Jobs
DeSerialization of Object is done..!

If you need more in detail Examples then refer below mention URL :  Reference URL