Wednesday, September 26, 2012

c program to find hcf and lcm

C program to find hcf and lcm: The code below finds highest common factor and least common multiple of two integers. HCF is also known as greatest common divisor(GCD) or greatest common factor(gcf)

C programming code

#include <stdio.h>
 
int main() {
  int a, b, x, y, t, gcd, lcm;
 
  printf("Enter two integers\n");
  scanf("%d%d", &x, &y);
 
  a = x;
  b = y;
 
  while (b != 0) {
    t = b;
    b = a % b;
    a = t;
  }
 
  gcd = a;
  lcm = (x*y)/gcd;
 
  printf("Greatest common divisor of %d and %d = %d\n", x, y, gcd);
  printf("Least common multiple of %d and %d = %d\n", x, y, lcm);
 
  return 0;
}

C program to find hcf and lcm using recursion

#include <stdio.h>
 
long gcd(long, long);
 
int main() {
  long x, y, hcf, lcm;
 
  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);
 
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
 
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
 
  return 0;
}
 
long gcd(long a, long b) {
  if (b == 0) {
    return a;
  }
  else {
    return gcd(b, a % b);
  }
}

C program to find hcf and lcm using function
#include <stdio.h>
 
long gcd(long, long);
 
int main() {
  long x, y, hcf, lcm;
 
  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);
 
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
 
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
 
  return 0;
}
 
long gcd(long x, long y) {
  if (x == 0) {
    return y;
  }
 
  while (y != 0) {
    if (x > y) {
      x = x - y;
    }
    else {
      y = y - x;
    }
  }
 
  return x;
}
Output of program:






Wednesday, February 2, 2011

Calendar in JSP

                   Hey Are you anxious for adding calendar in your JSP Program. if so then you don't need to worry more.
Here I am just giving a fabulous solution for you. I am just providing the code of adding a JAVA Script calendar that works on client side and will give you a sophisticated way for entering date in your JSP page without rendering server side execution. And it is just very simple to integrate in your application. 
   I assume that your have a basic Idea about server side and client side code as well as JAVA Script so I haven't mentioned the explanation for the code below. Hope this will remove your pain. If it does then Never forget to comments.

Step 1 :
         Create a java script file in you web content folder and add the code script.

FileName :datepicker.js

var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');


var defaultDateSeparator = "-";        // common values would be "/" or "."
var defaultDateFormat = "mdy"    // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;


function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
  var targetDateField = document.getElementsByName (dateFieldName).item(0);

  // if we weren't told what node to display the datepicker beneath, just display it
  // beneath the date field we're updating
  if (!displayBelowThisObject)
    displayBelowThisObject = targetDateField;

  // if a date separator character was given, update the dateSeparator variable
  if (dtSep)
    dateSeparator = dtSep;
  else
    dateSeparator = defaultDateSeparator;

  // if a date format was given, update the dateFormat variable
  if (dtFormat)
    dateFormat = dtFormat;
  else
    dateFormat = defaultDateFormat;

  var x = displayBelowThisObject.offsetLeft;
  var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;

  // deal with elements inside tables and such
  var parent = displayBelowThisObject;
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop ;
  }

  drawDatePicker(targetDateField, x, y);
}


