Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Advance java Notes

The document provides an overview of the Java Collection Framework, detailing its components including interfaces, classes, and algorithms, as well as the differences between Core Java and Advanced Java. It explains various collection types such as Lists, Sets, and Maps, along with their implementations like ArrayList, LinkedList, HashSet, and HashMap. Additionally, it covers multithreading concepts in Java, including thread states, creation methods, and thread lifecycle management.

Uploaded by

pranita.tathe15
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Advance java Notes

The document provides an overview of the Java Collection Framework, detailing its components including interfaces, classes, and algorithms, as well as the differences between Core Java and Advanced Java. It explains various collection types such as Lists, Sets, and Maps, along with their implementations like ArrayList, LinkedList, HashSet, and HashMap. Additionally, it covers multithreading concepts in Java, including thread states, creation methods, and thread lifecycle management.

Uploaded by

pranita.tathe15
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 138

Advance java Notes

Collection of Framework
What is a Java Collection Framework ?

A Java collection framework provides an architecture to store and manipulate


a group of objects. A Java collection framework includes the following:
1 Interfaces
2 Classes
3 Algorithm
Difference between Core Java and
Advance Java
• Core Java is the base. It has all the libraries need to develop desktop app and
without this libraries you cannot develop a single line of Java code. It has the Java
language compiler(JDK) and runtime(JRE). So without learning or deep dive
knowledge of core Java advanced Java is nothing. You cannot learn/compile/run a
single line of advanced Java code without core Java support. You need to install
and setup core Java first to run/test advanced Java.
• Advanced Java is nothing but a subset of libraries needed to run web based app
on top of Java. It has lot of nice names but they are almost same as core Java in
terms of coding standard and look. All the advanced Java code needs to compile
with core Java to run. And to run you need JRE always. Few of the advanced Java
components could be Servlet, JSP, EJB etc. There are many new components
come every year inside advanced Java but all of them written in core Java.
Sometimes few advanced Java libraries has been added into core Java due to
Advance java notes

• Interfaces:
• Interface in Java refers to the abstract data types. They allow Java
collections to be manipulated independently from the details of their
representation. Also, they form a hierarchy in object-oriented
programming languages.
• Classes:
• Classes in Java are the implementation of the collection interface. It
basically refers to the data structures that are used again and again.
• Algorithm: Algorithm refers to the methods which are used to
perform operations such as searching and sorting, on objects that
implement collection interfaces. Algorithms are polymorphic in
nature as the same method can be used to take many forms or you
can say perform different implementations of the Java collection
interface.
Java Collections : Interface

• Iterator interface : Iterator is an interface that iterates the elements.


It is used to traverse the list and modify the elements. Iterator
interface has three methods which are mentioned below:
• public boolean hasNext() – This method returns true if iterator has
more elements.
• public object next() – It returns the element and moves the cursor
pointer to the next element.
• public void remove() – This method removes the last elements
returned by the iterator.
Java collections: List

• A List is an ordered Collection of elements which may contain


duplicates. It is an interface that extents the Collection interface. Lists
are further classified into the following:
• ArrayList
• LinkedList
• Vectors
Array list:
• ArrayList is the implementation of List Interface where the elements
can be dynamically added or removed from the list. Also, the size of
the list is increased dynamically if the elements are added more than
the initial size.
• Syntax:
• ArrayList object = new ArrayList ();
Methods of ArrayList
Method Description
boolean
Appends the specified element to the end of a list.
add(Collection c)

void add(int index,


Inserts the specified element at the specified position.
Object element)
void clear() Removes all the elements from this list.
int Return the index in this list of the last occurrence of the
lastIndexOf(Object specified element, or -1 if the list does not contain this
o) element.
Object clone() Return a shallow copy of an ArrayList.
Linked List
• Linked List is a sequence of links which contains items. Each link
contains a connection to another link.
• Syntax: Linkedlist object = new Linkedlist();
• Java Linked List class uses two types of Linked list to store the elements:
• Singly Linked List
• Doubly Linked List
• Singly Linked List: In a singly Linked list each node in this list stores the
data of the node and a pointer or reference to the next node in the list.
Some of the methods in the
linked list are listed below:
Method Description

boolean add( Object o) It is used to append the specified element to the end of the vector.

boolean contains(Object
Returns true if this list contains the specified element.
o)

void add (int index,


Inserts the element at the specified element in the vector.
Object element)

void addFirst(Object o) It is used to insert the given element at the beginning.

void addLast(Object o) It is used to append the given element to the end.

int size() It is used to return the number of elements in a list

boolean remove(Object o) Removes the first occurrence of the specified element from this list.

int indexOf(Object
Returns the index of the first occurrence of the specified element in this list, or -1.
element)

int lastIndexOf(Object
Returns the index of the last occurrence of the specified element in this list, or -1.
element)
Doubly Linked List:

