Saturday, June 30, 2012

Session Tracking using Cookies

Cookies are piece of information sent by any web application to a web browser. and this information is further used to track the client state(data).
In my last post i wrote about session tracking with the help of hidden form fields but i also mentioned there that the hidden form fields are not effective in most of the situations.
So cookies are our next hope and cookies are nice indeed as they sound, I am going to discuss how.

Whenever a client or end user sends a request to a web application by supplying some information in the form of request body or through URL.
The web appliction does :
  • Grab all the information from the request body or URL(Depends on the request method either get or post).
  • Create cookies for each of these information elements.(!! creating cookies is far easy you will see very soon)
  • Now that the information is encapsulated in the cookies the web application sends these cookies back to the requesting browser as a response.  
 Now the browser plays its role :
  • The duty of browser is to store the cookies received from the web-application in some private location with Domain name and path of web-application from where the cookies arrived.
  • Now when the cookies are stored,whenever next request is made from the same browser to the same domain the browser automatically embeds all the cookies matching that particular domain to the request body.
  Note: Every Browser keep its cookies separately. ex. Internet Explorer don't share its cookies with Mozilla or any other,and same is the case with any other browser.

pictorial representation of cookie transfer mechanism

As you can observe above the mechanism of cookies is very simple.This was the general concept of how the cookies work.This concept remain same, doesn't matter on whether you use JAVA, PHP or .net.

But i am totally java oriented person so Lets relate the concept of cookies with the java technology.

Cookie : is a class in java come with javax.servlet.http package with one and only two argument constructor.
Cookie(String ,"value"); 
second argument to the constructor can be of any type i.e String,int,double,float,boolean etc.
>> Creating a cookie:
You can't create a cookie object without providing these two arguments i.e name and value.
Syntax for creating a Cookie object is :

Cookie cuki=new Cookie("uasername","wilson");

in the above line of java code "cuki" is a complete cookie with name "username" and value "wilson".

Every cookie in the world is created in the same way as shown above.

>> Now the second minor challenge is to pass the cookie to the browser back.

we do it like this:

response.addCookie("reference to cookie object");

After adding the cookie to the response the role of Server side application is almost over.
>> Now the browser will store the cookie in a predefined fashion
that is:
whenever the browser receives a cookie it first checks whether there is prior cookie from the same domain with same name.

case1: if a cookie is already present there with same name and domain
          browser just replace it with the new one.
case2: if the cookie is new to the browser then it stores the cookie normally.

>> After storing the cookie,the prime duty of browser is to attach all the associated cookies for a domain to any of request made for that domain.

>> And the web application utilizes these cookies to identify client states.

This was all theoretical view of working of cookies.
now its time for a real and working example which will show you the complete picture:

//index.html the starting page.

<%@page language="java"%>
<title>cookies tutorial</title>
<body bgcolor="gray">
<form name="login" action="Storecookies">
UserName:<input type="text" name="uname"/><br/>
Password: <input type="password" name="pass"/><br/>
<input type="submit" value="login"/>