function drawDatePicker(targetDateField, x, y)
{
  var dt = getFieldDate(targetDateField.value );


  if (!document.getElementById(datePickerDivID)) {
   
    var newNode = document.createElement("div");
    newNode.setAttribute("id", datePickerDivID);
    newNode.setAttribute("class", "dpDiv");
    newNode.setAttribute("style", "visibility: hidden;");
    document.body.appendChild(newNode);
  }

  // move the datepicker div to the proper x,y coordinate and toggle the visiblity
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.position = "absolute";
  pickerDiv.style.left = x + "px";
  pickerDiv.style.top = y + "px";
  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
  pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
  pickerDiv.style.zIndex = 10000;

  // draw the datepicker table
  refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
  // if no arguments are passed, use today's date; otherwise, month and year
  // are required (if a day is passed, it will be highlighted later)
  var thisDay = new Date();

  if ((month >= 0) && (year > 0)) {
    thisDay = new Date(year, month, 1);
  } else {
    day = thisDay.getDate();
    thisDay.setDate(1);
  }

  // the calendar will be drawn as a table
  // you can customize the table elements with a global CSS style sheet,
  // or by hardcoding style and formatting elements below
  var crlf = "\r\n";
  var TABLE = "<table cols=7 class='dpTable'>" + crlf;
  var xTABLE = "</table>" + crlf;
  var TR = "<tr class='dpTR'>";
  var TR_title = "<tr class='dpTitleTR'>";
  var TR_days = "<tr class='dpDayTR'>";
  var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
  var xTR = "</tr>" + crlf;
  var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var TD_title = "<td colspan=5 class='dpTitleTD'>";
  var TD_buttons = "<td class='dpButtonTD'>";
  var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
  var TD_days = "<td class='dpDayTD'>";
  var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var xTD = "</td>" + crlf;
  var DIV_title = "<div class='dpTitleText'>";
  var DIV_selected = "<div class='dpDayHighlight'>";
  var xDIV = "</div>";

  // start generating the code for the calendar table
  var html = TABLE;

  // this is the title bar, which displays the month and the buttons to
  // go back to a previous month or forward to the next month
  html += TR_title;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
  html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
  html += xTR;

  // this is the row that indicates which day of the week we're on
  html += TR_days;
  for(i = 0; i < dayArrayShort.length; i++)
    html += TD_days + dayArrayShort[i] + xTD;
  html += xTR;

  // now we'll start populating the table with days of the month
  html += TR;

  // first, the leading blanks
  for (i = 0; i < thisDay.getDay(); i++)
    html += TD + "&nbsp;" + xTD;

  // now, the days of the month
  do {
    dayNum = thisDay.getDate();
    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
   
    if (dayNum == day)
      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else
      html += TD + TD_onclick + dayNum + xTD;
   
    // if this is a Saturday, start a new row
    if (thisDay.getDay() == 6)
      html += xTR + TR;
   
    // increment the day
    thisDay.setDate(thisDay.getDate() + 1);
  } while (thisDay.getDate() > 1)

  // fill in any trailing blanks
  if (thisDay.getDay() > 0) {
    for (i = 6; i > thisDay.getDay(); i--)
      html += TD + "&nbsp;" + xTD;
  }
  html += xTR;

  // add a button to allow the user to easily return to today, or close the calendar
  var today = new Date();
  var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
  html += TR_todaybutton + TD_todaybutton;
  html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>this month</button> ";
  html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>close</button>";
  html += xTD + xTR;

  // and finally, close the table
  html += xTABLE;

  document.getElementById(datePickerDivID).innerHTML = html;
  // add an "iFrame shim" to allow the datepicker to display above selection lists
  adjustiFrame();
}


/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
  var newMonth = (dateVal.getMonth () + adjust) % 12;
  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
  if (newMonth < 0) {
    newMonth += 12;
    newYear += -1;
  }

  return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}


/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);

  switch (dateFormat) {
    case "dmy" :
      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
    case "ymd" :
      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
    case "mdy" :
    default :
      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
  }
}


/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;

  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
      dateVal = new Date(y, m, d);
    } else if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } catch(e) {
    dateVal = new Date();
  }

  return dateVal;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;

  return dArray;
}


function updateDateField(dateFieldName, dateString)
{
  var targetDateField = document.getElementsByName (dateFieldName).item(0);
  if (dateString)
    targetDateField.value = dateString;

  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.visibility = "hidden";
  pickerDiv.style.display = "none";

  adjustiFrame();
  targetDateField.focus();

  // after the datepicker has closed, optionally run a user-defined function called
  // datePickerClosed, passing the field that was just updated as a parameter
  // (note that this will only run if the user actually selected a date from the datepicker)
  if ((dateString) && (typeof(datePickerClosed) == "function"))
    datePickerClosed(targetDateField);
}


/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(pickerDiv, iFrameDiv)
{
  // we know that Opera doesn't like something about this, so if we
  // think we're using Opera, don't even try
  var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
  if (is_opera)
    return;
 
  // put a try/catch block around the whole thing, just in case
  try {
    if (!document.getElementById(iFrameDivID)) {
      // don't use innerHTML to update the body, because it can cause global variables
      // that are currently pointing to objects on the page to have bad references
      //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
      var newNode = document.createElement("iFrame");
      newNode.setAttribute("id", iFrameDivID);
      newNode.setAttribute("src", "javascript:false;");
      newNode.setAttribute("scrolling", "no");
      newNode.setAttribute ("frameborder", "0");
      document.body.appendChild(newNode);
    }
   
    if (!pickerDiv)
      pickerDiv = document.getElementById(datePickerDivID);
    if (!iFrameDiv)
      iFrameDiv = document.getElementById(iFrameDivID);
   
    try {
      iFrameDiv.style.position = "absolute";
      iFrameDiv.style.width = pickerDiv.offsetWidth;
      iFrameDiv.style.height = pickerDiv.offsetHeight ;
      iFrameDiv.style.top = pickerDiv.style.top;
      iFrameDiv.style.left = pickerDiv.style.left;
      iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
      iFrameDiv.style.visibility = pickerDiv.style.visibility ;
      iFrameDiv.style.display = pickerDiv.style.display;
    } catch(e) {
    }

  } catch (ee) {
  }

}

Step 2 :  Add a css file for your calendar style in your web content folder and just paste the style defined below .