• In a doubly Linked list, it has two references, one to the next node and
another to previous node.
Method Description
boolean It is used to append the specified element to the end of the
add( Object o) vector.
boolean
contains(Object Returns true if this list contains the specified element.
o)
void add (int
index, Object Inserts the element at the specified element in the vector.
element)
Vectors
• Vectors are similar to arrays, where the elements of the vector object
can be accessed via an index into the vector. Vector implements a
dynamic array. Also, the vector is not limited to a specific size, it can
shrink or grow automatically whenever required. It is similar to
ArrayList, but with two differences :
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the
collections framework.
• Syntax:
• Vector object = new Vector(size,increment);
Method Description
boolean
Appends the specified element to the end of the list.
add(Object o)
void clear() Removes all of the elements from this list.
void add(int
index, Object Inserts the specified element at the specified position.
element)
boolean
Removes the first occurrence of the specified element from this
remove(Object
list.
o)
boolean
contains(Object Returns true if this list contains the specified element.
element)
int
Returns the index of the first occurrence of the specified
indexOfObject (
Java collections: Queue

• Queue in Java follows a FIFO approach i.e. it orders the elements in


First In First Out manner. In a queue,the first element is removed first
and last element is removed in the end. Each basic method exists in
two forms: one throws an exception if the operation fails, the other
returns a special value.
• Also, priority queue implements Queue interface. The elements of
the priority queue are ordered according to their natural ordering, or
by a Comparator provided at the queue construction time. The head
of this queue is the least element with respect to the specified
ordering.
Below are some of the methods of
Java Queue interface:
Method Description
Inserts the specified element into the
boolean add(object)
queue and returns true if it is a success.
Inserts the specified element into this
boolean offer(object)
queue.
Retrieves and removes the head of the
Object remove()
queue.
Retrieves and removes the head of the
Object poll() queue, or returns null if the queue is
empty.
Retrieves, but does not remove the head
Java Collections: Sets

• A Set refers to a collection that cannot contain duplicate elements. It


is mainly used to model the mathematical set abstraction. Set has its
implementation in various classes such as HashSet, TreeSetand
LinkedHashSet.
• HashSet:
• Java HashSet class creates a collection that use a hash table for
storage. Hashset only contain unique elements and it inherits the
AbstractSet class and implements Set interface. Also, it uses a
mechanism hashing to store the elements.
Below are some of the methods of Java HashSet class:
Method Description
boolean add(Object Adds the specified element to this set if it is not already
o) present.
boolean
Returns true if the set contains the specified element.
contains(Object o)
void clear() Removes all the elements from the set.

boolean isEmpty() Returns true if the set contains no elements.

boolean
Remove the specified element from the set.
remove(Object o)
Returns a shallow copy of the HashSet instance: the
Object clone()
elements themselves are not cloned.

Iterator iterator() Returns an iterator over the elements in this set.


Linked Hashset
• Java LinkedHashSet class is a Hash table and Linked list implementation of
the set interface. It contains only unique elements like HashSet. Linked
HashSet also provides all optional set operations and maintains insertion
order. Let us understand these linked Hashset with a programmatic
• TreeSet :
• TreeSet class implements the Set interface that uses a tree for storage.
The objects of this class are stored in the ascending order. Also, it inherits
AbstractSet class and implements NavigableSet interface. It contains only
unique elements like HashSet. In TreeSet class, access and retrieval time
are faster.
Below are some of the methods of Java TreeSet class:
Method Description
boolean addAll(Collectio
Add all the elements in the specified collection to this set.
n c)
boolean contains(Object
Returns true if the set contains the specified element.
o)
boolean isEmpty() Returns true if this set contains no elements.

boolean remove(Object o) Remove the specified element from the set.

void add(Object o) Add the specified element to the set.


void clear() Removes all the elements from the set.
Object clone() Return a shallow copy of this TreeSet instance.

Object first() Return the first element currently in the sorted set.

Object last() Return the last element currently in the sorted set.
Map
• HashMap
• : this implementation uses a hash table as the underlying data structure. It implements all of
the Mapoperations and allows null values and one null key. This class is roughly equivalent
to Hashtable - a legacy data structure before Java Collections Framework, but it is not synchronized
and permits nulls. HashMap does not guarantee the order of its key-value elements. Therefore,
consider to use a HashMap when order does not matter and nulls are acceptable.
• LinkedHashMap
• : this implementation uses a hash table and a linked list as the underlying data structures, thus the
order of a LinkedHashMap is predictable, with insertion-order as the default order. This
implementation also allows nulls like HashMap. So consider using a LinkedHashMap when you want
a Map with its key-value pairs are sorted by their insertion order.
• TreeMap:
• this implementation uses a red-black tree as the underlying data structure. A TreeMap is sorted
according to the natural ordering of its keys, or by a Comparator provided at creation time. This
implementation does not allow nulls. So consider using a TreeMap when you want a Map sorts its
key-value pairs by the natural order of the keys (e.g. alphabetic order or numeric order), or by a
custom order you specify.
Chapter 2
• A thread
• is a light-weight smallest part of a process that can run concurrently with the
other parts(other threads) of the same process.
• Threads are independent because they all have separate path of execution that’s
the reason if an exception occurs in one thread, it doesn’t affect the execution of
other threads. All threads of a process share the common memory. The process
of executing multiple threads simultaneously is known as multithreading.
• 1. The main purpose of multithreading is to provide simultaneous execution of
two or more parts of a program to maximum utilize the CPU time. A
multithreaded program contains two or more parts that can run concurrently.
Each such part of a program called thread.
Thread
• 2. Threads are lightweight sub-processes, they share the common memory space.
In Multithreaded environment, programs that are benefited from multithreading,
utilize the maximum CPU time so that the idle time can be kept to minimum.
• 3. A thread can be in one of the following states:
NEW – A thread that has not yet started is in this state.
RUNNABLE – A thread executing in the Java virtual machine is in this state.
BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.
WAITING – A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.
TIMED_WAITING – A thread that is waiting for another thread to perform an
action for up to a specified waiting time is in this state.
TERMINATED – A thread that has exited is in this state.
A thread can be in only one state at a given point in time.
Creating a thread in Java

• There are two ways to create a thread in Java:


1) By extending Thread class.
2) By implementing Runnable interface.
• Before we begin with the programs(code) of creating threads, let’s have a look at
these methods of Thread class. We have used few of these methods in the
example below.
• getPriority(): Obtain a thread’s priority
• getName(): It is used for Obtaining a thread’s name
• isAlive(): Determine if a thread is still running
• join(): Wait for a thread to terminate
• Run() Entry point for the thread.
• Sleep() suspend the thread for period of time.
• Start() start the thread by calling it’s run method.
• Sleep method in java
• The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.
• Syntax of sleep() method in java
• The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws InterruptedException
Life cycle of a Thread (Thread
States)
• A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
• A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
• 1) New
• The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
• 2) Runnable
• The thread is in runnable state after invocation of start() method, but the thread
• 3) Running
• The thread is in running state if the thread scheduler has selected it.
• 4) Non-Runnable (Blocked)
• This is the state when the thread is still alive, but is currently not eligible to run.
• 5) Terminated
• A thread is in terminated or dead state when its run() method exits.
Life cycle
new

Runnable

NonRunnable
blocked
Running

Terminated
Can we start a thread twice
• No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but
for second time, it will throw exception.
• What if we call run() method directly instead start() method?
• Each thread starts in a separate call stack.
• Invoking the run() method from main thread, the run() method goes onto the
current call stack rather than at the beginning of a new call stack.
• The join() method
• The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task
Syntax:
• public void join()throws InterruptedException
• .public void join(long milliseconds)throws InterruptedException.
• getName(),setName(String) and getId() method:
• public String getName()
• public void setName(String name)
• public long getId()
• The currentThread() method:
• The currentThread() method returns a reference to the currently executing
thread object.
• Naming Thread
• The Thread class provides methods to change and get the name of a thread. By
default, each thread has a name i.e. thread-0,
• thread-1 and so on. By we can change the name of the thread by using setName()
method. The syntax of setName() and
• getName() methods are given below:
• public String getName(): is used to return the name of a thread.
• public void setName(String name): is used to change the name of a thread.
• Priority of a Thread (Thread Priority):
• Each thread have a priority. Priorities are represented by a number between 1
and 10. In most cases, thread schedular schedules
• the threads according to their priority (known as preemptive scheduling). But it is
not guaranteed because it depends on JVM .
• specification that which scheduling it chooses.
3 constants defined in Thread class:
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
• Daemon Thread in Java
• Daemon thread in java
• is a service provider thread that provides services to the user thread. Its life
depend on the mercy of user .
• threads i.e. when all the user threads dies, JVM terminates this thread
automatically.
• There are many java daemon threads running automatically e.g. gc, finalizer etc.
• Points to remember for Daemon Thread in Java
• It provides services to user threads for background supporting tasks. It has no role
• Its life depends on user threads.
• It is a low priority thread.