// this is the source of Storecookies servlet.

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class Storecookies extends HttpServlet
    public Storecookies(){
    public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException
        Enumeration paras=req.getParameterNames();
        PrintWriter pw=resp.getWriter();
        String rem=req.getParameter("remember")
                String pname=(String) paras.nextElement();                                                  
                String pvalue=req.getParameter(pname);                                                      
                Cookie c=new Cookie(pname,pvalue);                                                           
            pw.write("<b>cookies are stored successfully</b>");                                            
            pw.write("<a href='Showcookies'>show me the cookies</a>");                               

// Source of Showcookies Servlet.

import javax.servlet.http.*;
import javax.servlet.*;
public class Showcookies extends HttpServlet
    public void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
        Cookie c[]=req.getCookies();
        PrintWriter pw=resp.getWriter();
        pw.write("<html><body bgcolor='gray'>");
        for(int i=0;i<c.length;i++)
            String name=c[i].getName();
            String value=c[i].getValue();
            pw.println(name+" -> "+value+"<br/>");

    public void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException


// web.xml file with Servlet mappings

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns=""
 xmlns:xsi="" xsi:schemaLocation="">
  <description>just testing servlets</description>

This was a Simple application imlementing cookies to store client data.You can easily Deploy this simple and ready made application and checkout the outcome.

Now i want to add some methods which are provided by Cookie class for providing advance control over cookies.

>>What is Age for a cookie?

Its the time period for which the browsers keep a cookie and after expiring of that time period they delete the cookie.
We can set Maximum age for any cookie using the below method

setMaxAge(time in seconds);

Default MaxAge for any cookie is -1 which instructs browser to keep the cookie till the browser is running,once the browser is closed cookie is lost.

>> We can set Domain name for a cookie explicitly if we like to do so.otherwise its automatically set by the web containers. 

setDomain("Domain name");

>> We can decide the paths for which the browser should send the cookie within a applicatin,like if you want a cookie to be sent only for the login page in your web can do it like this


>> Cookies are of two types secured and insecure
Secured cookies use https(hypertext secure socket layer) protocol.But cookies are insecure by default.

setSecure("boolean"); //provide true as argument to make a cookie secure.

>> To get value of a cookie object we use the below method on the cookie object:


>> To get name of a cookie :

>> If you want to know MaxAge of a cookie use 


 support by providing your valuable feedback !!

Thursday, June 28, 2012

Session Tracking

What is Session ?

Session is nothing But the time for which a client is recognizable to the web application.
When a client first time makes a request for some web resource by providing some information about itself the Session starts, and when the serving web application loses information about the client the session ends.
For example : when you click on login button after providing a valid email id and password in the Gmail login screen your session is started, because from that time onward google can recognize you untill you logout. 

Here in this Post you will learn about the requirement of session tracking and various mechanisms to achieve session tracking.

What is Session Tracking ? 

Session tracking is mechanism of tracking the client provided data and making it available to the next request from the same client.and this process is continued until the user choose to LogOut or terminate the session.

Why we need Session Tracking ?

Hypertext Transfer Protocol(HTTP) we all are familiar with this protocol because it is totally unavoidable.
The must know characteristic of HTTP is its stateless nature.
Stateless means it can't sustain a relationship with the clients.HTTP protocol sends a response back to a client and then it just forget about this activity, and go for serving next request. 

StateLess nature of Http protocol
If our requirement is limited to static content only then HTTP is very effective because it is faster than any other protocol,but what to do if you want to be recognized by the application you are using on the web.
like if you want to reserve air tickets and you are on website of Kingfisher Airlines,how would you feel if they ask you for your account information and then shows you a welcome note, obviously you will feel good to be welcomed
but what happens if they just forget about you on the next request and again ask you to provide account information,everybody is supposed to lose patience at that time this is also obvious.
So the Conclusion is,we need to maintain client data to design effective dynamic applications.

Session tracking mechanisms :

1. Hidden Form Fields.
2. Cookies.
3. URL rewriting.
4. HttpSession interface.

Hidden Form Fields Mechanism: as we are aware about html forms,they are used to accept input from client or end user.
Form fields are of three types regular,password and hidden.
we can define them like this:
<input type="text" name="<any anme>" value="<default value>"/>
<input type="password" name="<any name>" value="<default value>"/>
<input type="hidden" name="<any name>" value="<value of field>"/>
 The last one with type="hidden" is not displayed by the browser while rendering the response.So these hidden form fields become effective tools to embed information about the client inside the html forms without displaying it to the end user.
The wonderful quality of hidden fields is,they are automatically sent with the request object along other fields when user clicks on the submit button.

here is an example of a simple servlet based application using hidden form fields to maintain client data.

Bank account refilling application

In the above sample application flow diagram,first of all user sees a login form:
<form action="Authorization" method="post">
<input type="text" name="userid"/>
<input type="password" name="upasswd"/>
<input type="submit" value="login"/>

User name:

when the user click on login the control goes to Authorization servlet which accesses database to match the input data and if the data provided by the user is valid it produces a dynamic html form like this:
<form action="refill" method="post">
<input type="hidden" value=request.getParameter("userid")/>
<input type="text" name="bank"/>
<input type="text" name="amount"/> 
<input type="submit"/>

Bank name:
Amount to be Filled:

when the user clicks on the refill button the control automatically goes to refill servlet which then communicate with database to refill the account of client with userID embedded in the hidden form field.

So now i think its clear to you that how the information is shared between multiple requests using hidden form fields. 

now its time to discuss some drawbacks of this mechanism of hidden form fields

1.It is not supported by hyperlinks :means if the control transfer is through the means of form submission then its k but if a user clicks on an anchor tag then all the information in hidden fields is just lost.
2.We cant track sensitive data like passwords in the hidden form fields because,even a average technical person can view the HTML source of the pages retrieved from server and take out passwords very easily.
3.Useful only if the forms are generated by server side scripts,these hidden fields are of no use in session tracking if the forms are static. 

The alternative to the mechanism of hidden form fields are :


URL rewriting  

HttpSession interface.

Wednesday, June 27, 2012

Environment variables

Environment variables:

These are variables which controls the behavior of applications and various processes dynamically.
for example %TEMP% environment variable can be used by a processes to store temporary data used by it at the path provided by %TEMP% variable.
Environmental variables enhances the flexibility of applications in two ways: 
1. user can edit the environment variables an application uses to change its behavior,any time.
2. As the environmental variables are external to the applications they are loaded at run-time.So its possible to change the behavior of application without recompiling them.

Note: Environment variables can be provided only specific names which can be detected by the processes which use them.So it is not in our hands to decide the Environment Variable Name but We can change the paths to which Environment variables points.
For Example:     
%HOME% Environment Variable is used by various processes to locate the root user's home directory which is by default "C:\users\<user account>" in every windows operating system.
but we can change this path to any other say:  "d:\home"
but if we attempt to change variable name from %HOME% to any other say %MYHOME% then this Environment Variable is of no use to any process which are coded to use %HOME% Environment variable.

There are many standard Environment variables:

  • HOME (points to the user home directory) 
  • TEMP  or TMP (point to the path used for storing temporary data)
  • NUMBER_OF_PROCESSORS (no of processors deployed in your system)
  • OS (represents Operating System)
       classpath variable is used to locate class files used inside java 
       whenever a class is need to be loaded in a java application the JVM    
       searches for appropriate class file in all locations starting from first path 
       in the CLASSPATH variable.If the class file is present in the current 
       working directory and you dont want JVM to search through all path   
       locations in the CLASSPATH variable just add ".;" to the beginning of 
       your CLASSPATH variable. in ".;" the dot "." represents current working 
       directory and ";" is the separator.
  • path:
          path environment variable is used to provide paths to the executable  
          files and commands of the operating syatem or some other application 
       like Compilers and MySQL. We use path variables for individual 
       commands so that we are not required to provide full directory path 
       every time we execute the commands. 
       Example: we provide path "c:\program files\java\jdk1.6.0\bin" in the   
       path variable because we need to use javac and java commands to 
       compile and execute java applications from command prompt and these 
       executable commands are located inside the bin directory of our java 
       installation directory.after setting path variable we can directly use javac
       and java commands in command prompt like any other DOS command. 
  • USERNAME  (stores the username for admin account)     etc.

Most of the above Environment variables must have are already declared on your system if you will check for them,because these above Environment variables are Operating System oriented.

How to check Environment Variables:
there are two ways
1. Open command prompt
    give command:   set
    It will display all the variables on the console.  
    note:If you want to look at some specific variables for ex. if you want to
    display variables with names starting with character L 
    give command: set L
2. Open control panel
    select System > advance system settings > Environment variables

How to set Environment Variable:
there are two ways
1. Open command prompt
    give command: set <variable name>=<path>
2. Open control panel > system > advance system settings >Environment    
    variables > new
    then provide variable name and value in the fields provided.

How to delete  Environment variable
again there are two ways
1. Open command prompt
    give command: set <variable name to be deleted>=
    this way the value for the variable will be set to null value in other words   
    it will be removed.
2. Open  control panel > system > advance system settings >Environment
    variables  select variable and click on delete.

note: You may have seen environment variable names enclosed in %---%
this syntax is used with those Environment variables which are used in other paths like path=%JAVA_HOME%/bin;
this way %JAVA_HOME% will be automatically replaced with value of JAVA_HOME Environment variable.


Thursday, June 21, 2012

Using Type-4 DB2 driver for Communication between java application and DB2 server

This is my second Post on JDBC the first was based on Type-1 architecture based JDBC Drivers and this one is for Type-4
I suppose that you have Installed the DB2 database server and JDK/JRE on your system if you have not installed yet Do it now,before starting this tutorial.

Now to create an application which can communicate with DB2 server you need
1. JDBC driver.
2. CLASSPATH environment variable of our system set to JDBC driver provided by DB2.
3. Little knowledge of basic JAVA and  following interfaces
    a.) Driver interface.
    b.) Statement and PreparedStatement Interfaces.
    c.) ResultSet Interface.