FileName : datepicker.css

body {
    font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif;
    font-size: .8em;
    }

/* the div that holds the date picker calendar */
.dpDiv {
    }


/* the table (within the div) that holds the date picker calendar */
.dpTable {
    font-family: Tahoma, Arial, Helvetica, sans-serif;
    font-size: 12px;
    text-align: center;
    color: #505050;
    background-color: #ece9d8;
    border: 1px solid #AAAAAA;
    }


/* a table row that holds date numbers (either blank or 1-31) */
.dpTR {
    }


/* the top table row that holds the month, year, and forward/backward buttons */
.dpTitleTR {
    }


/* the second table row, that holds the names of days of the week (Mo, Tu, We, etc.) */
.dpDayTR {
    }


/* the bottom table row, that has the "This Month" and "Close" buttons */
.dpTodayButtonTR {
    }


/* a table cell that holds a date number (either blank or 1-31) */
.dpTD {
    border: 1px solid #ece9d8;
    }


/* a table cell that holds a highlighted day (usually either today's date or the current date field value) */
.dpDayHighlightTD {
    background-color: #CCCCCC;
    border: 1px solid #AAAAAA;
    }


/* the date number table cell that the mouse pointer is currently over (you can use contrasting colors to make it apparent which cell is being hovered over) */
.dpTDHover {
    background-color: #aca998;
    border: 1px solid #888888;
    cursor: pointer;
    color: red;
    }


/* the table cell that holds the name of the month and the year */
.dpTitleTD {
    }


/* a table cell that holds one of the forward/backward buttons */
.dpButtonTD {
    }


/* the table cell that holds the "This Month" or "Close" button at the bottom */
.dpTodayButtonTD {
    }


/* a table cell that holds the names of days of the week (Mo, Tu, We, etc.) */
.dpDayTD {
    background-color: #CCCCCC;
    border: 1px solid #AAAAAA;
    color: white;
    }


/* additional style information for the text that indicates the month and year */
.dpTitleText {
    font-size: 12px;
    color: gray;
    font-weight: bold;
    }


/* additional style information for the cell that holds a highlighted day (usually either today's date or the current date field value) */
.dpDayHighlight {
    color: 4060ff;
    font-weight: bold;
    }


/* the forward/backward buttons at the top */
.dpButton {
    font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif;
    font-size: 10px;
    color: gray;
    background: #d8e8ff;
    font-weight: bold;
    padding: 0px;
    }


/* the "This Month" and "Close" buttons at the bottom */
.dpTodayButton {
    font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif;
    font-size: 10px;
    color: gray;
    background: #d8e8ff;
    font-weight: bold;
    }

Step 3 :
            Just add the following code in your index.jsp page and run the program. However you can use the calendar in the same way on other page by following the same method  as in index.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>
<link rel="stylesheet" type="text/css" href="datepicker.css"/>
<script type="text/javascript" src="datepicker.js"></script>

</head>
<body>

  <b>Date:</b><input  type="text" name="date" id="cdate">
<input type=button value="Select Date" onclick="displayDatePicker('date', this);">
</body>
</html>
Hope this will help you....





Wednesday, January 26, 2011

Form Validation in JSP

What is Validation ?
Validation refers the process of validating/checking out of data that is about to handled by your program. In this process we validate the type of data , size of data and format of data. if it is found wrong or unacceptable we display an appropriate message to user so that he can re-enter his data in real way so that program can work successfully. The main goal of validation is to make the program prevent any bug that causes by user mistake.
How does we Validate data ?
In the early age of programming this task can be only done by the code developed by programmers itself  but now a days , advance technologies provide a sophisticated way to validate our data.
Example of Validation in JSP Program ?
Here I am giving a piece of code to validate the two integer against null. In this program if a user miss to enter any one of data the program guides him to enter the value.
Run the program by paste the code in index page. Hope this will give to a bit signal to understand validation.
Never miss to put your comment if like this topic.
index.jsp
<%
String elder = request.getParameter("age1");
String younger = request.getParameter("age2");
boolean first = false;
int totalage = 0;
String message = "";
if (elder == null) {
first = true;
message = "Your results will appear here";
} else {
try {
int fred = Integer.parseInt(elder);
int doris = Integer.parseInt(younger);
totalage = fred + doris;
} catch (Exception e) {
message = "You must enter two Integers";
first = true;
}
}
// -------------------------------------------------------
%>
<html>
<head><title>Example for first JSP Practical</title></head>
<body><h1>JSP is like a Jumbo Jet Driver</h1>
Because the smallest of operators can do a mighty lot<hr>
<% if (! first) { %>
Inputs were <%= elder %> and <%= younger %><br>
The total age of the kids is <%= totalage %>
<% } else { %>
<%= message %>
<% } %>
<hr>
<form>Please enter age 1 <input name=age1> and
age 2 <input name=age2> and <input type=submit></form>
Copyright ....
</body>
</html>