No. Method Description

1) public void setDaemon(boolean is used to mark the current


status) thread as daemon thread or user
thread.

2) public boolean isDaemon() is used to check that current is


daemon.
Java Thread Pool
• Java Thread pool represents a group of worker threads that are waiting for the
job and reuse many times. In case of thread pool, a group of fixed size threads are
created. A thread from the thread pool is pulled out and assigned a job by the
service provider. After completion of the job, thread is contained in the thread
pool again.
• Advantage of Java Thread Pool
• Better performance It saves time because there is no need to create new thread.
• Real time usage
• It is used in Servlet and JSP where container creates a thread pool to process the
request.
ThreadGroup in Java

• java provides a convenient way to group multiple threads in a single object. In


such way, we can suspend, resume or interrupt group of threads by a single
method call.
• Java thread group is implemented by java.lang.ThreadGroup class.
• A ThreadGroup represents a set of threads. A thread group can also include the
other thread group. The thread group creates a tree in which every thread group
except the initial thread group has a parent.
• A thread is allowed to access information about its own thread group, but it
cannot access the information about its thread group's parent thread group or
any other thread groups.
Synchronization in Java
• Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
• Java Synchronization is better option where we want to allow only one thread to access
the shared resource.
• Why use Synchronization
• The synchronization is mainly used to
• To prevent thread interference.
• To prevent consistency problem.
• Types of Synchronization
• There are two types of synchronization
• Process Synchronization
• Thread Synchronization
Thread Synchronization
• There are two types of thread synchronization mutual exclusive and inter-thread
communication.
• Mutual Exclusive
• Synchronized method.
• Synchronized block.
• static synchronization.
• Cooperation (Inter-thread communication in java)
• Ex Table,mythread1,mythread2,testsynoch.
Java Socket

• Java Socket programming is used for communication between the applications


running on different JRE.
• Java Socket programming can be connection-oriented or connection-less.
• Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.
• The client in socket programming must know two information:
• IP Address of Server, and
• Port number.
Socket class

• A socket is simply an endpoint for communications between the machines. The


Socket class can be used to create a socket.
Method Description

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this


socket.

3) public synchronized void close() closes this socket


ServerSocket class

• The ServerSocket class can be used to create a server socket. This object is used
to establish communication with the clients.
Method Description

1) public Socket accept() returns the socket and establish a connection


between server and client.

2) public synchronized void close() closes the server socket.


Java URL
• 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.
• A URL contains many information:
• Protocol: In this case, http is the protocol.
• Server name or IP Address: In this case, www.javatpoint.com is the server name.
• Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port
number is not mentioned in the URL, it returns -1.
• File Name or directory name: In this case, index.jsp is the file name.
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.

Java 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.
How to get the object of URLConnection class
The openConnection() method of URL class returns the object of URLConnection class. Syntax:
public URLConnection openConnection()throws IOException{}
Displaying source code of a webpage by URLConnecton class

• The URLConnection class provides many methods, we can display all the data of a
webpage by using the getInputStream() method. The getInputStream() method
returns all the data of the specified URL in the stream that can be read and
displayed.
• Java HttpURLConnection class
• The Java HttpURLConnection class is http specific URLConnection. It works for
HTTP protocol only.
• By the help of HttpURLConnection class, you can information of any HTTP URL such
as header information, status code, response code etc.
• The java.net.HttpURLConnection is subclass of URLConnection class.
• How to get the object of HttpURLConnection class
• The openConnection() method of URL class returns the object of URLConnection
• public URLConnection openConnection()throws IOException{}
• Java 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.javatpoint.com, www.google.com, www.facebook.com etc.
Commonly used methods of InetAddress class
•Method Description

public static InetAddress getByName(String host) it returns the instance of InetAddress containing
throws UnknownHostException LocalHost IP and name.

public static InetAddress getLocalHost() throws it returns the instance of InetAdddress containing
UnknownHostException 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.


Java DatagramSocket and DatagramPacket
• Java DatagramSocket class
• Java DatagramSocket class represents a connection-less socket for sending and
receiving datagram packets.
• A datagram is basically an information but there is no guarantee of its content,
arrival or arrival time.
• Commonly used Constructors of DatagramSocket class
• DatagramSocket() throws SocketEeption: it creates a datagram socket and binds
it with the available Port Number on the localhost machine.
• DatagramSocket(int port) throws SocketEeption: it creates a datagram socket
and binds it with the given Port Number.
• DatagramSocket(int port, InetAddress address) throws SocketEeption: it
creates a datagram socket and binds it with the specified port number and host
address.
Java DatagramPacket class
• Java DatagramPacket is a message that can be sent or received. If you send
multiple packet, it may arrive in any order. Additionally, packet delivery is not
guaranteed.
• Commonly used Constructors of DatagramPacket class
• DatagramPacket(byte[] barr, int length): it creates a datagram packet. This
constructor is used to receive the packets.
• DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates
a datagram packet. This constructor is used to send the packets.
Java JDBC

• JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database. There are four types of
JDBC drivers:
• JDBC-ODBC Bridge Driver,
• Native Driver,
• Network Protocol Driver, and
• Thin Driver
• We can use JDBC API to access tabular data stored in any relational database. By
the help of JDBC API, we can save, update, delete and fetch data from the
database. It is like Open Database Connectivity (ODBC) provided by Microsoft.
JDBC API

JDBC Driver
Java application Database
What is API
• API (Application programming interface) is a document that contains a
description of all the features of a product or software. It represents classes and
interfaces that software programs can follow to communicate with each other. An
API can be created for applications, libraries, operating systems, etc.
• JDBC Driver
• Advantages:
• easy to use.
• can be easily connected to any database.
• Disadvantages:
• Performance degraded because JDBC method call is converted into the ODBC
function calls.
• The ODBC driver needs to be installed on the client machine.
Java Database Connectivity with 5 Steps
• There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection
• Java Database Connectivity with MySQL
• Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
• Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database,
in such case, we need to replace the sonoo with our database name.
• Username: The default username for the mysql database is root.
• Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
• Two ways to load the jar file:
• Paste the mysqlconnector.jar file in jre/lib/ext folder
• Set classpath
• 1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:
• Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
• 2) Set classpath:
• There are two ways to set the classpath:
• temporary
• C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
• Statement interface
• The Statement interface provides methods to execute queries with the
database. The statement interface is a factory of ResultSet i.e. it provides factory
method to get the object of ResultSet.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.

2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop,
insert, update, delete etc.

3) public boolean execute(String sql): is used to execute queries that may return multiple results.

4) public int[] executeBatch(): is used to execute batch of commands.


PreparedStatement interface

• The PreparedStatement interface is a subinterface of Statement. It is used to


execute parameterized query.
• Why use PreparedStatement?
• Improves performance: The performance of the application will be faster if you
use PreparedStatement interface because query is compiled only once.
Method Description
• public PreparedStatement prepareStatement(String query)throws SQLException{}
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.