>> JDBC driver requirement is not a reason to worry,because type-4 drivers are shipped with database products by default by the database vendors.
For your DB2 version you can find it in the installation directory of your DB2
for windows OS it is mostly ->  c:\program files\IBM
then you can find drivers in the SQLLIB\java directory in the IBM folder
the driver names are   db2jcc.jar and  db2jcc_license_cu.jar

>> Now that you have located your drivers you need to add complete path for these driver to the CLASSPATH environment variable of your system.
To do this proceed with following steps:
  1. open control panel.
  2. select system option.
  3. select advanced system settings.
  4. a new small window will pop up select environment variables from here 
  5. now see if there is already a CLASSPATH variable in system or user variables or not
case 1: If it is already there select it to edit and add full path for both the drivers mentioned above separated by a semicolon(;) and save the settings by clicking on ok button.
case 2: If the CLASSPATH variable is not there already create a new one provide the name CLASSPATH to it and add path for both  drivers.

>>Half of your JOB is done already. Its time for coding the application

Keep in mind:
  • Default port no for DB2 is : 50000
  • Host name : localhost ( if the server is on your own machine).
  • Driver URL:
       For type-4 Drivers:
       and for type-2 Drivers it is: 
  • Never forget to close the connection after using it,its not a matter of consideration here in our sample application.but if you are designing some enterprise level application for your employer,and you forget to close the connections then only god can save you from getting fired .. mind it.