Friday, January 21, 2011

Managing a Login Session in JSP

As we know that the Http protocol is a stateless protocol, that means that it can't persist the data. Http treats each request as a new request so every time you will send a request you will be considered as a new user. It is not reliable when we are doing any type of transactions or any other related work where persistence of the information  is necessary.  To remove these obstacles we use session management. In session management whenever a request comes for any resource, a unique token is generated by the server and transmitted to the client by the response object and stored on the client machine as a cookie. We can also say that the process of managing the state of a web based client is through the use of session IDs. Session IDs are used to uniquely identify a client browser, while the server side processes are used to associate the session ID with a level of access. Thus, once a client has successfully authenticated to the web applicatiion, the session ID can be used as a stored authentication voucher so that the client does not have to retype their login information with each page request. Now whenever a request goes from this client again the ID or token will also be passed through the request object so that the server can understand from where the request is coming. Session  management can be achieved by using the following thing.
1. Cookies: cookies are small bits of textual information that a web server sends to a browser and that browsers returns the cookie when it visits the same site again. In cookie the information is stored in the form of a name, value pair. By default the cookie is generated. If the user doesn't want to use cookies then it can disable them.
2. URL rewriting: In URL rewriting we append some extra information on the end of each URL that identifies the session. This URL rewriting can be used where a cookie is disabled. It is a good practice to use URL rewriting. In this session ID information is embedded in the URL, which is recieved by the application through Http GET requests when the client clicks on the links embedded with a page.
3. Hidden form fields: In hidden form fields the html entry will be like this : <input type ="hidden" name = "name" value="">. This means that when you submit the form, the specified name and value will be get included in get or post method. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command.
In JSP we have been provided a implicit object session so we don't need to create a object of session explicitly as we do in Servlets. In Jsp the session is by default true. The session is defined inside the directive <%@ page session = "true/false" %>. If we don't declare it inside the jsp page then session will  be available to the page, as it is default by true.
For the convenience to understand the concept of session management we have made one program.
The code of the program is given below:
Step1:
        Open a New Web application in NetBeans or Ecllips that you prefer.
Step2:
         Paste the code below in index page of your application under web content folder

<%@ page import="java.util.*, java.lang.* , pack1.HelloBean" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<HTML>
    <HEAD>
        <TITLE>Login using jsp</TITLE>
    </HEAD>

    <BODY style="background-color:blue;" >
        <H1>LOGIN FORM</H1>
        <center>  
        <%
        String myname =  (String)session.getAttribute("username");
     
        if(myname!=null)
            {
             out.println("Welcome  "+myname+"  , <br/><br/><br/><br/><br/><a href=\"logout.jsp\" >Logout</a>");
            }
        else
            {
            %>

        <form action="checkLogin.jsp">
               
                <table>
                    <tr>
                        <td> Username  : </td><td> <input name="username" size=15 type="text" /> </td>
                    </tr>
                    <tr>
                        <td> Password  : </td><td> <input name="password" size=15 type="password" /> </td>
                    </tr>
                </table>
                <br/>
                <input type="submit" value="login" />
               
            </form>
            </center>
            <%
            }
       
           
            %>
       
    </BODY>
</HTML> 



Step3:
       Create a new jsp file with name checkLogin.jsp under the same web content folder and paste the code below. 

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
   <html><head><title>Login Example</title></head><body style="background-color:blue;">
      
           <center>
<%
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            if (username == null || password == null) {

                out.print("<br/><br/><br/><br/><br/>Invalid paramters");
                out.println("<br/><br/><br/><br/><br/><a href=\"index.jsp\">Return to Login</a>");
            }
            // Here you put the check on the username and password
            if (username.toLowerCase().trim().equals("sadique") && password.toLowerCase().trim().equals("arslan")) {
                out.println("<br/><br/><br/><br/><br/>Welcome " + username);
                %>
                <br/><br/><br/><br/><br/>
                <%
                out.println(" <a href=\"index.jsp\">Return to Home</a>");
                session.setAttribute("username", username);
            }
           else
               {
                out.println("<br/><br/><br/><br/><br/>Invalid username and password");
                out.println("<br/><br/><br/><br/><br/><a href=\"index.jsp\">Return to Login</a>");
           }




%></center>
</body></html>


Step4: 
        Create a logout.jsp page under the same web-content folder and paste the code below


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
   <html><head><title>Login Example</title></head><body style="background-color:blue;"><center>