public void setString(int paramIndex, String value) sets the String value to the given parameter index.

public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.

public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.

public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.
Java ResultSetMetaData Interface
• The metadata means data about data i.e. we can get further information from the
data.
• If you have to get metadata of a table like total number of column, column name,
column type etc. , ResultSetMetaData interface is useful because it provides
methods to get metadata from the ResultSet object.
Method Description
public int it returns the total number of columns in the ResultSet object.
getColumnCount()throws
SQLException
public String it returns the column name of the specified column index.
getColumnName(int
index)throws SQLException
public String it returns the column type name for the specified index.
getColumnTypeName(int
index)throws SQLException
public String getTableName(int it returns the table name for the specified column index.
index)throws SQLException
Java DatabaseMetaData interface
• DatabaseMetaData 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.
• public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
• public String getDriverVersion()throws SQLException: it returns the version number of the
JDBC driver.
• public String getUserName()throws SQLException: it returns the username of the database.
• public String getDatabaseProductName()throws SQLException: it returns the product name
of the database.
• public String getDatabaseProductVersion()throws SQLException: it returns the product
version of the database.
• public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types)throws SQLException: it returns the description of the tables of the specified
catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
store image in Sql database

• You can store images in the database in java by the help


of PreparedStatement interface.
• The setBinaryStream() method of PreparedStatement is used to set Binary
information into the parameterIndex.
• Signature of setBinaryStream method
• The syntax of setBinaryStream() method is given below:
• 1) public void setBinaryStream(int paramIndex,InputStream stream)
• throws SQLException
• 2) public void setBinaryStream(int paramIndex,InputStream stream,long length)

• throws SQLException
• CREATE TABLE "IMGTABLE"
• ( "NAME" VARCHAR2(4000),
• "PHOTO" BLOB
• )
• Advance jdbc
• Scrollable Resultset in JDBC
• In Jdbc ResultSet Interface are classified into two type;.
• Non-Scrollable ResultSet in JDBC
• Scrollable ResultSet
• By default a ResultSet Interface is Non-Scrollable, In non-scrollable ResultSet we can
move only in forward direction (that means from first record to last record), but not in
Backward Direction, If you want to move in backward direction use Scrollable Interface.
Difference
Non-Scrollable ResultSet Scrollable ResultSet

Cursor can move both forward and


1 Cursor move only in forward direction
backward direction

Slow performance, If we want to move Fast performance, directly move on any


1
nth record then we need to n+1 iteration record.

Non-Scrollable ResultSet cursor can not Scrollable ResultSet cursor can move
1
move randomly randomly

Type:
•public static final int TYPE_FORWARD_ONLY=1003
•public static final int TYPE_SCROLL_INSENSITIVE=1004
•public static final int TYPE_SCROLL_SENSITIVE=1005
Mode:
•public static final int CONCUR_READ_ONLY=1007
•public static final int CONCUR_UPDATABLE=1008
Methods of Scrollable ResultSet

• afterLast Used to move the cursor after last row.


• BeforeFirst: Used to move the cursor before first row.
• previous: Used to move the cursor backward.
• first: Used to move the cursor first at row.
• last: Used to move the cursor at last row.
• ResultSet.CONCUR_UPDATABLE
• ResultSet.TYPE_SCROLL_INSENSITIVE described in the Result Set tutorial. This
example would explain INSERT, UPDATE and DELETE operation on a table.
• It should be noted that tables you are working on should have Primary Key set
properly.
Date & Time Data Types

• The java.sql.Date class maps to the SQL DATE type, and the java.sql.Time and
java.sql.Timestamp classes map to the SQL TIME and SQL TIMESTAMP data types,
respectively.
• Following example shows how the Date and Time classes format the standard Java
date and time values to match the SQL data type requirements
• Batch Processing in JDBC
• Instead of executing a single query, we can execute a batch (group) of queries. It makes
the performance fast.
• The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for
batch processing.
• Advantage of Batch Processing
• Fast Performance
Example of batch processing in jdbc

• Load the driver class


• Create Connection
• Create Statement
• Add query in the batch
• Execute Batch
• Close Connection
Method Description

void addBatch(String query) It adds query into batch.

int[] executeBatch() It executes the batch of queries.


Servlets

• Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
• Servlet technology is robust and scalable because of java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this
technology. We have discussed these disadvantages below.
• There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
• What is a Servlet?
• Servlet can be described in many ways, depending on the context.
• Servlet is a technology which is used to create a web application.
• Servlet is an API that provides many interfaces and classes including documentation.
• Servlet is an interface that must be implemented for creating any Servlet.
• Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a dynamic
web page.

client server

Response
send to client
Advantages of Servlet

• There are many advantages of Servlet over CGI. The web container creates
threads for handling the multiple requests to the Servlet. Threads have many
benefits over the Processes such as they share a common memory area,
lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:
• Better performance: because it creates a thread for each request, not process.
• Portability: because it uses Java language.
• Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
• Secure: because it uses java language.
Life Cycle of a Servlet (Servlet Life
Cycle)
• The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
Life cycle

Loading and Unselected


initialization service

Destorying
Initialization the service

In service
Website

• Website is a collection of related web pages that may contain text, images, audio
and video. The first page of a website is called home page. Each website has
specific internet address (URL) that you need to enter in your browser to access a
website.
• Website is hosted on one or more servers and can be accessed by visiting its
homepage using a computer network. A website is managed by its owner that
can be an individual, company or an organization.
• Static website
• Static website is the basic type of website that is easy to create. You don't need
the knowledge of web programming and database design to create a static
website. Its web pages are coded in HTML.
• The codes are fixed for each page so the information contained in the page does
not change and it looks like a printed page.
Server Client Browser
Dynamic website

• Dynamic website is a collection of dynamic web pages whose content changes


dynamically. It accesses content from a database or Content Management System
(CMS). Therefore, when you alter or update the content of the database, the
content of the website is also altered or updated.
• Dynamic website uses client-side scripting or server-side scripting, or both to
generate dynamic content.
• Client side scripting generates content at the client computer on the basis of user
input. The web browser downloads the web page from the server and processes the
code within the page to render information to the user.
• In server side scripting, the software runs on the server and processing is completed
in the server then plain pages are sent to the user.
Clinet/Browser
server

Database
HTTP (Hyper Text Transfer Protocol)
• The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,
distributed, hypermedia information systems. It is the data communication protocol used to
establish communication between client and server.
• HTTP is TCP/IP based communication protocol, which is used to deliver the data like image
files, query results, HTML files etc on the World Wide Web (WWW) with the default port is
TCP 80. It provides the standardized way for computers to communicate with each other.
• HTTP Requests
• The request sent by the computer to a web server, contains all sorts of potentially interesting
information; it is known as HTTP requests.
• The HTTP client sends the request to the server in the form of request message which
includes following information:
• The Request-line
• The analysis of source IP address, proxy and port
• The analysis of destination IP address, protocol, port and host
• The Request method and Content
• The User-Agent header
• The Connection control header
• The Cache control header
• Get vs. Post
GET POST

