USCSP 369-Java II labbook
USCSP 369-Java II labbook
USCSP 369
Practical course on USCS 365
Object Oriented Programming using Java – II
Work Book
To be implemented from
Academic Year 2024–2025
Name:
Academic Year:
-1-
Editor:
Mrs. Aparna Gohad
MES Abasaheb Garware College (Autonomous), Pune
Reviewed By:
Mrs. Chitra Nagarkar
Head, Department of Computer Science
MES Abasaheb Garware College (Autonomous), Pune
-1-
INDEX
Table of Contents
1 Collections 2 7
2 Multithreading 3 19
3 Database Programming 3 28
4 Servlets 3 37
5 JSP 3
-2-
Introduction
1) Students are expected to carry this book every time they come to the lab for
practical.
2) Students should prepare oneself beforehand for the Assignment by reading the
relevant material.
3) Instructor will specify which problems to solve in the lab during the allotted slot
and student should complete them and get verified by the instructor. However
student should spend additional hours in Lab and at home to cover as many
problems as possible given in this work book.
4) Students will be assessed for each exercise on a scale from 0 to 5.
Not done 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
Well Done 5
-3-
5. Guidelines for Instructors
1) Explain the assignment and related concepts in around ten minutes using
white board if required or by demonstrating on Projector.
2) You should evaluate each assignment carried out by a student on a scale
of 5 as specified above by ticking appropriate box.
3) The value should also been written on assignment completion page
of the respective Lab course.
You have to ensure appropriate hardware and software is made available to each student.
The operating system and software requirements on server side and also client-side
areas given below:
Operating system: Linux
Editor: Any linux based editor like vi, gedit, eclipse etc.
Compiler: javac (Note : JAVA 8 and above version)
Web server: Tomcat
Database: PostgreSQL
-4-
Assignment Completion Sheet
Sr. Marks
No Assignment Name Signature
(Out of 5)
1 Collections
2 Multithreading
3 Database Programming
4 Servlets
5 JSP
Total out of 25
-5-
CERTIFICATE
Instructor HOD/Coordinator
-6-
Assignment 1: Collections
Objectives
What is Collection?
In Java we can store and transfer the data in the following ways.
1. Primitive data types
We can use primitive data types for storing only one element data and only one type
of data.
2. Class objects
Can store multiple fixed number of values of different type and can store multiple
data elements of multiple types.
3. Array Object
Can store multiple fixed number of values of same typefor storing many values of
same data type.
4. Collection Object
Can store multiple objects of same and different types without size limitations
Thus, if our requirement is store and process multiple objects then we go for
Collection Framework.
Limitations of Arrays -
1. Type(It is homogeneous in nature)
2. Size
3. Storing order
4. Operation Problem
Arrays Vs Collections
Arrays Collection
Fixed in size Growable
Can hold only homogeneous data Can hold both homogeneous &
heterogeneous data
No predefined method support For every requirement methods are available
Arrays can hold both primitives and objects Collections can hold only objects
-7-
Collection Framework
Collection
It is at the top of collection hierarchy and must be implemented by any class
that defines a collection. Following are some of the commonly used methods in this
interface.
Methods Description
Used to add objects to a collection. Returns true if
obj was added to the collection. Returns false if obj
boolean add( Object e )
is already a member of the collection, or if the
collection does not allow duplicates.
Add all elements of collection C to the invoking
boolean addAll( Collection C ) collection. Returns true if the element were added.
Otherwise, returns false.
To remove an object from collection. Returns true
boolean remove( Object obj ) if the element was removed. Otherwise, returns
false.
Removes all element of collection C from the
boolean removeAll( Collection C ) invoking collection. Returns true if the collection's
elements were removed. Otherwise, returns false.
To determine whether an object is present in
boolean contains( Object obj ) collection or not. Returns true if obj is an element
of the invoking collection. Otherwise, returns false.
Returns true if collection is empty, else returns
booleanisEmpty()
false.
int size() Returns number of elements present in collection.
Removes total number of elements from the
void clear()
collection.
-8-
Returns an array which consists of the invoking
Object[] toArray()
collection elements.
Deletes all the elements of invoking collection
boolean retainAll(Collection c)
except the specified collection.
Iterator iterator( ) Returns an iterator for the invoking collection.
Returns true if the invoking collection and obj are
boolean equals(Object obj)
equal. Otherwise, returns false.
Returns an array containing only those collection
Object[] toArray(Object array[]) elements whose type matches of the specified
array.
Implementations
The general-purpose implementations are summarized in the following table.
ArrayList class
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. .
Methods of ArrayList
Method Description
void add(int index, Object element) It is used to insert the specified element at the
specified position in a list.
boolean addAll(int index, Collection c) It is used to append all the elements in the
specified collection, starting at the specified
position of the list.
void clear() It is used to remove all of the elements from
this list.
-9-
void ensureCapacity(int requiredCapacity) It is used to enhance the capacity of an
ArrayList instance.
get(int index) It is used to fetch the element from the
particular position of the list.
It returns true if the list is empty, otherwise
boolean isEmpty() false.
boolean contains(Object o) It returns true if the list contains the specified
element
boolean remove(Object o) It is used to remove the first occurrence of
the specified element.
boolean removeAll(Collection c) It is used to remove all the elements from the
list.
void replaceAll(Collection c) It is used to replace all the elements from the
list with the specified element.
void retainAll(Collection c) It is used to retain all the elements in the list
that are present in the specified collection.
int size() It is used to return the number of elements
present in the list.
Linked List
Java LinkedList class provides implementation of linked-list data structure.
Important points to note
- 10 -
Object remove() It is used to retrieve and removes the first element of a list.
Object remove(int index) It is used to remove the element at the specified position in
a list.
It is used to return the number of elements in a list.
int size()
Set Implementation
Sets are further classified into the following:
HashSet
LinkedHashSet
TreeSet
HasSet
Underlying data structure for HashSet is hash table.
Duplicates are not allowed
Insertion order is not preserved
Heterogeneous objects insertion is allowed
‘Null’ insertion is possible
HashSet is best choice if our frequent operation is search
LinkedHashSet
Underlying data structure for LinkedHashSetis hash table and Linked List.
Duplicates are not allowed.
Insertion order is not preserved.
Heterogeneous objects insertion is allowed.
‘Null’ insertion is possible.
LinkedHashSet is best choice to develop catche based application.
TreeSet
Underlying data structure is balanced tree.
Duplicates are not allowed
Insertion order is not preserved but all objects will be inserted according to some
sorting order
Heterogeneous objects insertion is not allowed
‘Null’ insertion is possible but only once
HashSet is best choice if our frequent operation is search
Map
A Map is useful if you have to search, update or delete elements on the basis of a key.
There are two interfaces for implementing Map in java: Map and SortedMap, and
Three classes: HashMap, LinkedHashMap, and TreeMap.
Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain
any order.
- 11 -
LinkedHashMap LinkedHashMap is the implementation of Map. It inherits
HashMap class. It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap. It
maintains ascending order.
HashMap
Map contains its own methods. collection terminology is not applicable
Underlying datastructure forHashMapis hash table
Duplicates keys are not allowed but values are allowed
Insertion order is not preserved and it is based on hashcode of keys
Heterogeneous keys and values are allowed
‘Null’ insertion is possible
Best choice for searching
LinkedHashMap
Underlying datastructure forLinkedHashMap is hash table and Linked List
Duplicates keys are not allowed but values are allowed
Insertion order is preserved and it is based on hashcode of keys
Heterogeneous keys and values allowed
‘Null’ insertion is possible
Best choice for searching
SortedMap
It is child interface of Map.
Underlying data structure for SortedMap is hash table
Duplicates keys are not allowed but values
Insertion order is not preserved and it is based on hashcode of keys
Heterogeneous keys and values allowed
‘Null’ insertion is possible
Best choice for searching
TreeMap
Underlying data structure is RED-BLACK TREE
Duplicates keys are not allowed but values can be duplicated
Insertion order is not preserved and it is based on some sorting order ofkeys
Heterogeneous keys and values not allowed
Null acceptance is not there
Cursors
A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or
Stream object’s elements one by one.
Java supports the following three different cursors.
Enumeration
Iterator
ListIterator
- 12 -
Enumeration
We can use Enumeration to get objects one by one from the legacy collection objects.
We can create Enumeration object by using elements() method.
Enumeration interface defines the following two methods
public boolean hasMoreElements();
public Object nextElement();
Iterator
We can apply Iterator concept for any collection object hence it is universal cursor. By using
this we can perform both read and remove operations. We can create Iterator by using
Iterator() of collection interface.
public Iterator iterator();
Iterator itr = c.Iterator();
Where c is any collection object
Iterator Methods
Methods Description
next() Returns the next object
This returns a true value if a high number of elements are
boolean hasNext()
encountered during iteration.
This method removes the current element.
remove() Throws IllegalStateException if an attempt is made to call
remove( ) that is not preceded by a call to next( ).
ListIterator
By using this we can move either to f/w or b/w direction and hence it is
bidirectional cursor. We can perform replacement and addition of new objects in addition to
read and remove operation.
Note - It is most powerful cursor but its limitation is,it is applicable only for list implemented
class objects and it is not universal cursor.
ListIterator methods
Methods Description
void add(Object obj) Inserts obj into the list in front of the element that will be
returned by the next call to next( ).
boolean hasNext( ) Returns true if there is the next element. Otherwise, returns
false.
Returns true if there is a previous element. Otherwise,
boolean hasPrevious( ) returns false.
object next( ) Returns the next element. A NoSuchElementException is
thrown if there is not the next element.
int nextIndex( ) Returns the index of the next element. If there is not the
next element, returns the size of the list.
Object previous( ) Returns the previous element. A NoSuchElementException
is thrown if there is not a previous element.
int previousIndex( ) Returns the index of the previous element. If there is not a
previous element, returns -1.
void remove( ) Removes the current element from the list. An
IllegalStateException is thrown if remove( ) is called before
next( ) or previous( ) is invoked.
- 13 -
void set(Object obj) Assigns obj to the current element. This is the element last
returned by a call to either next( ) or previous( ).
Comparator
Comparator interface is used to order the objects of a user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object
obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of
any data member, for example, rollno, name, age or anything else
Self-Activity
Note: To use any Collection class in your program, you need to import java.util package.
Whenever you print any Collection class, it gets printed inside the square brackets [] with its
elements.
import java.util.ArrayList;
class ArrayListDemo
{
public static void main(String[] args)
{
// creating an Array List named colors
ArrayList Al = new ArrayList();
// add elements in the
Array ListAl.add("Red");
Al.add(5);
Al.add("Null");
Al.add("Orange");
Al.add("Red");
// printing the ArrayList
System.out.println(Al);
}
}
- 14 -
Sample Program 2 : Program to demonstrate LinkedList
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String>itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
}
}
- 15 -
Sample Program 4 : Program to demonstrate LinkedHashSet
- 16 -
Sample Program8 : Program to demonstrate ListIterator
Lab Assignments
SET A
1. Write a java program to accept names of ‘n’ cities, insert same into array list collection
and display the contents of same array list, also remove all these elements.
2. Write a java program to read ‘n’ names of your friends, store it into linked list, also
display contents using ListIterator interface.
3. Accept n integers from the user and store them in a collection. Display them in the sorted
order. The collection should not accept duplicate elements. (Use a suitable collection).
Search for a particular element using predefined search method in the Collection
- 17 -
framework.
4. Create a Hash map containing Employee name and Salary. Display the details of the hash
map. Also search for a specific Employee and display Salary of that Employee.
SET B
1. Construct a linked List containing names of colours: red, blue, yellow and orange. Then
extend your program to do the following:
a. Display the contents of the List using an Iterator
b. Display the contents of the List in reverse order using a ListIterator
c. Create another list containing pink and green. Insert the elements of this list
between blue and yellow.
2. Create a java application to store city names and their STD codes using an appropriate
collection. The GUI should allow the following operations:
a. Add a new city and its code (No duplicates)
b. Remove a city from the collection
c. Search for a city name and display the code
3. Write a menu driven program to create link list of integer objects. Do the following:
i. Add element at first position
ii. Delete last element
iii. Display the size of link list
SET C
1. Read a text file, specified by the first command line argument, into a list. The program
should then display a menu which performs the following operations on thelist:
1. Insert line 2. Delete line 3. Append line 4. Modify line 5. Exit
When the user selects Exit, save the contents of the list to the file and end theprogram.
2. Write a program that loads names and phone numbers from a text file where the data is
organized as one line per record and each field in a record are separated by a tab (\t).it
takes a name or phone number as input and prints the corresponding other value from the
hash table (hint: use hash tables)
Assignment Evaluation
- 18 -
Assignment 2: Multithreading
Objectives
Introduction:
A program can be divided into a number of small processes. Each small process can be
addressed as a single thread (a lightweight process).
Multithreaded programs contain two or more threads that can run concurrently and each
thread defines a separate path of execution. This means that a single program can perform
two or more tasks simultaneously. For example, one thread is writing content on a file at the
same time another thread is performing spelling check.
Why Multithreading?
Thread has many advantages over the process to perform multitasking. Process is heavy
weight, takes more memory and occupy CPU for longer time that may lead to performance
issue with the system. To overcome this issue process is broken into small unit of
independent sub-process. These sub-process are called threads that can perform independent
task efficiently. So nowadays computer systems prefer to use thread over the process and use
multithreading to perform multitasking.
- 19 -
Method 1: Thread creation by extending Thread class
class MultithreadingDemo extends Thread
{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[])
{
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
Output:
- 20 -
Determines if the currently running thread has permission
checkAccess()
to modify this thread.
Returns a reference to the currently executing thread
currentThread()
object.
getId() Returns the identifier of this Thread.
getState() Returns the state of this thread.
interrupt() Interrupts this thread.
isAlive() Tests if this thread is alive.
isDaemon() Tests if this thread is a daemon thread.
isInterrupted() Tests whether this thread has been interrupted.
setPriority(int newPriority) Changes the priority of this thread.
A hint to the scheduler that the current thread is willing to
yield()
yield its current use of a processor.
Priority of a Thread
Each thread have a priority. Priorities are represented by a number between 1 and 10.
Thread Synchronization
If multiple threads are trying to operate simultaneously on same java object, then
there may be a chance of data inconsistency problem. To overcome this problem,
we should go for Synchronization
If a method or block declared as synchronized then at a time only one thread is
allowed to execute that method or block on the given object so that data
inconsistency prob will be resolved.
Sample Program1: Below is a program that illustrates instantiation and running of threads using
the Runnable interface.
class RunnableThread implements Runnable
{
Thread runner;
public RunnableThread()
{
}
public RunnableThread(String threadName)
{
runner = new Thread(this, threadName); // Create a new thread.
System.out.println(runner.getName());
runner.start(); // Start the thread.
}
public void run()
{
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}
public class RunnableExample
{
public static void main(String[] args)
{
Thread thread1 = new Thread(new RunnableThread(), "thread1");
Thread thread2 = new Thread(new RunnableThread(), "thread2");
RunnableThread thread3 = new RunnableThread("thread3");
//Start the threads
thread1.start();
thread2.start();
try
{//delay for one second Thread.currentThread().sleep(1000);
}
catch (InterruptedException e)
{}
//Display info about the main thread
System.out.println(Thread.currentThread());}
}
- 22 -
Sample Program2:Creating multiple threads using the Thread class.
class MyThread extends Thread
{
String message;
MyThread(String message)
{
this.message = message;
}
public void run()
{
try
{
for(int i=1; i<=5; i++)
{
System.out.println(message + ”-” + i);
Thread.sleep(5000); //sleep for 5 seconds
}
}
catch(InterruptedException ie) { }
}
}
public class MultipleThreadDemo
{
public static void main( String[] args)
{
MyThread t1 = new MyThread(“One”);
MyThread t2 = new MyThread(“Two”);
System.out.println(t1);
System.out.println(t2); t1.start();
t2.start();
}
}
- 23 -
Sample Program3: Demonstrating Priority of a Thread
class PriorityDemo extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
PriorityDemo m1=new PriorityDemo();
PriorityDemo m2=new PriorityDemo();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
- 24 -
/* Main class */
class MySynchro
{
public static void main(String args[])
{
mythread t1=new mythread("Thread 1: ");
mythread t2=new mythread("Thread 2: ");
t1.start(); t2.start();
System.out.println("Main thread exited");
}
}
int tBal = 0;
public void run()
{
synchronized (this)
{
3. Write a program in which thread sleep for 2 sec in the loop in reverse order from 100
to 1 and change the name of thread.
4. Write a program that implements a multi-thread application that has three threads.
First thread generates random integer after every 1 second and if the value is even,
second thread computes the square of the number and prints. If the value is odd, the
third thread will print the value of cube of the number.
SET B
1. Write a program to calculate the sum and average of an array of 1000 integers
(generated randomly) using 10 threads. Each thread calculates the sum of 100 integers.
Use these values to calculate average. [Use join method].
2. Write a Java program using Runnable interface to blink Text on the frame.
4. Write a program for a simple search engine. Accept a string to be searched. Search
for the string in all text files in the current folder. Use a separate thread for each file.
The result should display the filename, line number where the string is found.
SET C
1. Write a Java program to show lifecycle (creation, sleep, and dead) of a thread. Program
should print randomly the name of thread and value of sleep time. The name of the
thread should be hard coded through constructor. The sleep time of a thread will be a
random integer in the range 0 to 4999.
- 26 -
2. Write a program to create a thread for moving a ball inside a panel vertically. The ball
should be created when the user clicks on the start button.
3. Write a program that simulates a traffic light. The program lets the user select one of
three lights: red, yellow, or green with radio buttons. On selecting a button, an
appropriate message with “stop” or “ready” or “go” should appear above the buttons in
a selected color. Initially there is no message shown.
Assignment Evaluation
- 27 -
Assignment 3: Database Programming
Objectives
This API contains of a set of classes and interfaces to enable programmers to communicate
with a database using java. These classes and interfaces are in the java.sql package.
JDBC Drivers
Load Driver
- 28 -
Example :
Class.forName(“org.postgresql.Driver”);
Establishing a connection
To establish a connection with the database, use the getConnection method of the
DriverManager class.
Boolean getAutoCommit() Retrieves the current auto-commit mode for this Connection
object.
DatabaseMetaData Retrieves a DatabaseMetaData object that contains metadata
getMetaData() about the database to which this Connection object
represents a connection.
CallableStatement Creates a CallableStatement object for calling database
prepareCall(String s ql) stored procedures.
CallableStatement Creates a CallableStatement object that will generate
prepareCall(String s ql, int ResultSet objects with the given type and concurrency.
resultSetType, int
resultSetConcurr ency)
- 29 -
void rollback() Undoes all changes made in the current transaction and
releases any database locks currently held by this Connection
object.
void setAutoCommit(Boolean Sets this connection's auto-commit mode to the given state.
autoCommit)
Executing Queries
To execute an SQL query, you have to use one of the following classes :
Statement
PreparedStatement
CallableStatement
CallableStatement objects are used to execute SQL stored procedures. The method
prepareCall(String sql) creates a CallableStatement object.
Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
To execute a query, call an execute method from Statement such as the following :
execute : Use this method if the query could return one or more ResultSet objects.
executeQuery : Returns one ResultSet object.
executeUpdate : Returns an integer representing the number of rows affected by the
SQL statement. Use this method if you are using INSERT, DELETE, or UPDATE
SQL statements.
Examples
Examples :
- 30 -
{
//access resultset data
}
To access these values, there are getXXX() methods where XXX is a type for example,
getString(), getInt() etc.
Example
rs.getString(“studname”)); rs.getString(1);
//where name appears as column 1 in the ResultSet
Using PreparedStatement
These are precompiled sql statements. For parameters, the SQL commands in a
PreparedStatement can contain placeholders which are represented by ‘?’ in the SQL
command.
Example
String sql = “UPDATE authors SET name = ? WHERE id = ?”;PreparedStatement ps =
conn.prepareStatement(sql);
Before the sql statement is executed, the placeholders have to be replaced by actual values.This
is done by calling a setXXX(int n, XXX x) method,
where XXX is the appropriate type for the parameter
For example, setString, setInt, setFloat, setDate etc,
n is the placeholder number and x is the value which replaces the placeholder.
Scroll Type
TYPE_FORWARD_ONLY The result set is not scrollable.
TYPE_SCROLL_INSENSITIVE The result set is scrollable but not sensitive to
database changes.
TYPE_SCROLL_SENSITIVE The result set is scrollable and sensitive to
database changes.
Concurrency Type
CONCUR_READ_ONLY The result set cannot be used to update the
database.
CONCUR_UPDATABLE The result set can be used to update the
database.
- 31 -
Example
Statement stmt = conn.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet Interface The ResultSet interface provides methods for retrieving and manipulating
the results of executed queries.
Methods Description
beforeFirst() Default position. Puts cursor before 1st row of ResultSet.
first() Puts cursor on 1st row of ResultSet.
last() Puts cursor on last row of ResultSet.
afterLast() Puts cursor after/beyond last row of ResultSet.
absolute (int pos) Puts cursor at row number position where absolute (1) is a 1st row
and absolute (-1) is last row of ResultSet.
relative (int pos) Puts cursor at row no. position relative from current position.
next() To move to the next row in ResultSet
previous() To move to the previous row in ResultSet.
void close() To close the ResultSet.
deleteRow() Deletes the current row from the ResultSet and underlying database.
getRow() Retrieves the current row number.
insertRow() Inserts the contents of the insert row into the ResultSet object and into
the database.
refreshRow() Refreshes the current row with its most recent value in the database.
updateRow() Updates the underlying database with the new contents of the current
row of this ResultSet object.
getXXX(String Retrieves the value of the designated column in the current row as a
columnName) corresponding type in the Java programming language. XXX
represents a type: Int, String, Float, Short, Long, Time etc.
moveToInsertRow() Moves the cursor to the insert row.
close() Disposes the ResultSet.
isFirst() Tests whether the cursor is at the first position.
isLast() Tests whether the cursor is at the last position.
isBeforeFirst() Tests whether the cursor is before the first position.
isAfterLast() Tests whether the cursor is after the last position.
updateXXX(int Updates the value of the designated column in the current row as a
columnNumber, corresponding type in the Java programming language. XXX
XXX value) represents a type: Int, String, Float, Short, Long, Time etc.
DatabaseMetaData
This interface provides methods that tell you about the database for a given connection
object.
Methods Description
getDatabaseProductName() Retrieves the name of this database product.
getDatabaseProductVersion() Retrieves the version number of this database product.
- 32 -
getDriverName() Retrieves the name of this JDBC driver.
Retrieves the version number of this JDBC driver as a String.
getDriverVersion()
getUserName() Retrieves the user name as known to this database.
getCatalogs() Retrieves the catalog names available in this database.
getSchemas(String catalog, Retrieves the schema names available in this database.
String schemaPattern)
Example
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTables(null, null, null,new String[] {"TABLE"});
while (rs.next())
System.out.println( rs.getString("TABLE_NAME"));
ResultSetMetaData
- 33 -
Methods Description
getColumnCount() Returns the number of columns in the current ResultSet
object.
Gives the maximum width of the column specified by the
getColumnDisplaySize(int index parameter.
column)
getColumnLabel(int column)Gives the suggested title for the column for use in display and
printouts.
getColumnName(int column) Gives the column name associated with the column index.
getColumnTypeName(int Gives the designated column's SQL type. isReadOnly(int
column) column) Indicates whether the designated column is read-
only.
isWritable(int column) Indicates whether you can write to the designated column.
isNullable(int column) Indicates the nullability of values in the designated column.
Self - Activity
Sample Program1 : Sample program to display employee data (empid, empname, salary)
import java.sql.*;
import java.io.*;
class JDBCDemo
{
public static void main(String[] args) throws SQLException
{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try
{Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql:empDB","postgres","");
if(conn==null)
System.out.println("Connection failed ");
else
{
System.out.println(“Connection successful..”);
stmt = conn.createStatement();
rs = stmt.executeQuery("Select * from emp");
while(rs.next())
{System.out.print("EmpID = " + rs.getInt(1));
System.out.println("EmpName = " + rs.getString(2));
System.out.println("Salary = " + rs.getInt(3));
}
con.close();
}
}
catch(Exception e)
{System.out.println(“ERROR”+e);
}
}//end of main
}// end of class
- 34 -
Sample Program2 : To perform insert and delete operations on employee table
using PreparedStatement (Empid, Empname, Empsalary)
import java.sql.*;
import java.io.*;
class JDBCDemoOp
{
public static void main(String[] args) throws SQLException
{
Connection con = null;Statement st = null;
ResultSet rs = null;
PreparedStatement ps1 = null, ps2=null;int eid,esal;
String ename;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql:EmpDB","postgres","");
st = conn.createStatement();
ps1 = con.prepareStatement("Insert into employee values(?,?,?)");
ps2 = con.prepareStatement("Delete employee where ID = ?");
if(con!=null)
System.out.println("Connection successful..");
System.out.println("Enter the employee ID, employee name and
employee salaryto be inserted ");
eid = Integer.parseInt(br.readLine());
ename = br.readLine();
esal = Integer.parseInt(br.readLine());
ps1.setInt(1,eid);
ps1.setString(2,ename);
ps1.setInt(3,esal);
ps1.executeUpdate();
Lab Assignments
SET A
1. Write a JDBC program to display all the details of the Person table in proper format on the
screen. Create a Person table with fields as PID, name, gender, birth_year in PostgreSQL.
Insert values in Person table.
2. Write a program to display information about the database and list all the tables in the database.
- 35 -
(Use DatabaseMetaData).
3. Write a program to display information about the ResultSet like number of columns
available in the ResultSet and SQL type of the column. Use Person table. (Use
ResultSetMetaData).
4. Write a JDBC program to display all the countries located in West Region. Create a table
Country in PostgreSQL with fields (Name, continent, Capital,Region). Insert values in the
table.
SET B
1. Write a JDBC program to insert the records into the table Employee(ID,name,salary) using
PreparedStatement interface. Accept details of Employees from user.
4. Write a menu driven program to perform the following operations on District (Name, area,
population) table.
i. Insert
ii. Modify
iii. Delete
iv. Search
v. View All
vi. Exit
SET C
1. Create a table Student with fields roll number, name, percentage using Postgresql. Insert
values in the table. Write a JDBC program to display all the details of the student table in a
tabular format on the screen. (Using Swing)
2. Create tables : Course (courseid, coursename, courseinstructor) Create a GUI based system
for performing the following operations on the table:
Course : Add Course, View All students of a specific course
Assignment Evaluation
Objectives
Servlet provides full support for sessions, a way to keep track of a particular user over time as
a website’s pages are being viewed. They also can communicate directly with a web server
using a standard interface.
Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a
standard part of the Java’s enterprise edition, an expanded version of the Java class library
that supports large-scale development projects.
Running servlets requires a server that supports the technologies. Several web servers, each
of which has its own installation, security and administration procedures, support Servlets.
The most popular one is the Tomcat- an open source server developed by the Apache
Software Foundation in cooperation with Sun Microsystems version 5.5 of Tomcat supports
Java Servlet.
Getting Tomcat
The software is available a a free download from Apache’s website at the address
http://jakarta.apache.org/tomcat. Several versions are available: Linux users should download
the rpm of Tomcat.
The javax.servlet package The important interfaces and classes are described in the table
below:
Interface Description
Servlet A java servlet must implement the Servlet interface. This interface
defines methods to initialize a servlet, to service requests, and to
remove a servlet from the server. These are known as life-cycle
methods.
ServletConfig The ServletConfig interface is used by the server to pass configuration
information to a servlet. Its methods are used by the servlet to retrieve
this information.
taglib Allows programmers to use new tags from tag libraries that
encapsulate more complex functionality and simplify the coding of a
JSP.
ServletRequest The ServletRequest interface encapsulates a client request for service.
It defines a number of methods for obtaining information about the
server, requester, and request.
- 37 -
ServletResponse The ServletResponse interface is used by a servlet to respond to a
request by sending information back to the client.
ServletContext The ServletContext interface defines the environment in which an
applet is executed. It provides methods that are used by applets to
access environment information.
SingleThreadModel The SingleThreadModel interface is used to identify servlets that must
be thread-safe. If a servlet implements this interface, the Web server
will not concurrently execute the service() method of more than one
instance of the servlet.
Class Description
GenericServlet The GenericServlet class implements the Servlet interface. You can
subclass this class to define your own servlets.
ServletInputStream The ServletInputStream class is used to access request information
supplied by a Web client. An object of this class is returned by the
getInputStream() method of the ServletRequest interface.
ServletOutputStream The ServletOutputStream class is used to send response information
to a Web client. An object of this class is returned by the
getOutputStream() method of the ServletResponse interface.
Interface Description
HttpServletRequest The HttpServletRequest interface extends the ServletRequest
interface and adds methods for accessing the details of an HTTP
request.
HttpServletResponse The HttpServletResponse interface extends the ServletResponse
interface and adds constants and methods for returning HTTP-
specific responses
HttpSession This interface is implemented by servlets to enable them to support
browserserver sessions that span multiple HTTP request-response
pairs. Since HTTP is a stateless protocol, session state is maintained
externally using client-side cookies or URL rewriting. This interface
provides methods for reading and writing state values and managing
sessions.
HttpSessionContext This interface is used to represent a collection of HttpSession objects
that are associated with session IDs.
Class Description
HttpServlet Used to create HTTP servlets. The HttpServlet class extends the
GenericServlet class.
Cookie This class represents an HTTP cookie. Cookies are used to maintain
session state over multiple HTTP requests. They are named data
values that are created on the Web server and stored on individual
browser clients. The Cookie class provides the method for getting and
setting cookie values and attributes.
A servlet’s life cycle methods function similarly to the life cycle methods of applets.
The init(ServletConfig) method is called automatically when a web server first begins
- 38 -
a servlet to handle the user’s request. The init() method is called only once.
ServletConfig is an interface in the javax.servlet package, containing the methods to
find out more about the environment in which a servlet is running.
The servlet action is in the service() method. The service() method checks the HTTP
request type (GET, POST, PUT, DELETE etc.) and calls doGet(), doPost(), doPut(),
doDelete() etc. methods. A GET request results from normal request for a URL or
from an HTML form that has no METHOD specified. The POST request results from
an HTML form that specifically lists POST as the METHOD.
The destroy() method is called when a web server takes a servlet offline.
Using Servlets
One of the main tasks of a servlet is to collect information from a web user and present
something back in response. Collection of information is achieved using form, which is a group
of text boxes, radio buttons, text areas, and other input fields on the web page. Each field on a
form stores information that can be transmitted to a web server and then sent to a Java servlet.
web browsers communicate with servers by using Hypertext Transfer Protocol(HTTP).
Form data can be sent to a server using two kinds of HTTP requests: get and post.
When web page calls a server using get or post, the name of the program that handles
the request must be specified as a web address, also called uniform resource locator
(URL). A get request affixes all data on a form to the end of a URL. A post request
includes form data as a header and sent separately from the URL. This is generally
preferred, and it’s required when confidential information is being collected on the
form.
Java servlets handle both of these requests through methods inherited from the
HTTPServlet class: doGet(HttpServletRequest, HttpServletResponse) and
doPost(HttpServletRequest, HttpServletResponse). These methods throw two kinds of
exceptions: ServletException, part of javax.servlet package, and IOException, an
exception in the java.io package.
The getparameter(String) method is used to retrieve the fields in a servlet with the
name of the field as an argument. Using an HTML document a servlet communicates
with the user.
While preparing the response you have to define the kind of content the servlet is
sending to a browser. The setContentType(String) method is used to decide the type of
response servlet is communicating. Most common form of response is written using
an HTML as: setContentType(“text/html”).
To send data to the browser, you create a servlet output stream associated with the
browser and then call the println(String) method on that stream. The getWriter()
method of HttpServletResponse object returns a stream. which can be used to send a
response back to the client.
Example
- 39 -
import java.io.*;
import javax.servlet.* ;
import javax.servlet.http.*;
public class MyHttpServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
// Use “req” to read incoming request
// Use “res” to specify the HTTP response status
//Use req.getParameter(String) or getParameterValues(String) to obtain
parameters
PrintWriter out = res.getWriter();//stream for output
// Use "out" to send content to browser
}
}
- 40 -
String getMethod() Returns the name of the HTTP method with
which this request was made for example GET,
POST, or PUT.
String getQueryString() Returns the query string that is contained in the
request URL after the path.
String getRemoteUser() Returns the login of the user making this request,
if the user has been authenticated, or null if the
user has not been authenticated.
After saving this servlet, compile it with the Java compiler as:
javac MyServlet.java.
To make the servlet available, you have to publish this class file in a folder on your web
server that has been designated for Java servlets. Tomcat provides the classes sub-folder to
deploy this servlet’s class file. Copy this class file in this classes sub-folder, which is
- 41 -
available on the path: tomcat/webapps/ WEB-INF/classes.
Now edit the web.xml file available under WEB-INF sub-folder with the following lines:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class> MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> MyServlet </servlet-name>
<url-pattern>/ MyServlet </url-pattern>
</servlet-mapping>
Repeat the above sequence of line to run every newly created servlet. Remember, these line
lines must be placed somewhere after the <web-app> tag and before the closing </web-app>
tag.
After adding these lines, save web.xml file. Restart the Tomcat service and run the servlet by
loading its address with a web browser as: http://localhost:8080/MyServlet.
Java’s Servlet also provides support for data handling using PostgreSQL database. For this
you have to do few simple steps.
1. Copy the jar file mentioned in Database Connectivity assignment into the subfolder:
tomcat/lib/common.
2. Edit the file .bash_profile of your login using command: vi .bash_profile.
3. Add the following line without removing any line.
4. export CLASSPATH=$CLASSPATH:/$HOME/tomcat/common/lib/<jar file> used in
database connectivity assignment.
5. Example: if I have postgresql-9.3-1104.jdbc4.jar file, I will type the line as export
CLASSPATH=$CLASSPATH:/$HOME/tomcat/common/lib/postgresql-9.3-1104.jdbc4.jar
6. Save this file. Logout from the terminal and re-login.
7. Create the table student(sno, sname) in your database. Insert few records into this table.
Session Handling
1. Using cookies
2. Using HttpSession class
1. Using Cookies
To keep the track of information about you and the features you want the site to
display. This customization is possible because of a web browser features called
cookies, small files containing information that a website wants to remember about a
user, like username, number of visits, and other. The files are stored on the user’s
computer, and a website can read only the cookies on the user’s system that the site
has created. The default behavior of all the web browsers is to accept all cookies.
- 42 -
The javax.servlet.http.Cookie class allows us to create a cookie and send it to the
browser. The methods are:
Method Description
int getMaxAge() Returns the maximum age of the cookie, specified in
seconds, By default, -1 indicating the cookie will persist
until browser shutdown.
String getName() Returns the name of the cookie.
String getValue() Returns the value of the cookie.
void setMaxAge(int s) Sets the maximum age of the cookie in seconds.
void setValue (String Assigns a new value to a cookie after the cookie is created.
value)
2.HttpSession class
Servlet can retain the state of user through HttpSession, a class that represents sessions. There
can be one session object for each user running your servlet.
// ….
}
Objects held by session are called its attributes. Call the session’s setAttribute(String,
Object) method with two arguments: a name to give the attribute and the object.
To retrieve an attribute, call the getAttribute(String) method with its name as the only
argument. It returns the object, which must be cast from object to the desired class, or
null if no attribute of that name exists.
To remove an attribute when it’s no longer needed, call removeAttribute(String) with
its name as the argument.
- 43 -
Method Description
Object getAttribute(String Returns the object bound with the specified name in this
name) session, or null if no object is bound under the name.
Enumeration Returns an Enumeration of String objects containing the
getAttributeNames() names of all the objects bound to this session.
long getCreationTime() Returns the time when this session was created,
measured in milliseconds since midnight January 1,
1970 GMT.
long getLastAccessedTime() Returns the last time the client sent a request associated
with this session, as the number of milliseconds since
midnight January 1, 1970 GMT, and marked by the time
the container received the request.
int getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the
servlet container will keep this session open between
client accesses
void RemoveAttribute(String Removes the object bound with the specified name from
name) this session.
void setAttribute(String Binds an object to this session, using the name specified.
name, Object value)
void Specifies the time, in seconds, between client requests
setMaxInactiveInterval(int before the servlet container will invalidate this session.
seconds)
void invalidate() Invalidates this session then unbinds any objects bound
to it.
Boolean isNew() Returns true if it is a new session.
String getId() Returns a string containing the unique identifier
assigned to this session.
Self Activity
- 44 -
After saving this servlet, compile it with the Java compiler as: javac MyServlet.java. Run theservlet using
http://localhost:8080/MyServlet
<html>
<head>
<title>Subtraction of Two Number </title>
</head>
<body>
<form method="post" action="http://server-ip or localhost:8080/SubServlet">
Enter the Number1 <input type="text" name="No1">
Enter the Number2 <input type="text" name="No2">
<br> <input type="Submit" value =”SUB” >
<br> <input type="Reset" value =”CLEAR” >
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
- 45 -
//Create a student table (sno, sname)
//The servlet displays all records from the student table on theclient machine.
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ServletJdbc extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,
ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try
{
out.println("<html>");
out.println("<body>");
Class.forName("org.postgresql.Driver");
out.println("<h1>Driver loaded</h1>");
Connection c =
DriverManager.getConnection("jdbc:postgresql:m2","postgres","");
out.println("<h1>Connection created</h1>");
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from student");
while(rs.next())
{
out.print("<h3>"+rs.getInt(1)+" –
"+rs.getString(2)+"</h3>");
out.println("<br>");
}
}
catch(SQLException e)
{
out.println("ERROR"+e);
}
out.println("<h1>Hi! Manisha</h1>");
out.println("</body>");
out.println("</html>");
}
}
Run this program as http://server-ip:8080/ServletJdbc
- 46 -
Sample Program 4 : For Add the cookies
//Save this program as AddCookie.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
{
Cookie [] c=req.getCookies();
res.setContentType("text/html");
PrintWriter out = res.getWriter();
for(int i=0;i<c.length;i++)
out.println("Cookie Name"+c[i].getName()); pw.close();
}
}
- 47 -
Sample Program 5 : Program for Session using Servlet
//Save this program as DemoSession.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoSession extends HttpServlet
{
String result1="success";
String result2="failure";
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
HttpSession hs=req.getSession(true);
String uname = req.getParameter("txt1");
String pwd = req.getParameter("txt2");
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
if((uname.equals("covid"))&&(pwd.equals("covid19")))
{
pw.print("<a href=http://localhost:8080/NewInfo.html>
Login Success</a>");
hs.setAttribute("loginID",result1);
}
else
{
pw.print("<a href=http://localhost:8080/NewInfo.html> Kick Out</a>");
hs.setAttribute("loginID",result2);
}
pw.close();
}
}
- 48 -
<!—HTML File for NewInfo.html --> <html>
<head> <title></title>
</head>
<body> <form method="post" action="http://localhost:8080/SessionInfo">
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpSession hs = req.getSession(true);
readloginid = hs.getId();
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
if(hs.getAttribute("loginID").equals("success"))
pw.print("Your Session ID " + readloginid);
else
pw.print("<h1>Session Expired </h1>");
pw.close();
}
}
Create an html file for login and password and use http://server-ip:8080/SessionDemo in the
Form Action tag.
SET A
1. Write a servlet program to display IP address, browser type, current date and time of
server.
2. Write a servlet program to accept username and display message as “Have a Nice
day!!!” with username.
- 49 -
SET B
1. Design the table User (username, password) using Postgre Database. Design HTML
login screen. Accept the user name and password from the user. Write a servlet
program to accept the login name and password and validates it from the database
you have created. If it is correct then display Welcome.html otherwise display
Error.html.
2. Write a Servlet program to display number of times user has visited the page. (Use
Session)
SET C
Assignment Evaluation
- 50 -
Assignment 5: JSP
Objectives
What is JSP?
JSP is Java Server Page, which is a dynamic web page and used to build dynamic websites.
To run jsp, we need web server which can be tomcat provided by apache, it can also be jRun,
jBoss(Redhat), weblogic (BEA) , or websphere(IBM).
JSP is dynamic file whereas Html file is static. HTML cannot get data from database or
dynamic data. JSP can be interactive and communicate with database and controllable by
programmer. It is saved by extension of .jsp. Each Java server page is compiled into a servlet
before it can be used. This is normally done when the first request to the JSP page is made.
1. Directives:- these are messages to the JSP container that is the server program that
executes JSPs.
2. Scripting elements:- These enables programmers to insert java code which will be
a part of the resultant servlet.
3. Actions:- Actions encapsulates functionally in predefined tags that programmers
can embedded in a JSP.
JSP Directives
Directives are message to the JSP container that enable the programmer to specify page
setting to include content from other resources & to specify custom tag libraries for use in a
JSP.
Syntax
<%@ name attribute1=”….”, attribute2=”…”…%>
Directive Description
page Defines page settings for the JSP container to process.
include Causes the JSP container to perform a translation-time insertion of another
resource's content. The file included can be either static ( HTML file) or
dynamic (i.e., another tag file)
taglib Allows programmers to use new tags from tag libraries that encapsulate more
complex functionality and simplify the coding of a JSP.
Page Directive
The page directives specify global settings for the JSP in the JSP container. There can be
many page directives, provided that there is only one occurrence of each attribute.
Syntax
- 51 -
<%@ page
[ language="java" ]
[ extends="package.class" ]
[ import="{package.class | package.*}, ..." ]
[ session="true|false" ]
[ buffer="none|8kb|sizekb" ]
[ autoFlush="true|false" ]
[ isThreadSafe="true|false" ]
[ info="text" ]
[ errorPage="relativeURL" ]
[ contentType="mimeType [ ; charset=characterSet ]" "text/html ; charset=ISO-8859-1" ]
[ isErrorPage="true|false" ]
[ pageEncoding="characterSet | ISO-8859-1" ] %>
Scripting Elements
1. Declarations
A declaration declares one or more variables or methods that you can use in Java code
later in the JSP file.
Syntax
2. Expressions
An expression element contains a java expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file.
Syntax
Example
3. Scriptlet
A scriptlet contains a set of java statements which is executed. A scriptlet can have
java variable and method declarations, expressions, use implicit objects and contain
any other statement valid in java.
Syntax
To run JSP files: all JSP code should be copied (Deployed) into webapps folder in the tomcat
server. To execute the file, type: http://server-ip:8080/Programname.jsp
Self Activity
Sample Program1 : Simple display on browser.
/* type this as first.jsp */
<html>
<body>
<% out.print("DREAMS Don’t work UNLESS YOU DO!"); %>
</body>
</html>
- 53 -
<%@ page language="java" import="java.util.*" %>
<html>
<body> Current Date time: <%=new java.util.Date()%>
</body>
</html>
</form>
</body>
Lab Assignments
</html>
SET A
1. Create a JSP page to accept a number from user and display it in words: Example:
123 – One Two Three.
SET B
1. Create a JSP page, which accepts user name in a text box and greets the user
according to the time on server side.
- 54 -
If it is afternoon then display message in green color as,
Good afternoon Admin
Today’s date: dd/mm/yyyy format
Current time: hh:mm:ss format
2. Write a JSP program to display number of times user has visited the page. (Use
cookies)
SET C
1. Write a JSP program to display details of products from database in tabular format.
Design Product table in database as (pid, pname, qty, price)
Assignment Evaluation
- 55 -