import java.util.*;
import java.sql.*;
class test
    public static void main(String args[])
          /* load the driver class and registers the driver with driver pool automatically*/
          /* create a connection object using DriverManager class of java.sql package*/ 
         Connection conn=DriverManager.getConnection("jdbc:db2://localhost:5000/test","hsd","hsdhaka91");
         /*create statement class object and use it to send query to the connected database*/
         ResultSet rs=conn.createStatement().executeQuery("select * from test.employee");
            // access the data records/rows here.          
           // if there is no record in the tablename table this block will not be executed.
        catch(Exception ex)


Same application but without using the DriverManager

import java.util.*;
import java.sql.*;
class test
    public static void main(String args[])
         /* load the driver class,registers the driver with driver pool and creates an object to Driver class*/ obj=new;
        /* Properties  is an inbuilt class in the java.util package used to store properties */
        Properties p=new Properties();
        p.setProperty("user","username");  //provide username as second argument.
        p.setProperty("password","userpassword");   // provide password for the database user
        Connection conn=obj.connect("jdbc:db2://localhost:50000/dbname",p);

        ResultSet rs=conn.createStatement().executeQuery("select * from tablename");
            // access the data records/rows here.
            // if there is no record in the tablename table this block will not be executed.
        catch(Exception ex)

In the second application we are not taking support of DriverManager class to create connection object
but we are directly calling connect("URL",property object); method  to create the connection.
This connect method is a member of Driver class object.

>> You can also use PreparedStatement Interface to increase the user interactivity of your application.

I think This tutorial will be helpful for my readers.
Please provide your valuable Feedback for this post.

Sunday, June 17, 2012

timing events in javascript

setInterval() and setTimeout()

are the two methods available in javascript which we can use to invoke timing events.
setInterval() method takes two arguments,first one is the name of the function to be called after the time interval that we have provided as argument to the setInterval() method of ours.
and Second argument is the time interval itself in milliseconds.
i.e setInterval(functionName(),1000);
It will keep on calling functionName() after every 1000 milliseconds
We can stop this repeated calling of function explicitaly using another javascript method that is
where intervalvar is variable for setInterval()
 var intervalvar=setInterval("function name",1000);

here is an interesting example using setInterval() to implement a slideshow of images:

<title>changing Image</title>
<script type="text/javascript">
 var images= new Array();
 var x=0;
function timer()
    setInterval(function() {slider()},7000);
function slider()
<body onload="timer()">

<image id="slide" src="image.jpg" style="border-style:solid; border-width:5px; border-color:green;" width="500" height="400"/>


setTimeout() is another timing event method,it also accept two arguments function to be called after timeout and time period.
i.e setTimeout(function(),3000);
It will call function() after 3000 milli seconds,but only once ! !

example for setTimeout():

<title>changing Image</title>
<script type="text/javascript">
 var images= new Array();
 var x=0;

 var myinterval;
function timer()

    setTimeout(function(){stopslideshow()},30001);    //setTimeout invoked
function slider()

function stopslideshow()



<body onload="timer()">

<image id="slide" src="image1.jpg" style="border-style:solid; border-width:5px; border-color:green;" width="500" height="400"/>


we can use
clearTimeout(timeoutvar)  to suspend the setTimeout() event.

where timeoutvar=setTimeout("function name",10000);
suppose you have provided 10 seconds of time interval in the setTimeout(function(),10000) and then you invoke clearTimeout(var) before 10 seconds from invoking setTimeout(),the function() will not be executed.

Friday, June 15, 2012

Passing Control Between Web Pages

Forward vs Redirect

These are the two methods of transferring the control between web pages,the purpose of both is almost same but there is some difference which i am going to tell you here.

Redirect: If you want to implement this redirecting process in jsp you have to follow this syntax:
<c:redirect url="targetPageURL">
>> where c is nothing but prefix for core JSTL actions we set at the beginning of every jsp page to use Java Standard Tag Library .

we include tag libraries in our page this way :
<%@taglib prefix="c" uri=""%>
Note:you can provide some other prefix aswell but c is recommended so that you don't catch a reserved keyword.
Now moving to the main point
Redirecting will pass the control to the page specified in the url attribute of tag. This control transfer make browser to request the new page in a formal way,and the address in the address bar of browser changes to the url of new page as the page is loaded. 

<jsp:forward page="targetPageURL"> 
this way the new page will be loaded for processing the same request by the jsp container implicitly without telling Browser of client machine about control transfer.
So the URL in the address bar of the browser will remain same even though new page has been loaded. 
Another specification of foreward method is,it automatically transfers all the parameters with Request scope to the nest page.
Differences b/w both:

Forward Redirect
-> It request the new page implicitly without letting browser know about the control transfer. -> It request the new page with the help of browser in a formal way.
-> URL in the address bar of the browser remain intact indicating previous page. -> URL changes to the new page automatically
-> Transfers all the request parameters to the target page. -> It doesn't transfer request scope parameters to the target page.

Advatage of Forward: It is fast because browser don't interfere in requesting of target page.
Drawback of Forward: URL doesn't change with the loading of target page,so if the user try to refresh the target page,browser will again open the previous page because the URL in the address bar is still indicating  the previous page.

Advantage of Redirect: If user try to refresh the target page,there's no problem.
Disadvantage of Redirect: it is slow because of Request and Response procedure followed by browser adds extra time in loading of target page.

Singleton classes in java

Speaking in a layman's language "classes that stay single throughout their life are called singleton classes" is not wrong at all
As you cant be a layman if you have surfed through here to read about singleton classes.
Here is the technical description for Singleton classes in java:

Classes with their constructor declared as private is called singleton class,simply speaking.

>> As we are aware about the purpose of constructors and consequences of declaring constructor for a class as private.


is a kind of method inside a class with same identifier(name) as of class,constructor is invoked by default whenever we create an object for a class.There can be multiple constructors declared for a single class,each with different no of arguments.
constructors are mostly used to initialize the member variables of the class by using constructors with arguments.

Suppose if there is only one constructor which is declared as private, means what ?
if you know a little about the access specifiers public , private and protected you will say "if the constructor is declared as private, we can't invoke it from outside of the class" 
that's right !!
to create an object of a class we need to call its constructor infact the default constructor is called automatically.
when we write something like
                                                 ClassName obj=new ClassName;
>>This simply concludes that we cant create object from outside of a class with private constructor.