1) In case of Get request, only limited amount of In case of post request, large amount of data can be
data can be sent because data is sent in header. sent because data is sent in body.

2) Get request is not secured because data is exposed in Post request is secured because data is not exposed in
URL bar. URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means second request Post request is non-idempotent.


will be ignored until response of first request is delivered

5) Get request is more efficient and used more than Post request is less efficient and used less than ge
Post.
Content Type
• Content Type is also known as MIME (Multipurpose internet Mail
Extension)Type. It is a HTTP header that provides the description about what are
you sending to the browser.
• MIME is an internet standard that is used for extending the limited capabilities of
email by allowing the insertion of sounds, images and text in a message.
• The features provided by MIME to the email services are as given below:
• It supports the non-ASCII characters
• It supports the multiple attachments in a single message
• It supports the attachment which contains executable audio, images and video
files etc.
• It supports the unlimited message length.
Reading All Form Parameters
• uses getParameterNames() method of HttpServletRequest to read all the
available form parameters. This method returns an Enumeration that contains the
parameter names in an unspecified order
• Once we have an Enumeration, we can loop down the Enumeration in standard
way by, using hasMoreElements() method to determine when to stop and
using nextElement() method to get each parameter name.
• HTTP Header Request
• getHeaderNames() method of HttpServletRequest to read the HTTP header
information. This method returns an Enumeration that contains the header
information associated with the current HTTP request.
• Once we have an Enumeration, we can loop down the Enumeration in the
standard manner, using hasMoreElements() method to determine when to stop
HTTP Header Response
• additionally we would use setIntHeader() method to set Refresh header.
• sendRedirect()
• Page redirection is a technique where the client is sent to a new location other
than requested. Page redirection is generally used when a document moves to a
new location or may be because of load balancing.
• The simplest way of redirecting a request to another page is using
method sendRedirect() of response object. Following is the signature of this
method −
• HTTP is a "stateless" protocol which means each time a client retrieves a Web
page, the client opens a separate connection to the Web server and the server
automatically does not keep any record of previous client request.
• Still there are following three ways to maintain session between web client and
web server −
• A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the recieved
cookie.
• This may not be an effective way because many time browser does not support a
cookie, so I would not recommend to use this procedure to maintain the sessions.
• Hidden Form Fields
• A web server can send a hidden HTML form field along with a unique session ID as
follows − This entry means that, when the form is submitted, the specified name
and value are automatically included in the GET or POST data. Each time when web
browser sends request back, then session_id value can be used to keep the track of
different web browsers.
• This could be an effective way of keeping track of the session but clicking on a
regular (<A HREF...>) hypertext link does not result in a form submission, so hidden
RequestDispatcher in Servlet

• The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the content of
another resource also. It is one of the way of servlet collaboration.
• There are two methods defined in the RequestDispatcher interface.
• Methods of RequestDispatcher interface
• The RequestDispatcher interface provides two methods. They are:
• public void forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request from a servlet to another resource
(servlet, JSP file, or HTML file) on the server.
• public void include(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or
HTML file) in the response.
• The HttpSession Object
• Apart from the above mentioned three ways, servlet provides
HttpSession Interface which provides a way to identify a user across
more than one page request or visit to a Web site and to store
information about that user.
• The servlet container uses this interface to create a session between
an HTTP client and an HTTP server. The session persists for a specified
time period, across more than one connection or page request from
the user.
ServletConfig Interface
• An object of ServletConfig is created by the web container for each servlet. This object can
be used to get configuration information from web.xml file.
• If the configuration information is modified from the web.xml file, we don't need to
change the servlet. So it is easier to manage the web application if any specific content is
modified from time to time.
• Advantage of ServletConfig
• The core advantage of ServletConfig is that you don't need to edit the servlet file if
information is modified from the web.xml file.
• Methods of ServletConfig interface
• public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
• public Enumeration getInitParameterNames():Returns an enumeration of all the
initialization parameter names.
• public String getServletName():Returns the name of the servlet.
URL Rewriting

• You can append some extra data on the end of each URL that identifies the
session, and the server can associate that session identifier with data it has
stored about that session.
• The HttpSession Object
• Apart from the above mentioned three ways, servlet provides HttpSession
Interface which provides a way to identify a user across more than one page
request or visit to a Web site and to store information about that user.
• The servlet container uses this interface to create a session between an HTTP
client and an HTTP server. The session persists for a specified time period, across
more than one connection or page request from the user.
Cookies in Servlet
• A cookie is a small piece of information that is persisted between the multiple
client requests.
• A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.
• How Cookie works
• By default, each request is considered as a new request. In cookies technique, we
add cookie with response from the servlet. So cookie is stored in the cache of the
browser. After that if request is sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old user.
Types of Cookie
• There are 2 types of cookies in servlets.
• Non-persistent cookie

Non-persistent cookie

• It is valid for single session only. It is removed each time when user closes the
browser.
• Persistent cookie
• It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
• Advantage of Cookies
• Simplest technique of maintaining the state.
• Cookies are maintained at client side.
• Disadvantage of Cookies
• It will not work if cookie is disabled from the browser.
Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot
be changed after creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.


Hidden Form Field

• In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining
the state of an user.
• In such case, we store the information in the hidden field and get it from another
servlet. This approach is better if we have to submit form in all the pages and we
don't want to depend on the browser.
• Let's see the code to store value in hidden field.
• Real application of hidden form field
• It is widely used in comment form of a website. In such case, we store page id or
page name in the hidden field so that each page can be uniquely identified.
• Advantage of Hidden Form Field
• It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:

• It is maintained at server side.


• Extra form submission is required on each pages.
• Only textual information can be used.
• HttpSessionEvent and HttpSessionListener
• The HttpSessionEvent is notified when session object is changed. The
corresponding Listener interface for this event is HttpSessionListener.
• We can perform some operations at this event such as counting total and current
logged-in users, maintaing a log of user details such as login time, logout time etc.
Hit Counter for a Web Page

• Many times you would be interested in knowing total number of hits on a particular page of your
website. It is very simple to count these hits using a servlet because the life cycle of a servlet is
controlled by the container in which it runs.
• Following are the steps to be taken to implement a simple page hit counter which is based on
Servlet Life Cycle −
• Initialize a global variable in init() method.
• Increase global variable every time either doGet() or doPost() method is called.
• If required, you can use a database table to store the value of global variable in destroy() method.
This value can be read inside init() method when servlet would be initialized next time. This step is
optional.
• If you want to count only unique page hits with-in a session then you can use isNew() method to
check if same page already have been hit with-in that session. This step is optional.
• You can display value of the global counter to show total number of hits on your web site. This step
Servlet Filter

• A filter is an object that is invoked at the preprocessing and postprocessing of a