<%

     String username=(String)session.getAttribute("username");
    if(username!=null)
        {
       
           out.println("<br/><br/><br/><br/><br/>Dear " + username+", You have been successfully loged out.");
            session.removeAttribute("username");
            out.println("<br/><br/><br/><br/><br/> <a href=\"index.jsp\">Return to Login</a>");
           
        }
     else
         {
         out.println("<br/><br/><br/><br/><br/>You are already not login <br/><br/><br/><br/><br/><a href=\"index.jsp\">Return to Login</a>");
     }



%> 

</center></body></html>



Step5:
        Finally run the program
Note: (Here username is sadique and password is arslan. However you can change it in your code.) 


I hope blog with help you to crack session management in JSP.

Monday, January 17, 2011

Calculator Program in JSP Using Multiple Submit Buttons

Here is a program to calculate your number that uses four submit buttons for four different purposes.

Just Paste it in index.jsp file and run the program.

<%@ page language="java"%>
<html>
    <head>
        <title>Using Multiple Forms</title>
    </head>
    <body>
        <h1>Using Multiple Forms</h1>
        <%
            if(request.getParameter("button") != null) {
        %>
        <% String s = request.getParameter("button");
           int no1,no2;
           if(request.getParameter("no1").equals("")) { no1 = 0; } else no1 = Integer.valueOf(request.getParameter("no1"));
           if(request.getParameter("no2").equals("")) { no2 = 0; } else no2 = Integer.valueOf(request.getParameter("no2"));
           if (s.equals("ADD")) {
               out.println("Result is " + (no1 + no2));
           }
           else if (s.equals("SUB")) {
               out.println("Result is " + (no1-no2));
           }
           else if(s.equals("MUL")) {
               out.println("Result is " + (no1*no2));
           }
           else if(s.equals("DIV")) {
               out.println("Result is " + (no1/no2));
           }
       
        %>
        <%
            }
        %>
       
       
        <form name="form1" method="get">
            <input name="no1">
            <input name="no2">
            <input type="hidden" name="button" value="ADD">
            <input type="submit" value="ADD">
        </form>
        <form name="form2" method="get">
            <input name="no1">
            <input name="no2">
            <input type="hidden" name="button" value="SUB">
            <input type="submit" value="SUB">
        </form>
        <form name="form3" method="get">
                    <input name="no1">
            <input name="no2">
            <input type="hidden" name="button" value="MUL">
            <input type="submit" value="MUL">
        </form>
        <form name="form4" method="get">
            <input name="no1">
            <input name="no2">
            <input type="hidden" name="button" value="DIV">
            <input type="submit" value="DIV">
        </form>
    </body>
</html>

Sunday, January 16, 2011

Simple Programs in JSP


JSP is dynamic programming language. It is capable of making simple program to complex. We can make simple program of add, even numbers, odd numbers. It is good start for beginner to learn with these programs.
 Step 1 :  Create a new Project in NetBeans or Ecllips Editor as
               Ex-    File  > New > Dynamic Web Project   (In Ecllips Hellios) 

Step 2 : Configure your Tomcat Server or the Server that you use with the project that you are creating 
             by  following create project dialog box.

Step 3:  Just paste the one of the program

First program of adding two numbers in JSP

<%@ page language="java"%>
<html>
<head>
<title>Add number program in JSP</title>
</head>

<body>
<%
 int a=5;
 int b=2;
 
 int result=a+b;
  
 out.print("Additon of a and b :"+result); 
%>
</body>
</html>

Second program of subtraction two numbers in JSP

<%@ page language="java"%>
<html>
<head>
<title>Subtraction numbers program in JSP</title>
</head>
<body>
<%
 int a=5;
 int b=2;
 int result=a-b;
 out.print("Subtraction of a and b :"+result); 
%>
</body>
</html>

Third program of print even numbers in JSP
 
<%@ page language="java"%>
<html>
<head>
<title>Even number program in JSP</title>
</head>

<body>
<%
 for(int i=0;i<=10;i++) 
 {
  if((i%2)==0)
  {
   out.print("Even number  :"+i); 
   out.print("<br>");
  }
 }
%>
</body>
</html>

Forth program of print odd numbers in JSP
 
<%@ page language="java"%>
<html>
<head>
<title>Odd number program in JSP</title>
</head>

<body>
<%
 for(int i=0;i<=10;i++) 
 {
  if((i%2)!=0)
  {
   out.print("Odd number  :"+i); 
   out.print("<br>");
  }
 }
%>
</body>
</html>

Saturday, January 15, 2011

JDBC connectivity in java

Java Database Connectivity or in short JDBC  is a technology that enables the java program to manipulate data stored into the database. Here is the complete tutorial on JDBC technology.

What is JDBC 


JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems.
Definition
Java Database Connectivity
in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the   database in tabular format from Java code using a set of  standard interfaces and classes written in the Java programming language.

JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the
same application. JDBC provides methods for querying and  updating the data in Relational Database Management system  such as SQL, Oracle etc. 

The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with  the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture.
Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC  makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems. 
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language. 
In short JDBC helps the programmers to write java applications that manage these three programming activities:

1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing  the results received from the database in terms of answering to your query.


Components of JDBC

 
JDBC has four Components:
1. The JDBC API.
2. The JDBC Driver Manager.
3. The JDBC Test Suite.
4. The JDBC-ODBC Bridge.

1. The JDBC API.

The JDBC application programming interface provides the facility for  accessing  the relational database from the Java programming language. The API technology provides the industrial standard for independently connecting Java programming language and a wide range of databases. The user not only execute the SQL statements, retrieve results, and update the data but can also access it  anywhere within a network because of  it's "Write Once, Run Anywhere" (WORA) capabilities. 

Due to JDBC API technology, user can also access other tabular data sources like spreadsheets or flat files even in the a heterogeneous environment.  JDBC application programmming interface is a  part of the Java platform that have included Java Standard Edition (Java SE ) and the Java  Enterprise Edition (Java EE) in itself.
The JDBC API has four main interface:
The latest version of  JDBC 4.0 application programming interface is divided into two packages
i-) java.sql
ii-) javax.sql. 

Java SE and Java EE platforms are included in both the packages.
2. The JDBC Driver Manager.

The JDBC Driver Manager is a very important class that defines objects which connect Java applications to a JDBC driver. Usually  Driver Manager is the backbone of the JDBC architecture. It's very simple and small that  is used to provide a means of managing the different types of JDBC database driver running on an application. The main responsibility of  JDBC database driver is to load all the drivers found in the system properly as well as to select the most  appropriate driver from opening a connection to a database.  The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected.  

3. The JDBC Test Suite.

The function of  JDBC driver test suite is to make ensure that the  JDBC drivers will run user's program or not . The test suite of  JDBC application program interface is very useful  for testing a driver based on JDBC technology during testing period. It  ensures the requirement of  Java Platform Enterprise Edition (J2EE).

4. The JDBC-ODBC Bridge.

The JDBC-ODBC bridge, also known as JDBC type 1 driver is a  database driver that utilize the ODBC driver to connect  the  database. This driver translates JDBC method calls into ODBC function calls. The Bridge implements Jdbc for any database for which an Odbc driver is available. The Bridge is always implemented as the sun.jdbc.odbc Java package and it contains a native library used to access ODBC.

Now we can conclude this topic: This first two component of   JDBC, the JDBC API and the JDBC Driver Manager manages to connect to the database and then build a java program that utilizes SQL commands to communicate with any RDBMS. On the other hand, the last two components are used  to communicate with ODBC or to test web application  in the specialized environment.


Understanding JDBC Architecture
JDBC is an API specification developed by Sun Microsystems that defines a uniform interface for accessing various relational databases. JDBC is a core part of the Java platform and is included in the standard JDK distribution.

The primary function of the JDBC API is to provide a means for the developer to issue SQL statements and process the results in a consistent, database-independent manner. JDBC provides rich, object-oriented access to databases by defining classes and interfaces that represent objects such as:

  1. Database connections
  2. SQL statements
  3. Result Set
  4. Database metadata
  5. Prepared statements
  6. Binary Large Objects (BLOBs)
  7. Character Large Objects (CLOBs)
  8. Callable statements
  9. Database drivers
  10. Driver manager
The JDBC API uses a Driver Manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The Driver Manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the servlet is shown in Figure 1.

Layers of the JDBC Architecture



A JDBC driver translates standard JDBC calls into a network or database protocol or into a database library API call that facilitates communication with the database. This translation layer provides JDBC applications with database independence. If the back-end database changes, only the JDBC driver need be replaced with few code modifications required. There are four distinct types of JDBC drivers.

Type 1 JDBC-ODBC Bridge. Type 1 drivers act as a "bridge" between JDBC and another database connectivity mechanism such as ODBC. The JDBC- ODBC bridge provides JDBC access using most standard ODBC drivers. This driver is included in the Java 2 SDK within the sun.jdbc.odbc package. In this driver the java statements are converted to a jdbc statements. JDBC statements calls the ODBC by using the JDBC-ODBC Bridge. And finally the query is executed by the database. This driver has serious limitation for many applications. (See Figure 2.)

Type 1 JDBC Architecture



Type 2 Java to Native API. Type 2 drivers use the Java Native Interface (JNI) to make calls to a local database library API.  This driver converts the JDBC calls into a database specific call for databases such as SQL, ORACLE etc. This driver communicates directly with the database server. It requires some native code to connect to the database. Type 2 drivers are usually faster than Type 1 drivers. Like Type 1 drivers, Type 2 drivers require native database client libraries to be installed and configured on the client machine. (See Figure 3.)