But there is a facility by which we can create a object for a singleton class but keep in mind only one object not more than one !!

Using static bock because static functions of a class can be called from anywhere using the class name even if there is no object existing for the class.
like shown in the java code snippet below:

Class Singleton
         int a;
         String s;
         static Singleton obj;
         private singleton()
        public static singleton getobject()
               return(new singleton());
               System.out.println("object of singleton class already exist");
        public static displaydata()
               System.out.println("a ="+a);
               System.out.println("s ="+s);

Class test
          public static void main(String args[])
                  Singleton obj=singleton.getobject();

object of singleton class already exist

>> whenever a static member of a class is called from outside of the class the class is automatically loaded into the memory.
>> The static content of a class is loaded only once into the memory even if we try to load a class multiple times. 
so in above example:
-> there is a class with name Singleton with private constructor.
-> there is a static member variable obj  of Class Singleton type.
-> when we are calling getobject() method first time from main method present in Test  class,JVM(java virtual machine) look into the memory for class Singleton,if it is already present in the memory or not.
but it is first time we are loading it so JVM will load the class and its static members into the memory with no problem.
-> Now the class is instantiated and the object is returned to the calling function main.
-> If You will try again to call the getobject() method to prove me wrong you   will see a message on the screen
"object of singleton class already exist"

So this is the way singleton classes are implemented and instantiated in realtime applications.

Now you must be thinking !!!
What is the use of defining a singleton class when we can't create objects to use its member functions


We make our class singleton, when our class is to be used by multiple threads of an application.Because if all the threads are allowed to create a separate object of class for themselves then logically they will be working on different set of variables and cant solve the purpose of multiple threading.
For Example: say there is an online shopping website,what they do.They have a products catalog in which all the products which are available in their stock are present and this product catalog is nothing but a class(singleton class).
This product catalog class is shared between every customer(a thread speaking technically) on the website to look for their favorite product because the product catalog is same for every customer,it will not be a good idea if they load the same class separately for each customer.


Tuesday, June 12, 2012

HTTP the logic behind the web

Stands for hypertext transfer protocol uses port no-80
used for communication between a Browser (client) and web servers.
HTTP is stateless protocol:stateless means it doesn't keep track of requests that have been processed or we can say HTTP cant recognize clients,if the same browser is making requests it will not be able to relate them in anyway.
HTTP processes requests and forget about them.
The communication between client and server happens in the form of
  • Request.
  • Response.

Request : is a request message sent by Browser of end user to the server, this request contains following information:

  1. Method of request(get/post).
  2. Browser and Operating system information.
  3. Query parameters.
  4. server address.
  5. URI(uniform resource identifier).
  6. Protocol used for sending request(http).
  7. Port no. used for request.
  8. Security enable/disable information.
  9. cookies.
  10. and many other
example :"hemant"&pass="123456"

Above example is a     http request    for server    ""    for a jsp page named     login.jsp   with two query attributes   name=hemant   and   pass=123456.

Response: Response is to be provided by the web server on the other side.the response may be a simple HTML document or execution of a process,the result of which is then appended to the response.

>> response is to be produced according to the request,where the  request can be a static page,accessing database or updating some database records or some other type.
>> server uses the same port for sending response back to the client which was used by client to send the request. i.e   a http request will always get a http response.
>> if response contains a html document which further contains some images or videos or some other data like shown in the example below:
<img src="" width="200" height="100"/>
<embed src="" width="200" height="100"/>
 then, the image and video which is embedded in the page will be accessed separately with separate requests for each image or  video.
so we can say the html page will be loaded first then the other elements like images and audio video.

Request/response Methods :

1. Get:-

>> this method is most commonly and by default used to request static pages or the requests which don't require any processing from the server.
>> there is no problem if we refresh or request the same page/resources again in the same session.
>> uses URL to append request parameters, and don't use any separate message body for the request parameters.

2. Post:-

>> is most commonly used to transfer form data from client to server for performing some database transaction or some other processing with the form data.
>> uses a separate message body to send request parameters,it don't use URLs to append request parameters contrary to :"hemant"&pass="123456" 
>> Refreshing the page or resending the page requests for pages with html forms can cause troubles sometime,so we use POST method.
POST method always alerts the end user before resending the form data.