request.
• It is mainly used to perform filtering tasks such as conversion, logging,
compression, encryption and decryption, input validation etc.
• The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet.
• So maintenance cost will be less.
Usage of Filter
• recording all incoming requests
• logs the IP addresses of the computers from which the requests originate
• conversion
• data compression
• encryption and decryption
• input validation etc.
• Advantage of Filter
• Filter is pluggable.
• One filter don't have dependency onto another resource.
• Less Maintenance
1) Filter interface
Method Description

public void init(FilterConfig config) init() method is invoked only once. It is used to
initialize the filter.

public void doFilter(HttpServletRequest doFilter() method is invoked every time when user
request,HttpServletResponse response, FilterChain request to any resource, to which the filter is
chain) mapped.It is used to perform filtering tasks.

public void destroy() This is invoked only once when filter is taken out of
the service.
2) FilterChain interface

• The object of FilterChain is responsible to invoke the next filter or resource in the
chain.This object is passed in the doFilter method of Filter interface.The
FilterChain interface contains only one method:
• public void doFilter(HttpServletRequest request, HttpServletResponse
response): it passes the control to the next filter or resource.
Event and Listener in Servlet
• Events are basically occurrence of something. Changing the state of an object is known as an event.
• We can perform some important tasks at the occurrence of these exceptions, such as counting total
and current logged-in users, creating tables of the database at time of deploying the project,
creating database connection object etc.
• There are many Event classes and Listener interfaces in the javax.servlet and javax.servlet.http
packages.
• Event classes
• The event classes are as follows:
• ServletRequestEvent
• ServletContextEvent
• ServletRequestAttributeEvent
• ServletContextAttributeEvent
• HttpSessionEvent
• HttpSessionBindingEvent
ServletContextEvent and ServletContextListener

• The ServletContextEvent is notified when web application is deployed on the


server.

If you want to perform some action at the time of deploying the web application
such as creating database connection, creating all the tables of the project etc,
you need to implement ServletContextListener interface and provide the
implementation of its methods.
• Constructor of ServletContextEvent class
• There is only one constructor defined in the ServletContextEvent class. The web
container creates the instance of ServletContextEvent after the ServletContext
instance.
Difference between Filter and
Listener
• Filter
• A filter is an object that dynamically intercepts requests and responses to transform or
use the information contained in the requests or responses.
• Filters typically do not themselves create responses but instead provide universal
functions that can be "attached" to any type of servlet or JSP page.
• The filter is run before rendering view but after controller rendered response.
• A Filter is used in the web layer only as it is defined in web.xml.
• Filters are more suitable when treating your request/response as a black box system.
They'll work regardless of how the servlet is implemented.
• Filters are used to perform filtering tasks such as login authentication ,auditing of
incoming requests from web pages, conversion, logging, compression, encryption and
decryption, input validation etc.
Listner
• Servlet Listener is used for listening to events in a web container, such as when
you create a session or place an attribute in a session or if you passivate and
activate in another container, to subscribe to these events you can configure
listener in web.xml, for example, HttpSessionListener.
• Listeners get triggered for an actual physical request that can be attached to
events in your app server .With listeners, you can track application-level, session-
level, life-cycle changes, attribute changes etc.
• You can monitor and react to events in a servlet's life cycle by defining listener
objects whose methods get invoked when lifecycle events occur.
JSP
• JSP technology is used to create web application just like Servlet technology. It can be thought of
as an extension to Servlet because it provides more functionality than servlet such as expression
language, JSTL, etc.
• A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet
because we can separate designing and development. It provides some additional features such
as Expression Language, Custom Tags, etc.
• Advantages of JSP over Servlet
• There are many advantages of JSP over the Servlet. They are as follows:
• 1) Extension to Servlet
• JSP technology is the extension to Servlet technology. We can use all the features of the Servlet
in JSP. In addition to, we can use implicit objects, predefined tags, expression language and
Custom tags in JSP, that makes JSP development easy.
• 2) Easy to maintain
• JSP can be easily managed because we can easily separate our business logic with presentation
logic. In Servlet technology, we mix our business logic with the presentation logic.
• 3) Fast Development: No need to recompile and redeploy
• If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look
and feel of the application.
• 4) Less code than Servlet
• In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.
• The Lifecycle of a JSP Page
• The JSP pages follow these phases:
• Translation of JSP Page
• Compilation of JSP Page
• Classloading (the classloader loads class file)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( the container invokes jspInit() method).
• Request processing ( the container invokes _jspService() method).
• Destroy ( the container invokes jspDestroy() method).
JSP Scriptlet tag (Scripting
elements)
• In JSP, java code can be written inside the jsp page using the scriptlet
tag. Let's see what are the scripting elements first.
• JSP Scripting elements
• The scripting elements provides the ability to insert java code inside
the jsp. There are three types of scripting elements:
• scriptlet tag
• expression tag
• declaration tag
JSP Buffer dynamic content
computer

Jsp translator
Servlet object

Servlet [java file]

JRE
compiler

Class file
The JSP API
• The JSP API consists of two packages:
• javax.servlet.jsp
• javax.servlet.jsp.tagext
• javax.servlet.jsp package
• The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as follows:
• JspPage
• HttpJspPage
• The classes are as follows:
• JspWriter
• PageContext
• JspFactory
• JspEngineInfo
• JspException
JSP expression tag
• The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to
print the values of variable or method.
• Syntax of JSP expression tag
• <%= statement %>
Difference between servlet and jsp
Servlet is a java code. JSP is a html based code.
Writing code for servlet is harder than JSP as it JSP is easy to code as it is java in html.
is html in java.
JSP is the view in MVC approach for showing
Servlet plays a controller role in MVC approach. output.

JSP is slower than Servlet because the first step


Servlet is faster than JSP. in JSP lifecycle is the translation of JSP to java
code and then compile.

Servlet can accept all protocol requests. JSP only accept http requests.
In Servlet, we can override the service()
method. In JSP, we cannot override its service() method.

In Servlet by default session management is not In JSP session management is automatically


JSP Implicit Objects
• here are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.
• The available implicit objects are out, request, config, session, application etc.
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
Exception Throwable
JSP response implicit object

• In JSP, response is an implicit object of type HttpServletResponse. The instance of


HttpServletResponse is created by the web container for each jsp request.
• It can be used to add or manipulate response such as redirect response to
another resource, send error etc.
• Let's see the example of response implicit object where we are redirecting the
response to the Google.
• JSP config implicit object
• In JSP, config is an implicit object of type ServletConfig. This object can be used to
get initialization parameter for a particular JSP page. The config object is created
by the web container for each jsp page.
• Generally, it is used to get initialization parameter from the web.xml file.
JSP config implicit object

