Advance Java Vision Academy Notes
Advance Java Vision Academy Notes
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Collection Interface
List Interface
• The elements in a list are ordered. Each element, therefore, has a position in the
list.
• It can contain duplicates.
• A zero-based index can be used to access the element at the position designated
by the index value. The position of an element can change as elements are
inserted or deleted from the list.
Constructor
LinkedList( )
LinkedList Class
Constructor
LinkedList()
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList ll = new LinkedList();
ll.add("F");
ll.add("B");
ll.add("D");
System.out.println(ll);
}
}
4 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
ArrayList Class
import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("F");
al.add("B");
al.add("D");
System.out.println(al);
}
}
ArrayList LinkedList
1) ArrayList internally uses dynamic array to
LinkedList internally uses doubly linked
tore the elements.
list to store the elements.
2) Manipulation with ArrayList is slow Manipulation with LinkedList is faster
because it internally uses array. If any element than ArrayList because it uses doubly
is removed from the array, all the bits are linked list so no bit shifting is required in
shifted in memory. memory.
Vector class
• The class can be used to create a generic dynamic array known as vector that can
hold objects of any type and any number.(Object don’t have to be homogenous)
Constructor
Vector( )
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
v.add("F");
v.add("B");
v.add("D");
System.out.println(v);
}
}
Iterator
Iterator is an interface available in Collection framework in java.util package. It is a Java
Cursor used to iterate a collection of objects.
boolean hasNext( )
1
Returns true if there is next elements. Otherwise, returns false.
Object next( )
2
Returns the next element.
Void remove( )
3
Removes the current element.
import java.util.*;
class IteratorDemo
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
ListIterator
boolean hasNext( )
2
Returns true if there is a next element. Otherwise, returns false.
boolean hasPrevious( )
3
Returns true if there is a previous element. Otherwise, returns false.
Object next( )
4 Returns the next element. A NoSuchElementException is thrown if there is not a
next element.
int nextIndex( )
5 Returns the index of the next element. If there is not a next element, returns the size
of the list.
Object previous( )
6 Returns the previous element. A NoSuchElementException is thrown if there is not a
previous element.
int previousIndex( )
7 Returns the index of the previous element. If there is not a previous element, returns
-1.
Void remove( )
8
Removes the current element from the list.
import java.util.*;
class ListIteratorDemo
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
• add(obj) • hasNext()
• hasNext() • next()
• hasPrevious() • remove()
• next()
• nextIndex()
• previous()
• previousIndex()
• remove()
• set(obj)
10 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one
at a time) the elements in a collection of objects.
import java.util.*;
class Enumeration
{
public static void main(String args[])
{
Enumeration d;
Vector v = new Vector();
v.add("C");
v.add("A");
v.add("E");
d=v.elements();
while (d.hasMoreElements())
{
System.out.println(d.nextElement());
}
}
}
Set Interface
SortedSet Interface
The SortedSet interface extends Set and declares the behavior of a set sorted in
ascending order.
TreeSet Class
Constructor
TreeSet( )
TreeSet(Comparator comp)
import java.util.*;
class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set
TreeSet ts = new TreeSet();
// Add elements to the tree set
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
[A, B, C, D, E, F]
obj1 and obj2 are the objects to be compared. This method returns zero if the
objects are equal. It returns a positive value if obj1 is greater than obj2.
Otherwise, a negative value is returned.
• It provides multiple sorting sequence i.e. you can sort the elements on the basis of
any data member, for example rollno, name, age or anything else.
12 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
import java.util.*;
class Tree implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
return s2.compareTo(s1);
}
HashSet Class
Constructor
HashSet( )
import java.util.*;
class HashSetDemo {
public static void main(String args[])
13 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
{
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
o/p
[A, F, E, D, C, B]
LinkedHashSet Class
Constructor
LinkedHashSet( )
import java.util.*;
class Lh
{
public static void main(String args[])
{
// create a hash set
LinkedHashSet hs = new LinkedHashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
o/p
14 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
[B,A,D,E,C,F]
Map Interface
• A Map interface defines mappings from keys to values. The <key, value> pair is
called an entry in a Map.
• A Map does not allow duplicate keys, in other words, the keys are unique.
Methods
• void putAll(Map t)
• int size()
• boolean isEmpty()
• void clear()
TreeMap Class
Constructor
TreeMap()
import java.util.*;
class TreeMapDemo
{
public static void main(String args[])
{
TreeMap tm = new TreeMap();
System.out.println(tm);
}
16 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
HashMap Class
• The HashMap class uses a hash table to implement the Map interface.
Constructor
HashMap( )
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap tm = new HashMap();
System.out.println(tm);
LinkedHashMap Class
Constructor
LinkedHashMap( )
import java.util.*;
class Hd
{
public static void main(String args[])
{
17 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
System.out.println(tm);
Hashtable
• Hashtable contains values based on the key. It implements the Map interface.
• It contains only unique key.
• It is synchronized.
Constructor
Hashtable()
import java.util.*;
class HashDemo
{
public static void main(String args[])
{
Hashtable tm = new Hashtable();
tm.put("Amol", new Float(55.55));
tm.put("Punit", new Float(66.33));
System.out.println(tm);
}
18 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
MultiThreading
MuliProcessing
• This allows many processes to run simultaneously.
• Process is a running instance of the program. i.e. an operating system
process.
CPU time is shared between different processes.
• OS provides context switching mechanism, which enables to switch
between the processes.
• Program’s entire contents (e.g. variables, global variables, functions) are
stored separately in their own context.
Example:- MS-Word and MS-Excel applications running simultaneously. (or
any two applications for that matter)
MultiThreading
• It allows many tasks within a program (process) to run simultaneously.
• Each such task is called as a Thread.
• Each Thread runs in a separate context.
• Each Thread has a beginning , a body,& an end
• Example:- Lets take a typical application like MS-Word. There are various
independent tasks going on, like displaying GUI, auto-saving the file, typing in
text, spell-checking, printing the file contents etc…
Thread
• Thread is an independent sequential path of execution within a program. i.e.
separate call stack.
19 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Main
Thread
Switching switching
}
Where A is name of thread.
2.Implement the run() method.i.e Responsible for executing of code the thread will
execute.
public void run()
{
-------
20 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
-----
}
3.Create a thread object & call the start() method to initiate the thread execution.
}
System.out.println("\n Exit from A");
}
System.out.println("\n Exit from B");
class ThreadTest
{
public static void main(String args[])
{
A t1=new A();
//new A().start();
t1.start();//invoke run method
21 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
B t2=new B();
}
2.Implementing java.lang.Runnable interface
Steps as follows
1.Declare the class as implementing the runnable interface.
2.Implement the run() method.
3.It create a thread which is pass a parameter as a thread class object which
implemetns “runnable” interface
4.Call the thread’s start() method to run the thread.
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
New
Thread newborn
stop
start
Active stop
Thread Running
Runnable Dead
yield
Suspend
Sleep Resume
wait Notify
stop
Idle
Thread Blocked
1 Newborn state
It create a thread object, the thread is born & is said to be newborn state.
2. Runnable state
It means thread is ready for execution & is waiting for the availability of processor.
The processor of assigning time to threads is known as timing-slicing.
yield
……
Runnable thread
23 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
If a thread to leave control to another thread of equal priority before its turn
comes,it can done by using yield() method
3.Running state
It means that the processor has given its time to the thread for its execution.
The thread runs until it leaves control on its own or it is preempted by higher priority
thread.A running thread my leaves its control in one of the following
1.suspend():
It has been suspended using suspend() method. A suspended thread can be received by
using resume() method.
Resume()
2.sleep()
It can put thread to sleep for a specified time period using sleep(t) method.(t is time
milliseconds).
Sleep(t)
After t
3.wait()
It has been hold to wait until some event occurs. This is done using wait() method. The
thread can be scheduled to run again using notify() method.
Wait Notify()
4.Blocked state
24 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
A thread is said to be blocked when it is prevented from entering into runnable state &
subsequently the running state. This happens when the thread is suspended,sleeping or
waiting.
A blocked thread is considered “not runnable” but not dead .
5.Dead state
Every Thread has a life cycle. A running threads ends its life when it has completed
executing its run() method.
class CurrentThreadDemo
{
try
{
}
}
Threads priority
Each thread is assigned a priority, which affects the order it is scheduled for running.
i.e Threads are assigned priorities that the thread scheduler can use to determine how the
threads will be scheduled.
The following static final integer constants are defined in the Thread class:
setPriority():It can modify a thread’s priority at any time after its creation using the
setPriority() method.
Threadname.setPriority(int number)
Where number is priority number.
t3.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(Thread.MIN_PRIORITY);
t3.start();
t1.start();
t2.start();
}
}
Threads Method
1. isAlive() method:
Returns true if the thread is alive, otherwise false.
public final boolean isAlive()
2.join() method:
The join() method waits for a thread to die.(A thread to wait until the completion
of another thread before continue.
public void join()
class ThreadTest
{
public static void main(String args[])
{
try
{
A t1=new A();
t1.start();//invoke run method
B t2=new B();
t2.start();//invoke run method
t1.join();
t2.join();
System.out.println("Main parent thread");
System.out.println("A thread "+t1.isAlive());
System.out.println("B thread "+t2.isAlive());
}
catch(Exception e)
{
System.out.println("error"+e);
}
}
}
28 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
synchronized method1 ()
{
// statements to be synchronized
}
When it declare a method synchronized, Java creates a “Monitor” & hands it over
to the thread that calls the method first time. As long as the thread holds the monitor, no
other thread can enter the synchronized section of code.
When thread has completed its work of using synchronized method(or block of
code),it will hand over the monitor to the next thread that is ready to use same resource.
Using synchronized
class Callme
{
t = new Thread(this);
t.start();
}
public void run()
{
target.call(msg);
}
}
public class Synch
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
}
}
Java - Interthread Communication
When multiple threads are running in an application, it become necessary for the threads
to communicate(talk) with each other such communication called as interthread
communication.
The thread can communicate by either sharing data or indicating when a specific activity
has completed.
Methods for interthread communication
wait( ): Causes the current thread to wait until another thread invokes the notify().
notifyAll( ): Wakes up all the threads that called wait( ) on the same object.
Join():The join() method waits for a thread to die.(A thread to wait until the completion
of another thread before continue.
String getName()
30 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
int getPriority()
This method Returns this thread's priority.
boolean isAlive()
This method tests if this thread is alive.
void join()
Waits for this thread to die.
void run()
If this thread was constructed using a separate
Runnable run object, then that Runnable object's
run method is called; otherwise, this method does
nothing and returns
void start()
This method causes this thread to begin execution;
the Java Virtual Machine calls the run method of
this thread.
DATABASE PROGRAMING
What is JDBC?
JDBC Architecture
JDBC drivers are divided into four types or levels. The different types of jdbc drivers
are:
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the
ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended
only for experimental use or when no other alternative is available.
32 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not
portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC
driver, then to the database, and this applies even in the reverse process. They are
the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC
calls into database-specific calls i.e. this driver is specific to a particular database. Some
33 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will
have oracle native api.
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better
performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less
than that of Type 1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot
be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability
issue.
3. If we change the Database we have to change the native api as it is specific to a
database.
Type 3 database requests are passed through the network to the middle-tier server. The
middle-tier then translates the request to the database. If the middle-tier server can in turn
use Type1, Type 2 or Type 4 drivers.
Advantage
1. This driver is server-based, so there is no need for any vendor database library to
be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and
scalability.
4. The net protocol can be designed to make the client JDBC driver very small
and fast to load.
5. The type 3 driver typically provides support for features such as caching
(connections, query results, and so on), load balancing, and advanced
Disadvantage
It requires another server application to install and maintain. Traversing the recordset
may take longer, since the data comes through the backend server.
35 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database
server.
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely
written in Java to achieve platform independence and eliminate deployment
administration issues. It is most suitable for the web.
2. . Number of translation layers is very less i.e. type 4 JDBC drivers don't have to
translate database requests to ODBC or a native connectivity interface or to pass
the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these
drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
JDBC Versions
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database
access.
1. Two-tier
In such an architecture, the Java application communicates directly with the data source
(or database). The database may reside on the same machine or may be on another
machine to which the clinet machine needs to be connected through a network
2. Three-tier
In such an architecture, the client machine will send the database access statements to the
middleware, which will then send the statements to the database residing on the third tier
37 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
of the architecture, which is normally referred to as the back end. The statements will be
processed there and the result be returned back to the client through the middle tier. This
approach will have all the advantages associated with the 3-tier architecture, such as
better maintainability, easier deployment, scalability, etc.
The java.sql package contains several classes and interface which are used to
communicate with the
database
38 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Loading Database driver is very first step towards making JDBC connectivity with the
database. It is necessary to load the JDBC drivers before attempting to connect to the
database.
39 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Syntax
Class.forName(drivername).
e.g Class.forName("org.postgresql.Driver");
2.Establishing Connection
After loading driver, now Establishing Connection with the database with user name and
password.
Syntax
con=DriverManager.getConnection("jdbc:postgresql://localhost:5432
/ty");
There are three basic types of SQL statements used in the JDBC API:
Eg
Eg 1
Eg2
ps.setFloat(3,66.55f);
ResultSet rs = ps.executeUpdate();
Eg
4.Execute a query
An SQL statement can either be a query that return result or operation that manipulates
the database
5.Process a query:
ResultSet provides access to a table of data generated by executing a Statement. The table
rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row
of data. The next() method is used to successively step through the rows of the tabular
results.
To access these values, there are getXXX() methods where XXX is a type for example,
Example
rs.getString(“sname”));
rs.getString(1);
41 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
After all work is done, it is important to close the connection. But before the connection
is closed , close the ResultSet and the statement objects.
e.g
rs.close();
stmt.close();
con.close();
The scroll type indicates how the cursor moves in the ResultSet. The concurrency type
affects concurrent access to the resultset. The types are given in the table below.
Scroll Type
TYPE_FORWARD_ONLY :
TYPE_SCROLL_INSENSITIVE:
TYPE_SCROLL_SENSITIVE:
Concurrency Type
import java.sql.*;
c=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat
");
Statement stmt = c.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println("Rollno"+rs.getInt(1));
System.out.println("Name"+rs.getString(2));
System.out.println("Per"+rs.getFloat(3));
}
}
catch (Exception e)
{
System.out.println(e);
}
}
import java.sql.*;
import java.io.*;
public class Post
{
public static void main(String args[])
{
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c=
DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat");
Statement stmt = c.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Roll no: ");
int rno=Integer.parseInt(br.readLine());
System.out.println("Enter Name: ");
String name=br.readLine();
44 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
}
}
import java.sql.*;
import java.io.*;
public class Post
{
public static void main(String args[])
{
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c=
DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat");
Statement stmt = c.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Roll no: ");
int rno=Integer.parseInt(br.readLine());
45 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
if(k>0)
System.out.println("Insert "+k);
else
System.out.println("Insert "+k);
catch (Exception e)
{
System.out.println(e);
}
}
import java.sql.*;
import java.io.*;
public class Post
{
public static void main(String args[])
{
Connection c = null;
try {
46 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Class.forName("org.postgresql.Driver");
c=
DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat");
Statement stmt = c.createStatement();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Roll no: ");
int rno=Integer.parseInt(br.readLine());
String sql="delete from student where rollno="+rno;
int k=stmt.executeUpdate(sql);
if(k>0)
System.out.println("Delete "+k);
else
System.out.println("Delete "+k);
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println("rollno"+rs.getInt(1));
System.out.println("name"+rs.getString(2));
System.out.println("Percentage"+rs.getFloat(3));
}
rs.close();
stmt.close();
c.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Navigate the Database
import java.sql.*;
class stud3
{
public static void main( String args[])
{
try
{
Connection c=null;
Class.forName("org.postgresql.Driver");
47 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
C=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","
redhat");
//Statement stmt=c.createStatement();
Statement stmt = c.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from student";
ResultSet rs= stmt.executeQuery(sql);
System.out.println("Display record next");
while( rs.next())
{
System.out.println( rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getDouble(3));
}
System.out.println("Display record previous");
while( rs.previous())
{
System.out.println( rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getDouble(3));
}
System.out.println("Display first record ");
rs.first();
System.out.println( rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getDouble(3));
Metadata means information about data. Some application need to discover information
about the tables, result set structure or underlying database dynamically. JDBC can
provide additional information about the structure of a database and its tables.
DatabaseMetadata Interface
MetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables,
name of total number of views etc.
Methods:
Example1:
DatabaseMetaData dbmd=con.getMetaData();
System.out.println("Driver Name: "+dbmd.getDriverName());
System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
49 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Example 2:
To print no. of tables
DatabaseMetaData dbmd=con.getMetaData();
String table[]={"TABLE"};
ResultSet rs=dbmd.getTables(null,null,null,table);
while(rs.next()){
System.out.println(rs.getString(3));
ResultSetMetaData
ResultSetMetaData interface
Method Description
public int getColumnCount()throws it returns the total number of
SQLException columns in the ResultSet object.
public String getColumnName(int it returns the column name of the
index)throws SQLException specified column index.
public String getColumnTypeName(int it returns the column type name
index)throws SQLException for the specified index.
public String getTableName(int index)throws it returns the table name for the
SQLException specified column index.
Example:
PreparedStatement ps=con.prepareStatement("select * from stud");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)
);
50 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Transaction
Method Description
void setAutoCommit(boolean It is true bydefault means each transaction is
status) committed bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
Savepoints
The save point is a logical position in a transaction up to which we can rollback the
transaction. When the save point is placed in the middle of the transaction, the logics
placed before the save point will be committed and the logics placed after the save point
will be rolled back.
NETWORKING
Networking Basics
Protocol
A protocol is a set of rules and standards for communication.
1. IP (Internet Protocol): is a network layer protocol that breaks data into small packets
and routes them using IP addresses.
Addressing
1. MAC Address: Each machine is uniquely identified by a physical address, address of
the network interface card. It is 48-bit address represented as 12 hexadecimal characters:
For Example: 00:09:5B:EC:EE:F2
2.IP Address: It is used to uniquely identify a network and a machine in the network.
Itis referred as global addressing scheme. Also called as logical address. Currently used
type of IP addresses is: Ipv4 – 32-bit address and Ipv6 – 128-bit address.
For Example:
Ipv4 – 192.168.16.1
Ipv6 – 0001:0BA0:01E0:D001:0000:0000:D0F0:0010
3.Port Address: It is the address used in the network to identify the application on the
network.
URL
A URL (Uniform Resource Locator) is a unique identifier for any resource located on the
Internet. The syntax for URL is given as:
<protocol>://<hostname>[:<port>][/<pathname>][/<filename>[#<section>]]
52 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Sockets
Def:A socket represents the end-point of the network communication.
It provides a simple read/write interface and hides the implementation details network
and transport layer protocols. It is used to indicate one of the two end-points of a
communication link between two processes. When client wishes to make connection to a
server, it will create a socket at its end of the communication link.
The socket concept was developed in the first networked version of UNIX developed at
the University of California at Berkeley. So sockets are also known as Berkeley Sockets.
Ports
A port number identifies a specific application running in the machine.
A port number is a number in the range 1-65535.
Reserved Ports: TCP/IP protocol reserves port number
in the range 1-1023 for the use of
specified standard services, often referred to as “well-known” services.
e.g
FTP :21
HTTP:80
SNMP:161
SMTP:25
InetAddress Class
Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example www.google.com,
www.facebook.com etc.
Method Description
public static InetAddress getByName(String it returns the instance of InetAddress
host) throws UnknownHostException containing LocalHost IP and name.
public static InetAddress getLocalHost() throws it returns the instance of InetAdddress
UnknownHostException containing local host name and address.
public String getHostName() it returns the host name of the IP
address.
public String getHostAddress() it returns the IP address in string format.
URL Class
The Java URL class represents an URL. URL is an acronym for Uniform Resource
Locator. It points to a resource on the World Wide Web.
The class has the following constructors:
53 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
1. URL(String url_str): Creates a URL object based on the string parameter. If the
URL cannot be correctly parsed, a MalformedURLException will be thrown.
2. URL(String protocol, String host, String path): Creates a URL object with the
specified protocol, host and path.
3. URL(String protocol, String host, int port, String path): Creates a URL object
with the specified protocol, host, port and file path.
Methods
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public URLConnection it returns the instance of URLConnection i.e.
openConnection() associated with this URL.
URLConnection Class
The Java URLConnection class represents a communication link between the URL and
the application. This class can be used to read and write data to the specified resource
referred by the URL.
{
System.out.println(e);
}
}
}
1.A Datagram socket uses user datagram protocol (UDP) to send datagrams (self
contained units of information) in a connectionless manner.
3.The advantage is the datagram sockets require relatively few resources and so
communication is faster.
1.A stream socket is a “connected” socket through which data is transferred continuously.
2. It use TCP to create a connection between the client and server. TCP/IP sockets are
used to implement reliable, bidirectional, persistent, point to point, stream-based
connection between hosts on the internet.
3. The benefit of using a stream socket is the communication is reliable. because once
connected ,the communication link is available till it is disconnected. So data
transmission is done in real-time and data arrives reliably in the same order that it was
sent. however this requires more resource. Application like file transfer require a reliable
communication. For such application stream sockets are better.
4. Java uses java.net.Socket class to create stream socket for client and
java.net.ServerSocket for server.
55 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
3. DatagramSocket are unreliable. They may be dropped ,duplicate and delivered out of
order.
Stream socket is reliable ,if datas are lost on the way, TCP automatically re-sends.
5.Application which use datagram sockets are request-reply type of application such as
DNS lookups,PING and SMTP.
Stream sockets are used for application like file transfer which require reliability.
ServerSocket Class
This class is used to create a server that listens for incoming connections from clients. It
is possible for client to connect with the server when server socket binds itself to a
specific port. The various constructors of the ServerSocket class are:
1. ServerSocket(int port): binds the server socket to the specified port number. If 0 is
passed, any free port will be used. However, clients will be unable to access the
service unless notified the port number.
Method Description
Socket Class
This class is used to represents a TCP client socket, which connects to a server socket and
initiate protocol exchanges. The various constructors of this class are:
2. Socket(String host, int port): creates a socket connected to the specified host and
port. Can throw an UnknownHostException or an IOException.
57 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
import java.net.*;
import java.io.*;
public class Server
{
public static void main(String[] ar)
{
try
{
int port = 6666;
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting for a client...");
Socket socket = ss.accept();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
1.Create an object of the socket class using the server names and port as parameter.
//Client
import java.net.*;
import java.io.*;
public class Client
{
public static void main(String[] ar)
{
try
{
int serverPort = 6666;
String address = "127.0.0.1";
while(true)
{
line = keyboard.readLine();
System.out.println("Sending this line to the server...");
out.writeUTF(line); // send the above line to the server.
out.flush();
System.out.println();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
60 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Servlet
What Web server?
➢ Apache is a very popular server
➢ 66% of the web sites on the Internet use Apache
Apache is:
• Full-featured and extensible
• Efficient
• Robust
• Secure (at least, more secure than other servers)
• Up to date with current standards
• Open source
• Free
What is Tomcat?
Tomcat is the Servlet Engine that handles servlet requests for Apache.
➢ Tomcat is a “helper application” for Apache
➢ It’s best to think of Tomcat as a “servlet container”
What is servlet?
A servlet is a web component,managed by a container, that generates dynamic
content.
The classloader is responsible to load the servlet class. The servlet class is loaded when
the first request for the servlet is received by the web container.
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
Servlet Package
It includeTwo packages:
▪ javax.servlet
▪ javax.servlet.http
The javax.servlet package contains a number of interfaces and classes that establish
the framework in which servlets operate.
Interface Description
Servlet Declares life cycle methods for a servlet.
Class Description
2.javax.servlet.http Package
Interface Description
63 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Class Description
Cookie Allows state information to be stored on a client
machine.
import java.io.*;
65 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servlet/PostServlet">
Enter name
<input type=text name=”t”>
<br>
<input type=submit value="Submit">
</body>
</html>
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
String s = request.getParameter("t");
pw.println(s);
pw.close();
}
}
2
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examples/servlets/servlet/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
HTML-SERVLET COMMUNICATION
What is a Cookie?
A "cookie" is a small piece of information sent by a web server to store on a web browser
so it can later be read back from that browser. A cookie’s value identify user
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servlets/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=”text” name="t1" >
68 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
SOFTWARE DEVELOPMENT
USING JAVA
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
There are several ways through which it can provide unique identifier in request and
response.
1. User Authentication – This is the very common way where we user can provide
authentication from the login page and then we can pass the authentication
information between server and client to maintain the session. This is not very
effective method because it wont work if the same user is logged in from different
browsers.
2. HTML Hidden Field – We can create a unique hidden field in the HTML and
when user starts navigating, we can set its value unique to the user and keep track
of the session. This method can’t be used with links because it needs the form to
be submitted every time request is made from client to server with the hidden
field. Also it’s not secure because we can get the hidden field value from the
HTML source and use it to hack the session.
3. URL Rewriting – We can append a session identifier parameter with every
request and response to keep track of the session. This is very tedious because we
need to keep track of this parameter in every response and make sure it’s not
clashing with other parameters.
4. Cookies: A "cookie" is a small piece of information sent by a web server to store
on a web browser so it can later be read back from that browser. It can maintain a
session with cookies but if the client disables the cookies, then it won’t work.
5. Session Management API:The servlet API provide methods and classes
specifically designed to handle session.The HttpSession class provide various
session tracking methods
out = res.getWriter();
Class.forName("org.postgresql.Driver");
c=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat
");
// Create a Statement object
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next())
{
out.println("rollno is" +rs.getString(1) );
out.println("name is" +rs.getString(2) );
out.println("per is" +rs.getString(3));
}
rs.close();
stmt.close();
c.close();
}
catch(Exception e)
{
out.println("error"+e);
}
}
}
72 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
1.jspInt()
• This method is identical to the init() method in Java servlet.
73 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
• This method is called first when the JSP is requested and is used to initialize objects
& variables that are used throughout the life of the JSP.
2.jspDestroy()
• This method is identical to the destroy() method in Java servlet.
• This method is automatically called when JSP terminates normally.
• This method is used for cleanup where resources used during execution of JSP are
released.
3._jspService()
• This method is identical to the service() method in Java servlet.
• This method is automatically processing request& sending response.
JSP Architecture
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
• As with a normal page, your browser sends an HTTP request to the web server.
• The web server recognizes that the HTTP request is for a JSP page and forwards
it to a JSP engine. This is done by using the URL or JSP page which ends with
.jsp instead of .html.
• The JSP engine loads the JSP page from disk and converts it into a servlet
content.
75 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
• The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
• A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format,
which the servlet engine passes to the web server inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static
HTML content.
JSP Tags
1.Comment Tags:
It is denoted by
<%--
--%>
e.g
<%-- This comment will not be visible in the page source --%>
2.Declaration statement tags: This tag is used for defining the functions and variables to
be used in the JSP.
It is denoted by
<%!
%>
Eg
<%! int age=25;%>
It is denoted by
<%
Eg. %>
<% for(int i=0;i<=3;i++)
{
---
---
}
%>
76 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
4.Expression tags: The expression is evaluated and the result is inserted into the HTML
page
It is denoted by
<%= expression %>
Eg.
<%=age%>
5.Directive tags:
The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.
o page directive
o include directive
o taglib directive
1.page directive
The page directive defines attributes that apply to an entire JSP page.
It is denoted by
<%@ directive attribute="" %>
Attribute as follows
2.Extends: This attribute is used to extend (inherit) the class like JAVA does
Syntax of extends:
Syntax of import:
4.contentType:
• It defines the character encoding scheme i.e. it is used to set the content type and
the character set of the response
• The default type of contentType is "text/html; charset=ISO-8859-1".
5.Session
Specifies whether or not the JSP page participates in HTTP sessionsSyntax of session
Syntax
6.errorPage:
This attribute is used to set the error page for the JSP page if JSP throws an exception and
then it redirects to the exception page.
Syntax of errorPage:
78 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
7. PageEncoding:
The "pageEncoding" attribute defines the character encoding for JSP page.The default is
specified as "ISO-8859-1" if any other is not specified.
Syntax
Example:
2.include directive:
e.g
a.jsp
<%="HELLO bcs"%>
p.jsp
<%@ include file="p.jsp" %>
<%="HELLO mcs"%>
3.taglib directive:
JSP taglib directive is used to define the tag library with "taglib" as the prefix, which we
can use in JSP. (custom tags allows us to defined our own tags).
79 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is
a tag name.
e.g
int sum=0;
for(int i=1;i<=n;i++)
sum=sum+i;
return(sum);
}
%>
80 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
JSP CODE
</p>
<body>
</html>
Implicit object:These objects are created automatically by JSP container. It can directly
use these object. JSP Implicit Objects are also called pre-defined variables
No. Object & Description
request
1 This is the HttpServletRequest object associated
with the request.
response
2 This is the HttpServletResponse object associated
with the response to the client.
out
3 This is the PrintWriter object used to send output to
the client.
session
4 This is the HttpSession object associated with the
request.
application
5 This is the ServletContext object associated with the
application context.
config
6 This is the ServletConfig object associated with the
page.
81 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
pageContext
7 This encapsulates use of server-specific features like
higher performance JspWriters.
page
8 This is simply a synonym for this, and is used to call
the methods defined by the translated servlet class.
Exception
9 The Exception object allows the exception data to be
accessed by designated JSP.
Login.jsp
<%
String s1=request.getParameter("t1");
String s2=request.getParameter("t2");
if(s1.equals("sachin")&&s2.equals("sachin"))
out.println("Login Sucessfully");
else
out.println("Login incorrect");
82 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
%>
}
rs.close();
sta.close();
con.close();
}
catch(Exception e)
{
}
%>
</body>
</html>
JSP Benefits
• Easy to combine static templates,including HTML or XML.
• JSP pages compile dynamically into servlets.
• JSP makes it easier to author pages "by hand"
• JSP tags for invoking JavaBeansTM components
Compare servlet &jsp
83 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
JSP Servlets
Servlets are Java programs that are
JSP is a webpage scripting language that can
already compiled which also creates
generate dynamic content.
dynamic web content.
JSP run slower compared to Servlet as it takes
Servlets run faster compared to JSP.
compilation time to convert into Java Servlets.
It’s easier to code in JSP than in Java Servlets. Its little much code to write here.
In MVC, jsp act as a view. In MVC, servlet act as a controller.
servlets are best for use when there is
JSP are generally preferred when there is not
more processing and manipulation
much processing of data required.
involved.
The advantage of JSP programming over
There is no such custom tag facility in
servlets is that we can build custom tags which
servlets.
can directly call Java beans.
We can achieve functionality of JSP at client
There are no such methods for servlets.
side by running JavaScript at client side.