Type 2 JDBC Architecture



Type 3 Java to Network Protocol Or All- Java Driver. Type 3 drivers are pure Java drivers that use a proprietary network protocol to communicate with JDBC middleware on the server. The middleware then translates the network protocol to database-specific function calls. Type 3 drivers are the most flexible JDBC solution because they do not require native database libraries on the client and can connect to many different databases on the back end. Type 3 drivers can be deployed over the Internet without client installation. (See Figure 4.)
Java-------> JDBC statements------> SQL statements ------> databases.

Type 3 JDBC Architecture



Type 4 Java to Database Protocol. Type 4 drivers are pure Java drivers that implement a proprietary database protocol (like Oracle's SQL*Net) to communicate directly with the database. Like Type 3 drivers, they do not require native database libraries and can be deployed over the Internet without client installation. One drawback to Type 4 drivers is that they are database specific. Unlike Type 3 drivers, if your back-end database changes, you may save to purchase and deploy a new Type 4 driver (some Type 4 drivers are available free of charge from the database manufacturer). However, because Type drivers communicate directly with the database engine rather than through middleware or a native library, they are usually the fastest JDBC drivers available. This driver directly converts the java statements to SQL statements.

(See Figure 5.)

Type 4 JDBC Architecture



So, you may be asking yourself, "Which is the right type of driver for your application?" Well, that depends on the requirements of your particular project. If you do not have the opportunity or inclination to install and configure software on each client, you can rule out Type 1 and Type 2 drivers.

However, if the cost of Type 3 or Type 4 drivers is prohibitive, Type 1 and type 2 drivers may become more attractive because they are usually available free of charge. Price aside, the debate will often boil down to whether to use Type 3 or Type 4 driver for a particular application. In this case, you may need to weigh the benefits of flexibility and interoperability against performance. Type 3 drivers offer your application the ability to transparently access different types of databases, while Type 4 drivers usually exhibit better performance and, like Type 1 and Type 2 drivers, may be available free if charge from the database manufacturer.


JDBC Drivers and its type

JDBC Driver Manager

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple.

This is a very important class. Its main purpose is to provide a means of managing the different types of JDBC database driver. On running an application, it is the DriverManager's responsibility to load all the drivers found in the system property jdbc. drivers. For example, this is where the driver for the Oracle database may be defined. This is not to say that a new driver cannot be explicitly stated in a program at runtime which is not included in jdbc.drivers. When opening a connection to a database it is the DriverManager' s role to choose the most appropriate driver from the previously loaded drivers.

The JDBC API defines the Java interfaces and classes that programmers use to connect to databases and send queries. A JDBC driver implements these interfaces and classes for a particular DBMS vendor.

A Java program that uses the JDBC API loads the specified driver for a particular DBMS before it actually connects to a database. The JDBC DriverManager class then sends all JDBC API calls to the loaded driver.

JDBC Driver

This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC  driver types are better suited for some applications than others.

Types of JDBC drivers

This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for some applications than others.

    There are  four types of JDBC drivers known as:                       

  • JDBC-ODBC bridge plus ODBC driver, also called Type 1.
  • Native-API, partly Java driver, also called Type 2.
  • JDBC-Net, pure Java driver, also called Type 3.
  • Native-protocol, pure Java driver, also called Type 4.
Type 1 Driver- the JDBC-ODBC bridge

The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database.

The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition. The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. Also, using this driver has got other dependencies such as ODBC must be installed on the computer having the driver and the database which is being connected to must support an ODBC driver. Hence the use of this driver is discouraged if the alternative of a pure-Java driver is available.

Type 1 is the simplest of all but platform specific i.e only to Microsoft platform.

A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many  cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of  driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see JDBC-ODBC Bridge Driver.

Type 1 drivers are "bridge" drivers. They use another technology such as Open Database Connectivity (ODBC) to communicate  with a database. This is an advantage because ODBC drivers exist for many Relational Database Management System (RDBMS) platforms. The Java Native Interface (JNI) is used to call ODBC functions from the JDBC driver.

A Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it. This can be a serious drawback for a production application. Type 1 drivers cannot be used in an applet since applets cannot load native code.

Functions:

  1.  Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver. 
  2.  Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed
     source.
  3. Client -> JDBC Driver -> ODBC Driver -> Database
  4. There is some overhead associated with the translation work to go from JDBC to ODBC.
Advantages:

Almost any database for which ODBC driver is installed, can be accessed.

Disadvantages:

  1. Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver, then to the native database connectivity interface.
  2. The ODBC driver needs to be installed on the client machine.
  3. Considering the client-side software needed, this might not be suitable for applets.
Type 2 Driver - the Native-API Driver

The JDBC type 2 driver, also known as the Native-API driver is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API.

The type 2 driver is not written entirely in Java as it interfaces with non-Java code that makes the final database calls.
The driver is compiled for use with the particular operating system. For platform interoperability, the Type 4 driver, being
a full-Java implementation, is preferred over this driver.

A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

However the type 2 driver provides more functionality and performance than the type 1 driver as it does not have the overhead of the additional ODBC function calls.

Type 2 drivers use a native API to communicate with a database system. Java native methods are used to invoke the API functions that perform database operations. Type 2 drivers are generally faster than Type 1 drivers.

Type 2 drivers need native binary code installed and configured to work. A Type 2 driver also uses the JNI. You cannot use a Type 2 driver in an applet since applets cannot load native code. A Type 2 JDBC driver may require some Database Management System (DBMS) networking software to be installed.

The Developer Kit for Java JDBC driver is a Type 2 JDBC driver.

Functions:

  1. This type of driver converts JDBC calls into calls to the client API for that database.
  2. Client -> JDBC Driver -> Vendor Client DB Library -> Database
Advantage

Better performance than Type 1 since no jdbc to odbc translation is needed.

Disadvantages

  1. The vendor client library needs to be installed on the client machine.
  2. Cannot be used in internet due the client side software needed.
  3. Not all databases give the client side library.
Type 3 driver - the Network-Protocol Driver

The JDBC type 3 driver, also known as the network-protocol driver is a database driver implementation which makes use of a middle-tier between the calling program and the database. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol.

This differs from the type 4 driver in that the protocol conversion logic resides not at the client, but in the middle-tier. However, like type 4 drivers, the type 3 driver is written entirely in Java.
The same driver can be used for multiple databases. It depends on the number of databases the middleware has been configured to support. The type 3 driver is platform-independent as the platform-related differences are taken care by the middleware. Also, making use of the middleware provides additional advantages of security and firewall access.
A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to     their existing database middleware products.
These drivers use a networking protocol and middleware to communicate with a server. The server then translates the protocol to DBMS function calls specific to DBMS.
Type 3 JDBC drivers are the most flexible JDBC solution because they do not require any native binary code on the client. A Type 3 driver does not need any client installation.

Functions:

  1. Follows a three tier communication approach.
  2. Can interface to multiple databases - Not vendor specific.
  3. The JDBC Client driver written in java, communicates with a middleware-net-server using a database independent  protocol, and then this net server translates this request into database commands for that database.
  4. Thus the client driver to middleware communication is database independent.
  5. Client -> JDBC Driver -> Middleware-Net Server -> Any Database
Advantages
  1. Since the communication between client and the middleware server is database independent, there is no need for the vendor db library on the client machine. Also the client to middleware need'nt be changed for a new database.
  2. The Middleware Server (Can be a full fledged J2EE Application server) can provide typical middleware services like caching (connections, query results, and so on), load balancing, logging, auditing etc..
  3. eg. for the above include jdbc driver features in Weblogic.
  4. Can be used in internet since there is no client side software needed.
  5. At client side a single driver can handle any database.(It works provided the middlware supports that database!!)
Disadvantages
  1. Requires database-specific coding to be done in the middle tier.
  2.  An extra layer added may result in a time-bottleneck. But typically this is overcome by providing efficient middleware
        services described above.
Type 4 - the Native-Protocol Driver

The JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol.

The type 4 driver is written completely in Java and is hence platform independent. It is installed inside the Java Virtual Machine of the client. It provides better performance over the type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC or database API calls. Unlike the type 1 and 2 drivers, it does not need associated software to work.

A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

As the database protocol is vendor-specific, separate drivers, usually vendor-supplied, need to be used to connect to the database.

A Type 4 driver uses Java to implement a DBMS vendor networking protocol. Since the protocols are usually proprietary, DBMS vendors are generally the only companies providing a Type 4 JDBC driver.

Type 4 drivers are all Java drivers. This means that there is no client installation or configuration. However, a Type 4 driver may not be suitable for some applications if the underlying protocol does not handle issues such as security and network connectivity well.

The IBM Toolbox for Java JDBC driver is a Type 4 JDBC driver, indicating that the API is a pure Java networking protocol driver.

Functions

  1. Type 4 drivers are entirely written in Java that communicate directly with a vendor's database through socket connections. No translation or middleware layers, are required, improving performance.
  2. The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server.
  3. Completely implemented in Java to achieve platform independence.
  4. e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which connect to jdbc:oracle:thin URL format.
  5. Client Machine -> Native protocol JDBC Driver -> Database server
Advantages

These drivers don't translate the requests into db request to ODBC or pass it to client api for the db, nor do they need a middleware layer for request indirection. Thus the performance is considerably improved.

Disadvantage

At client side, a separate driver is needed for each database.