• In JSP, config is an implicit object of type ServletConfig. This object can be used to get
initialization parameter for a particular JSP page. The config object is created by the
web container for each jsp page.
• Generally, it is used to get initialization parameter from the web.xml file.
• JSP application implicit object
• n JSP, application is an implicit object of type ServletContext.
• The instance of ServletContext is created only once by the web container when
application or project is deployed on the server.
• This object can be used to get initialization parameter from configuaration file
(web.xml). It can also be used to get, set or remove attribute from the application
scope.
session implicit object

• In JSP, session is an implicit object of type HttpSession.The Java developer can use
this object to set,get or remove attribute or to get session information.
• pageContext implicit object
• In JSP, pageContext is an implicit object of type PageContext class.The
pageContext object can be used to set,get or remove attribute from one of the
following scopes:page
• request
• session
• application
page implicit object:

• In JSP, page is an implicit object of type Object class.This object is assigned to the
reference of auto generated servlet class. It is written as:
• JSP directives
• The jsp directives are messages that tells the web container how to translate a
JSP page into the corresponding servlet.
• There are three types of directives:
• page directive
• include directive
• taglib directive
Attributes of JSP page directive

• import
• contentType
• extends
• info
• buffer
• language
• isELIgnored
• isThreadSafe
• autoFlush
• session
• pageEncoding
• errorPage
import

• The import attribute is used to import class,interface or all the members of a package.It is similar to import
keyword in java class or interface.
• contentType
• The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP
response.The default value is "text/html;charset=ISO-8859-1".
• 3)extends
• The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely used.
• 4)info
• This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo()
method of Servlet interface.
• 5)buffer
• The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The default
size of the buffer is 8Kb.
language

• The language attribute specifies the scripting language used in the JSP page. The
default value is "java".
• isELIgnored
• We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By
default its value is false i.e. Expression Language is enabled by default. We see
Expression Language later.
• isThreadSafe
• Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP
page, you can use isThreadSafe attribute of page directive.The value of isThreadSafe
value is true.If you make it false, the web container will serialize the multiple
requests, i.e. it will wait until the JSP finishes responding to a request before passing
another request to it.If you make the value of isThreadSafe attribute like:
• <%@ page isThreadSafe="false" %>
• errorPage
• The errorPage attribute is used to define the error page, if exception
occurs in the current page, it will be redirected to the error page.
• 10)isErrorPage
• The isErrorPage attribute is used to declare that the current page is
the error page.
Jsp Include Directive

• The include directive is used to include the contents of any resource it may
be jsp file, html file or text file. The include directive includes the original
content of the included resource at page translation time (the jsp page is
translated only once so it will be better to include static resource).
• Advantage of Include directive
• Code Reusability
• JSP Taglib directive
• The JSP taglib directive is used to define a tag library that defines many
tags. We use the TLD (Tag Library Descriptor) file to define the tags. In the
custom tag section we will use this tag so it will be better to learn it in
custom tag.
Exception Handling in JSP

• The exception is normally an object that is thrown at runtime.


Exception Handling is the process to handle the runtime errors. There
may occur exception any time in your web application. So handling
exceptions is a safer side for the web developer. In JSP, there are two
ways to perform exception handling:
• By errorPage and isErrorPage attributes of page directive
• By <error-page> element in web.xml file
JSP Action Tags
• There are many JSP action tags or elements. Each JSP action tag is used to
perform some specific tasks.
• The action tags are used to control the flow between pages and to use Java Bean.
The Jsp action tags are given below.
• The action tags are used to control the flow between pages and to use Java Bean.
The Jsp action tags are given below.
JSP Action Tags Description
jsp:forward forwards the request and response to another
resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward


and include mostly.

jsp:fallback can be used to print the message if plugin is


working. It is used in jsp:plugin.
jsp:include action tag
• The jsp:include action tag is used to include the content of another
resource it may be jsp, html or servlet.
• The jsp include action tag includes the resource at request time so it
is better for dynamic pages because there might be changes in future.
• The jsp:include tag can be used to include static as well as dynamic pages
• Advantage of jsp:include action tag
• Code reusability : We can use a page many times such as including header
and footer pages in all pages. So it saves a lot of time.
JSP include directive JSP include action

includes resource at translation time. includes resource at request time.


better for static pages. better for dynamic pages.
includes the original content in the generated calls the include method.
servlet.
Java Bean
• A Java Bean is a java class that should follow following conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as
getter and setter methods.
• Why use Java Bean?
• ccording to Java white paper, it is a reusable software component. A bean
encapsulates many objects into one object, so we can access this object from
multiple places. Moreover, it provides the easy maintenance.
• jsp:useBean action tag
• The jsp:useBean action tag is used to locate or instantiate a bean class. If bean
object of the Bean class is already created, it doesn't create the bean
• depending on the scope. But if object of bean is not created, it instantiates the bean.
• Attributes and Usage of jsp:useBean action tag
• id: is used to identify the bean in the specified scope.
• scope: represents the scope of the bean. It may be page, request, session or application. The default scope is
page.
• page: specifies that you can use this bean within the JSP page. The default scope is page.
• request: specifies that you can use this bean from any JSP page that processes the same request. It has wider scope than
page.
• session: specifies that you can use this bean from any JSP page in the same session whether processes the same request or
not. It has wider scope than request.
• application: specifies that you can use this bean from any JSP page in the same application. It has wider scope than session.
• class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must have no-arg or
no constructor and must not be abstract.
• type: provides the bean a data type if the bean already exists in the scope. It is mainly used with class or
beanName attribute. If you use it without class or beanName, no bean is instantiated.
• beanName: instantiates the bean using the java.beans.Beans.instantiate() method.
jsp:setProperty and jsp:getProperty action tags
• The setProperty and getProperty action tags are used for developing web
application with Java Bean. In web devlopment, bean class is mostly used
because it is a reusable software component that represents data.
• The jsp:setProperty action tag sets a property value or values in a bean using the
setter method.
• Displaying applet in JSP (jsp:plugin action tag)
• The jsp:plugin action tag is used to embed applet in the jsp file. The jsp:plugin
action tag downloads plugin at client side to execute an applet or bean.
Custom Tags in JSP
• Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag
and separates the business logic from the JSP page.
• The same business logic can be used many times by the use of custom tag.
• Advantages of Custom Tags
• The key advantages of Custom tags are as follows:
• Eliminates the need of scriptlet tag The custom tags eliminates the need of
scriptlet tag which is considered bad programming approach in JSP.
• Separation of business logic from JSP The custom tags separate the the business
logic from the JSP page so that it may be easy to maintain.
• Re-usability The custom tags makes the possibility to reuse the same business
logic again and again.
Attributes in JSP Custom Tag

• There can be defined too many attributes for any custom tag. To define the attribute,
you need to perform two tasks:
• Define the property in the TagHandler class with the attribute name and define the
setter method
• define the attribute element inside the tag element in the TLD file
• Let's understand the attribute by the tag given below:
• Iteration using JSP Custom Tag
• We can iterate the body content of any tag using the doAfterBody()method
of IterationTag interface.
• Here we are going to use the TagSupport class which implements the IterationTag
interface. For iterating the body content, we need to use
the EVAL_BODY_AGAIN constant in the doAfterBody() method.
Field Name Description

