DAO

REFERENCE
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,
etc.
load-on-startup for Servlets:
……
<servlet id=”servlet1”>
<servlet-name>NameOfTheServlet</servlet-name>
<display-name>DisplayNameOfTheServlet</display-name>
<servlet-class>FullyQualifiedServletClassName</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
……
load-on-startup for JSPs:
……
<servlet>
<servlet-name>NameOfTheServletGenerated</servlet-name>
<jsp-file>RelativePathOfTheJSPFile</jsp-file>
<load-on-startup>3</load-on-startup>
</servlet>

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
application.

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?
Ans.
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?
Ans
: 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.

Session

http://www.roseindia.net/interviewquestions/servlet/session-tracking.shtml

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?
Answer:
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?
Answer:
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();

Java IMP

What is the difference between ResultSet and RowSet ? Reference URL:

A ResultSet maintains a connection to a database and because of that it can’t be serialized and also we cant pass the Resultset object from one class to other class across the network.

RowSet is a disconnected, serializable version of a JDBC ResultSet and also the RowSet extends the ResultSet interface so it has all the methods of ResultSet. The RowSet can be serialized because it doesn’t have a connection to any database and also it can be sent from one class to another across the network.

More on RowSet:

A RowSet can be * connected * or *disconnected*
A *disconnected* rowset gets a connection to a data source in order to fill itself with data or to propagate changes in data back to the data source, but most of the time it does not have a connection open. While it is disconnected, it does not need a JDBC driver or the full JDBC API, so its footprint is very small. Thus a rowset is an ideal format for sending data over a network to a thin client.
A connected RowSet is like a wrapper around the ResultSet.
Implementation:
A CachedRowSet class—a disconnected rowset that caches its data in memory; not suitable for very large data sets, but an ideal way to provide thin Java clients, such as a Personal Digital Assistant (PDA) or Network Computer (NC), with tabular data

A JDBCRowSet class—a connected rowset that serves mainly as a thin wrapper around a ResultSet object to make a JDBC driver look like a JavaBeans component

A WebRowSet class—a connected rowset that uses the HTTP protocol internally to talk to a Java servlet that provides data access; used to make it possible for thin web clients to retrieve and possibly update a set of rows

From the above answer it seems that RowSet is far better than ResultSet. Ofcourse it is correct but there are some situations where we need to use ResultSet only.

For example when we are querying the database using the ResultSet object, as it is connected to the database until the object is open and it does not contain all the data from your query. Since it has a connection to the database, when you run the next() method if the ResultSet needs more data it can go to the database and get it. The RowSet can’t do that since it isn’t connected to the database so it must load and hold all the data from your query as soon as you run the execute() method. If your query returns a lot or rows you could encounter very slow processing and out of memory errors. However, if the number of rows to be returned is a reasonable number then a RowSet can be used.

By javaguideadmin Posted in Struts2

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;
	   }

	   @Override
	   public String toString() {
    	   return new StringBuffer(" Street : ")
    	   .append(this.street)
    	   .append(" Country : ")
    	   .append(this.country).toString();
	   }
}

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");

	   try{

	        FileOutputStream fout = new FileOutputStream("c:\\address.ser");
		ObjectOutputStream oos = new ObjectOutputStream(fout);
		oos.writeObject(address);
		oos.close();
		System.out.println("Done");

	   }catch(Exception ex){
		   ex.printStackTrace();
	   }
	}
}

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;

	   try{

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

		   System.out.println(address);

	   }catch(Exception ex){
		   ex.printStackTrace();
	   }
   }
}

Testing

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.


NameStore.java

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(this.firstName);
        sb.append("   Middle Name : ");
        sb.append(this.middleName);
        sb.append("   Last Name : ");
        sb.append(this.lastName);
        return sb.toString();
    }

}

TransientExample.java

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
        o.writeObject(nameStore);
        System.out.println("Serialization of Object is done..!");
        o.close();

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

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

        in.close();
    }
}
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