public static int EVAL_BODY_INCLUDE it evaluates the body content.

public static int EVAL_PAGE it evaluates the JSP page content after the custom
tag.

public static int SKIP_BODY it skips the body content of the tag.

public static int SKIP_PAGE it skips the JSP page content after the custom tag.
Custom URI in JSP Custom Tag

• We can use the custom URI, to tell the web container about the tld
file. In such case, we need to define the taglib element in the
web.xml. The web container gets the information about the tld file
from the web.xml file for the specified URI.
JSP Cookies Handling

• Cookies are the text files which are stored on the client machine.
• They are used to track the information for various purposes.
• It supports HTTP cookies using servlet technology
• The cookies are set in the HTTP Header.
• If the browser is configured to store cookies, it will keep information until expiry date.
• keep information until expiry date.
• Following are the cookies methods:
• Public void setDomain(String domain)It is used to set the domain to which the cookie
applies
• Public String getDomain()It is used to get the domain to which cookie applies
• Public void setMaxAge(int expiry)It sets the maximum time which should apply till the
• Public intgetMaxAge()It returns the maximum age of cookie
• Public String getName()It returns the name of the cookie
• Public void setValue(String value)Sets the value associated with the
cookie
• Public String getValue()Get the value associated with the cookie
• Public void setPath(String path)It sets the path to which cookie
applies
Pagination in JSP
• We can create pagination example in JSP easily. It is required if you have to
display many records. Displaying many records in a single page may take time, so
it is better to break the page into parts. To do so, we create pagination
application.
• In this pagination example, we are using MySQL database to fetch records.
• We have created "emp" table in "test" database. The emp table has three fields:
id, name and salary. Either create table and insert records manually or import our
sql file.
RMI (Remote Method Invocation)

• The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM.
• The RMI provides remote communication between the applications using two
objects stub and skeleton.
• Understanding stub and skeleton
• RMI uses stub and skeleton object for communication with the remote object.
• A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:
• stub
• The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
• It initiates a connection with remote Virtual Machine (JVM),
• It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
• It waits for the result
• It reads (unmarshals) the return value or exception, and
• It finally, returns the value to the caller.
• skeleton
• The skeleton is an object, acts as a gateway for the server side object. All the
incoming requests are routed through it. When the skeleton receives the
incoming request, it does the following tasks:
• It reads the parameter for the remote method
• It invokes the method on the actual remote object, and
• It writes and transmits (marshals) the result to the caller.

Machine A Manchine B
caller Remote object

interenet
Understanding requirements for the distributed
applications
• If any application performs these tasks, it can be distributed application.
• .The application need to locate the remote method
• It need to provide the communication with the remote objects, and
• The application need to load the class definitions for the objects.
• The RMI application have all these features, so it is called the distributed application.
• Java RMI Example
• The is given the 6 steps to write the RMI program.
• Create the remote interface
• Provide the implementation of the remote interface
• Compile the implementation class and create the stub and skeleton objects using the rmic tool
• Start the registry service by rmiregistry tool
• Create and start the remote application
• Create and start the client application
How t run program
• For running this rmi example,

• 1) compile all the java files

• javac *.java

• 2)create stub and skeleton object by rmic tool

• rmic AdderRemote

• 3)start rmi registry in one command prompt

• rmiregistry 5000

• 4)start the server in another command prompt

• java MyServer

• 5)start the client application in another command prompt

• java MyClient
• Struts 2 Tutorial
• struts 2 framework
• The struts 2 framework is used to develop MVC-based web application.
• The struts framework was initially created by Craig McClanahan and donated to
Apache Foundation in May, 2000 and Struts 1.0 was released in June 2001.
• The current stable release of Struts is Struts 2.3.16.1 in March 2, 2014.
• Struts 2 Framework
• The Struts 2 framework is used to develop MVC (Model View Controller) based
web applications. Struts 2 is the combination of webwork framework of
opensymphony and struts 1.
• Struts 2 provides many features that were not in struts 1. The
important features of struts 2 framework are as follows:
• Configurable MVC components
• POJO based actions
• AJAX support
• Integration support
• Various Result Types
• Various Tag support
• Theme and Template support
• ) Configurable MVC components
• In struts 2 framework, we provide all the components (view components and
action) information in struts.xml file. If we need to change any information, we
can simply change it in the xml file.
• 2) POJO based actions
• In struts 2, action class is POJO (Plain Old Java Object) i.e. a simple java class.
Here, you are not forced to implement any interface or inherit any class.
• 3) AJAX support
• Struts 2 provides support to ajax technology. It is used to make asynchronous
request i.e. it doesn't block the user. It sends only required field data to the
server side not all. So it makes the performance fast.
• 4) Integration Support
• We can simply integrate the struts 2 application with hibernate, spring, tiles etc.
frameworks.
• 5) Various Result Types
• We can use JSP, freemarker, velocity etc. technologies as the result in struts 2.
• 6) Various Tag support
• Struts 2 provides various types of tags such as UI tags, Data tags, control tags etc to
ease the development of struts 2 application.
• 7) Theme and Template support
• Struts 2 provides three types of theme support: xhtml, simple and css_xhtml. The
xhtml is default theme of struts 2. Themes and templates can be used for common
look and feel.
• Model 1 Architecture
• Servlet and JSP are the main technologies to develop the web applications.
• Servlet was considered superior to CGI. Servlet technology doesn't create process, rather it
creates thread to handle request. The advantage of creating thread over process is that it
doesn't allocate separate memory area. Thus many subsequent requests can be easily
handled by servlet.
• Problem in Servlet technology Servlet needs to recompile if any designing code is modified.
It doesn't provide separation of concern. Presentation and Business logic are mixed up.
• JSP overcomes almost all the problems of Servlet. It provides better separation of concern,
now presentation and business logic can be easily separated. You don't need to redeploy
the application if JSP page is modified. JSP provides support to develop web application
using JavaBean, custom tags and JSTL so that we can put the business logic separate from
our JSP that will be easier to test and debug.
• Disadvantage of Model 1 Architecture
• Navigation control is decentralized since every page contains the logic
to determine the next page. If JSP page name is changed that is
referred by other pages, we need to change it in all the pages that
leads to the maintenance problem.
• Time consuming You need to spend more time to develop custom
tags in JSP. So that we don't need to use scriptlet tag.
• Hard to extend It is better for small applications but not for large
applications.
• Model 2 (MVC) Architecture
• Model 2 is based on the MVC (Model View Controller) design pattern. The
MVC design pattern consists of three modules model, view and controller.
• Model The model represents the state (data) and business logic of the
application.
• View The view module is responsible to display data i.e. it represents the
presentation.
• Controller The controller module acts as an interface between view and
model. It intercepts all the requests i.e. receives input and commands to
Model / View to change accordingly.

You might also like