Java Sem 2
Java Sem 2
(Computer Science)
Laboratory Course II
(Programming in Java – II : CS-345 )
Semester II
Name ________________________________ Roll No. _______
CHAIRPERSON:
PROF. MRS. CHITRA NAGARKAR
CO-ORDINATOR:
PROF. MS. POONAM PONDE
AUTHORS:
Mr. Jeevan Limaye
Ms. Poonam Ponde
Mr. Sachin Bhoite
Ms. Kalpana Joshi
BOARD OF STUDY (COMPUTER SCIENCE) MEMBERS:
1. DR.VILAS KHARAT
2. MR. S. S. DESHMUKH
3. MRS. CHITRA NAGARKAR
4. MR. U. S. SURVE
5. MR. M. N. SHELAR
6. MR. V. R. WANI
7. MR. PRASHANT MULE
8. MR. S. N. SHINDE
9. MR. R. VENKATESH
ABOUT THE WORK BOOK
• OBJECTIVES OF THIS BOOK
• Difficulty Levels
Self Activity : Students should solve these exercises for practice only.
SET A - Easy : All exercises are compulsory.
SET B - Medium : At least one exercise is mandatory.
SET C - Difficult : Not Compulsory.
2 Multithreading
4 Collections
5 Servlets
7 Networking
Total:
Signature of Incharge:
Examiner I :
Examiner II :
Date:
Assignment 1: Graphics Programming Start Date / /
using Swing
Objectives
Reading
You should read the following topics before starting this exercise
1. Swing components.
2. The java.awt.Graphics class.
3. The paint and paintComponent method.
4. Methods of javax.swing.Graphics2D class.
5. Classes in the java.awt.geom package
6. Methods of java.awt.Color class
7. Methods of java.awt.Font class
Ready Reference
Drawing Text
To draw text, call a Graphics2D object’s drawString() method with three arguments
• The String to display
• The x coordinate where it should be displayed
• The y coordinate where it should be displayed
The x,y coordinate used in the drawString() method represent the pixel at the lower-left
corner of the string. Following code draws the string:
public void paintComponent(Graphics comp)
{
Graphics2D comp2D=(Graphics2D)comp;
comp2D.drawString(“Welcome to the 2D world”,22,100);
}
Examples:
Rectangle2D rect = new Rectangle2D.Double(100, 100, 200, 100);
Line2D line1 = new Line2D.Double(100, 100, 200, 200);
Draw Rectangles
Rectangles are created by using the Rectangle2D.Float class or Rectangle2D.Double
class. The difference is that one takes float arguments and the other takes double
argument. Rectangle2D.Float takes four arguments: x, y, width, and height.
Example:
Rectangle2D.Float rc = new Rectangle2D.Float(10F, 13F, 40F, 20F);
Creates a rectangle at 10,13 that is 40 pixels wide by 20 pixels tall.
Draw Ellipse
Ellipses, which were called ovals in early created with the Ellipse2D.Float class. It takes
four arguments: x, y, width and height.
Example:
Ellipse2D.Float ee=new Ellipse.Float(11,25,22,40);
Creates an ellipse at 113,25with a width of 22 pixels amd a height of 40 pixels.
Draw Arcs
Of all the shapes we drawn, an arc is the complex shape to construct. Arcs are created
with the Arc2D.Float class, which takes seven arguments:
Creates an arc for an oval at 27,22 that is 42 pixels wide by 30 pixels tall. The arc begins
at 33 degrees, extends 90 degrees clockwise and is closed like pie slice.
Draw Polygons
Polygons are created by defining each movement from one point on the polygon to
another. A polygon can be formed from straight lines, quadratic curves or Bezier curves.
The movements to create a polygon are defined as a GeneralPath object, which is part of
the java.awt.geom package. A GeneralPath object can be created without any arguments:
GeneralPath poly = new GeneralPath();
The moveto() method of GeneralPath is used to create the first point on the polygon. The
statement
poly.moveTo(5f, 0f);
Used if you wanted to start polly at the coordinate 5,0. After creating the first point, the
lineTo() method is used to create lines that end at a new point. Takes two arguments: x,y
coordinate of the new point.
Following statement add three lines to the polly object:
poly.lineTo(205f,0f);
poly.lineTo(205f,90f);
poly.lineTo(5f,90f);
The poly object is rectangle with points at 5,0; 205,0; 205,90; 5,90
The lineTO() and moveTo() methods require float arguments to specify coordinate points.
To close polygon, the closePath() method is used without any arguments, as:
polly.closePath();
Method closes a polygon by connecting the current point with the point specified by the
most recent moveTo() method. Alternative approach to close polygon is to use a lineTo()
method that connects to the original point. After you have created an open or closed
polygon, draw it using the draw() and fill() methods.
• Setting Colors
The Color and ColorSpace classes of the java.awt package can be used to make a
graphical user interface more colorful. With these classes, you can set the color for use in
drawing operations, as well as the background color of an interface component and other
windows. By default Java uses colors according to the sRGB color-description system. A
color is described by the amounts of red, green and blue it contains. Each of R, G, and B
To create a specific color, the constructors of the Color class can be used to create an
object.
i. Color(int r, int g, int b)
ii. Color(float r, float g, float b)
iii. Color (float r, float g, float b, float a)
iv. Color (int r, int g, int b, int a)
Here, r, g and b represent the three constituent colors: red, green and blue respectively.
(0-255 for int and 0.0-1.0 for float). a represents the alpha value (0.0 – transparent, 1.0 -
opaque)
Example:
Color c = new Color(0,0,0); //black
Color c = new Color(255,255,255); //white color
The following methods are used with graphics objects and AWT or Swing components
for working with colors.
Method Description
void setColor(Color c) Changes the current color. All subsequent graphics
operations will use the new color.
Color getColor() Returns the current color
void setPaint(Paint p) Sets the paint attribute of the graphics context.
void setBackground(Color c) Sets the background color of a component
void setForeground(Color c) Sets the foreground color of a component
• Displaying images
Self Activity
1. Sample program
/* Program to draw simple graphics objects in a panel*/
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
class GraphicsDemo extends JFrame
{
public GraphicsDemo ()
{
setTitle("Graphics2D Demo");
setSize(400, 400);
GraphicsPanel p = new GraphicsPanel();
p.setBackground(Color.red);
p.setForeground(Color.white);
add(p);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
2. Sample program
/* Program to Draw Polygon
Lab Assignments
Set A
1. Write a Java program to display “Hello 2D Graphics” using various fonts and sizes.
2. Write a program to list all machine fonts and their font metrics.
3. Write a Java program to obtain the information of the current font used by the
graphics object and displays the information about that font on a screen.
4. Write a program to accept the name of an image (using file open dialog) and display it
on a panel such that it occupies the whole panel area.
Set B
Label1
Label2
Apply
Red
Green
Blue
The first scroll bar will handle the Red color, second will handle the Green color and third
will handle the Blue color. Set min=0, max=255 for the scroll bars. The screen has two
labels and one command button “apply”. When user clicks on the Apply button, set the
background color of the label according to the RGB values. Display the values of Red,
Green and Blue scrollbars in the label2.
Set C
1. Write a Java program to design the following screen:
Allow user to select the appropriate values of Font, Font Style and size. Display the
selection in the appropriate text boxes above. When user clicks on the Apply button the
selection should get apply on the text typed in the text box 4.
Background Label1
Color
Foreground Label2
Color
Text Box 1
All 15 rectangles will display the color list of all 15 colors given in the ready reference.
Background color and Foreground color are command buttons, Label1 and Label2 are the
label controls. Text Box1 is the text box control. User can select any color from the
palette. When the user clicks on Background color button, the color of label1 should
change to the selected color. When user click on Foreground color the color of label2
should be changed. When you start typing in the text box, the selected background and
foreground color should be used.
Objectives
Reading
You should read the following topics before starting this exercise:
1. Thread class
2. Runnable interface
3. Thread lifecycle
4. Thread methods
Ready Reference
Introduction
Nearly every operating system supports the concept of processes -- independently running
programs that are isolated from each other to some degree. Threading is a facility to allow
multiple activities to coexist within a single process. Java is the first mainstream
programming language to explicitly include threading within the language itself.
A process can support multiple threads, which appear to execute simultaneously and
asynchronously to each other. Multiple threads within a process share the same memory
address space, which means they have access to the same variables and objects, and they
allocate objects from the same heap.
Thread Lifecycle:
The lifecycle of thread consist of several states which thread can be in. Each thread is in
one state at any given point of time.
1. New State: - Thread object was just created. It is in this state before the start ()
method is invoked. At this point the thread is considered not alive.
2. Runnable or ready state:- A thread starts its life from Runnable state. It enters this
state the time start() is called but it can enter this state several times later. In this state,
a thread is ready to run as soon as it gets CPU time.
3. Running State:- In this state, a thread is assigned a processor and is running. The
thread enters this state only after it is in the Runnable state and the scheduler assigns a
processor to the thread.
T.Y.B.Sc (Comp. Sc.) Lab – II, Sem – II [Page 12]
4. Sleeping state: - When the sleep method is invoked on a running thread, it enters the
Sleeping state.
5. Waiting State:- A thread enters the waiting state when the wait method is invoked on
the thread. When some other thread issues a notify () or notifyAll (), it returns to the
Runnable state().
6. Blocked State: - A thread can enter this state because it is waiting for resources that
are held by another thread – typically I/O resources.
7. Dead State:- This is the last state of a thread. When the thread has completed
execution that is its run () method ends, the thread is terminated. Once terminated, a
thread can’t be resumed.
Thread Creation
There are two ways to create thread in java;
1. Implement the Runnable interface (java.lang.Runnable)
2. By Extending the Thread class (java.lang.Thread)
One way to create a thread in java is to implement the Runnable Interface and then
instantiate an object of the class. We need to override the run() method into our class
which is the only method that needs to be implemented. The run() method contains the
logic of the thread.
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be
executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the
Thread constructor. The Thread object now has a Runnable object that implements the
run() method.
3. The start() method is invoked on the Thread object created in the previous step. The
start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by
throwing an uncaught exception.
Example:
class MyRunnable implements Runnable
{
public void run() //define run method
{
//thread action
}
}
...
MyRunnable r = new MyRunnable(); //create object
Thread t = new Thread(r); //create Thread object
t.start(); //execute thread
A class can also extend the Thread class to create a thread. When we extend the Thread
class, we should override the run method to specify the thread action.
Method Description
Returns the number of active threads in the current
static int activeCount()
thread's thread group.
static Thread Returns a reference to the currently executing thread
currentThread() object.
String getName() Returns this thread's name.
int getPriority() Returns this thread's priority.
ThreadGroup getThreadGroup() Returns the thread group to which this thread belongs.
void interrupt() Interrupts this thread.
boolean isAlive() Tests if this thread is alive.
boolean isDaemon() Tests if this thread is a daemon thread.
boolean isInterrupted() Tests whether this thread has been interrupted.
void join() Waits for this thread to end.
void setName(String name) Changes the name of this thread.
void setPriority(int
newPriority) Changes the priority of this thread.
void sleep(long mSec) Causes the currently executing thread to sleep.
void start() Causes this thread to begin execution.
Returns a string representation of this thread, including
String toString()
the thread's name, priority, and thread group.
Causes the currently executing thread object to
static void yield()
temporarily pause and allow other threads to execute.
Thread priorities
Every thread has a priority. A priority is an integer from 1 to 10 inclusive, where 10 is the
highest priority, referred to as the maximum priority, and 1 is the lowest priority, also
known as the minimum priority. The normal priority is 5, which is the default priority for
each thread.
To set a thread’s priority, use the setPriority() method. You can use an integer from 1 to
10, or you can use static, final variables defined in the Thread class. These variables are
i. Thread.MIN_PRIORITY: Minimum priority i.e. 1
ii. Thread.MAX_PRIORITY: Maximum priority i.e. 10
iii. Thread.NORM_PRIORITY: Default priority i.e. 5
Interthread Communication
When multiple threads are running, it becomes necessary for the threads to communicate
with each other. The methods used for inter-thread communication are join(), wait(),
notify() and notifyAll().
Lab Assignments
SET A
1. Write a program that create 2 threads – each displaying a message (Pass the
message as a parameter to the constructor). The threads should display the messages
continuously till the user presses ctrl-c. Also display the thread information as it is
running.
2. Write a java program to calculate the sum and average of an array of 100 integers
using 5 threads. Each thread calculates the sum of 20 integers. Use these values to
calculate average. [Initialize the array with numbers 1 to 100 for testing purpose. Use join
method ]
3. Define a thread called “PrintText_Thread” for printing text on command prompt for
n number of times. Create three threads and run them. Pass the text and n as
parameters to the thread constructor. Example:
i. First thread prints “I am in FY” 10 times
ii. Second thread prints “I am in SY” 20 times
iii. Third thread prints “I am in TY” 30 times
SET B
1. Write a java program to create a class called FileWatcher that can be given several
filenames that may or may not exist. The class should start a thread for each file name.
Each thread will periodically check for the existence of its file. If the file exists, the thread
will write a message to the console and then end.
2. Define a thread to move a ball inside a panel vertically. The Ball should be created
when user clicks on the Start Button. Each ball should have a different color and vertical
position (calculated randomly). Note: Suppose user has clicked buttons 5 times then five
balls should be created and move inside the panel. Ensure that ball is moving within the
panel border only.
2. Write a program to show how three thread manipulate same stack , two of them are
pushing elements on the stack, while the third one is popping elements off the
stack.
Objectives
• To communicate with a database using java.
• To execute queries on tables.
• To obtain information about the database and tables
Reading
You should read the following topics before starting this exercise:
1. The JDBC driver types
2. The design of JDBC
3. Statement, PreparedStatement, ResultSet
4. DatabaseMetaData and ResultSetMetaData
Ready Reference
JDBC Drivers
To communicate with a database, you need a database driver. There are four types of
drivers:
1. Type 1: JDBC-ODBC Bridge driver
2. Type 2: Native-API partly-Java driver:
3. Type 3: JDBC-Net pure Java driver:
4. Type 4: Native-protocol pure Java driver:
Example:
Class.forName(“org.gjt.mm.mysql.Driver”);
Establishing a connection
To establish a connection with the database, use the getConnection method of the
DriverManager class. This method returns a Connection object.
DriverManager.getConnection(“url”, “user”, “password”);
Example:
Connection conn = DriverManager.getConnection
(“jdbc:mysql://192.168.100.4/TestDB”, “scott”, “tiger”);
void close() Releases this Connection object's database and JDBC resources
immediately instead of waiting for them to be automatically released.
void commit() Makes all changes made since the previous commit/rollback permanent
and releases any database locks currently held by this Connection
object.
Statement
createStatement() Creates a Statement object for sending SQL statements to the database.
Boolean
getAutoCommit() Retrieves the current auto-commit mode for this Connection object.
Executing Queries
To execute an SQL query, you have to use one of the following classes:
• Statement
• PreparedStatement
• CallableStatement
A Statement represents a general SQL statement without parameters. The method
createStatement() creates a Statement object. A PreparedStatement represents a
precompiled SQL statement, with or without parameters. The method
prepareStatement(String sql) creates a PreparedStatement object. 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:
Examples:
ResultSet rs = stmt.executeQuery(“SELECT * FROM Student”);
int result = stmt.executeUpdate(“Update authors SET name = ‘abc’ WHERE id =
1”);
boolean ans = stmt.execute(“DROP TABLE IF EXISTS test”);
Examples:
Statement stmt = conn.prepareStatement();
ResultSet rs = stmt.executeQuery(“Select * from student”);
while(rs.next())
{
//access resultset data
}
To access these values, there are getXXX() methods where XXX is a type for example,
getString(), getInt() etc. There are two forms of the getXXX methods:
i. Using columnName: getXXX(String columnName)
ii. Using columnNumber: getXXX(int columnNumber)
Example
rs.getString(“stuname”));
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.
Example
String sql = “UPDATE authors SET name = ? WHERE id = ?”;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,’abc’); //assign abc to first placeholder
ps.setInt(2,123); //assign 123 to second placeholder
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.
Method Name Description
beforeFirst() Default position. Puts cursor before 1st row of ResultSet.
st
first() Puts cursor on 1 row of ResultSet.
last() Puts cursor on last row of ResultSet.
afterLast() Puts cursor after/beyond last row of ResultSet.
st
Puts cursor at row number position where absolute (1) is a 1 row and
absolute (int pos)
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
Inserts the contents of the insert row into the ResultSet object and into
insertRow()
the database.
refreshRow() Refreshes the current row with its most recent value in the database.
Updates the underlying database with the new contents of the current
updateRow()
row of this ResultSet object.
Retrieves the value of the designated column in the current row as a
getXXX(String
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, XXX corresponding type in the Java programming language. 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.
Method Name Description
getDatabaseProductName() Retrieves the name of this database product.
getDatabaseProductVersion() Retrieves the version number of this database
product.
getDriverName() Retrieves the name of this JDBC driver.
getDriverVersion() Retrieves the version number of this JDBC driver as
a String.
getUserName() Retrieves the user name as known to this database.
getCatalogs() Retrieves the catalog names available in this
database.
getSchemas(String catalog, String Retrieves the schema names available in this
schemaPattern)
database.
getTables(String catalog, String Retrieves a description of the tables available in the
schemaPattern, String
given catalog.
tableNamePattern, String[] types)
getPrimaryKeys(String catalog, String Retrieves a description of the given table's primary
schema, String table)
key columns.
getExportedKeys(String catalog, Retrieves a description of the foreign key columns
String schema, String table) that reference the given table's primary key
columns (the foreign keys exported by a table).
getImportedKeys(String catalog, Retrieves a description of the primary key columns
String schema, String table) that are referenced by a table's foreign key columns
(the primary keys imported by a table).
getColumns(String catalog, String Retrieves a description of table columns available in
schemaPattern, String
the specified catalog.
tableNamePattern, String
columnNamePattern)
getProcedures(String catalog, Retrieves a description of the stored procedures
String schemaPattern, available in the given catalog.
String procedureNamePattern)
getFunctions(String catalog, String Retrieves a description of the system and user
schemaPattern, String
functions available in the given catalog.
functionNamePattern)
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
The ResultSetMetaData interface provides information about the structure of a particular
ResultSet.
Method Name Description
getColumnCount() Returns the number of columns in the current ResultSet
object.
getColumnDisplaySize(int column) Gives the maximum width of the column specified by the
index parameter.
getColumnLabel(int column) Gives the suggested title for the column for use in display
and printouts.
Example:
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int noOfColumns = rsmd.getColumnCount();
System.out.println("Number of columns = " + noOfColumns);
for(int i=1; i<=noOfColumns; i++)
{
System.out.println("Column No : " + i);
System.out.println("Column Name : " + rsmd.getColumnName(i));
System.out.println("Column Type : " + rsmd.getColumnTypeName(i));
System.out.println("Column display size : " + rsmd.getColumnDisplaySize(i));
}
Self Activity
2. Sample program to perform insert and delete operations on employee table using
PreparedStatement (id, name, salary)
import java.sql.*;
import java.io.*;
class JDBCDemoOp
{
public static void main(String[] args) throws SQLException
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
Lab Assignments
SET A
1. Create a student table with fields roll number, name, percentage. Insert values in the
table. Display all the details of the student table using JDBC.
2. Write a program to display information about the database and list all the tables in
the database. (Use DatabaseMetaData).
3. Write a program to display information about all columns in the student table. (Use
ResultSetMetaData).
SET B
1. Write a menu driven program to perform the following operations on student table.
1. Insert 2. Modify 3. Delete 4. Search 5. View All 6. Exit
2. Program to Read ,Update and Delete any record from “Elements” table. The table
has following fields ( Atomic weight , Name (primary key), Chemical symbol). The input
should be provided through Command Line Arguments along with the appropriate data.
The operations are: R : Read, U: Update, D: Delete.
The syntax for Read: R
The syntax for Delete: D name
T.Y.B.Sc (Comp. Sc.) Lab – II, Sem – II [Page 25]
The syntax for Update: U name new-atomic-weight new-symbol
SET C
1. Create tables : Course (id, name, instructor) and Student (id, name). Course and
Student have a many to many relationship. Create a GUI based system for performing the
following operations on the tables:
Course: Add Course, View All students of a specific course
Student: Add Student, Delete Student, View All students, Search student
2. Design a GUI to store the details of a telephone user in a database. User has the
following attributes: User (id, name, telephone number, category, number of calls).
Category is Rural or Urban. Calculate the bill and displays the bill using the following
rule. Provide button to Search user on basis of code or name.
Category: Urban Area (the first 100 calls are free and rent is Rs. 700)
No. Of Calls Charge (per call)
> 100 and <=500 Rs. 1.30
> 500 Rs. 1.70
Category: Rural Area (the first 300 calls are free and rent is Rs. 400)
No. Of Calls Charge (per call)
> 300 and <=500 Rs. 0.80
> 500 Rs. 1.00
Objectives
• Study the Collections framework in java
• Use various collections
Reading
You should read the following topics before starting this exercise:
1. Concept of Collection
2. classes and interfaces in the Collections framework
3. Concept of iterator.
4. Creating and using collections objects.
Ready Reference
A collection is an object that represents a group of objects. A collection — sometimes
called a container — is simply an object that groups multiple elements into a single unit.
Collections are used to store, retrieve, manipulate, and communicate aggregate data.
A collections framework is a unified architecture for representing and manipulating
collections, allowing them to be manipulated independently of the details of their
representation.
List Set
SortedSet
Map
SortedMap
Interfaces:
Interface Name Description
Collection The most general collection interface type. A collection represents a
group of objects known as its elements. The Java platform doesn't
provide any direct implementations of this interface.
List Represents an ordered collection. Lists can contain duplicate
Classes:
Class name Description
AbstractCollection Implements most of the Collection interface.
AbstractList Extends AbstractCollection and implements most of the List
interface.
AbstractSequentialList Extends AbstractList for use by a collection that uses
sequential rather than random access of its elements.
LinkedList Implements a linked list by extending AbstractSequentialList.
ArrayList Implements a dynamic array by extending AbstractList.
AbstractSet Extends AbstractCollection and implements most of the Set
interface.
HashSet Extends AbstractSet for use with a hash table.
TreeSet Implements a set stored in a tree. Extends AbstractSet
boolean contains(Object Returns true if the collection contains the element passed in
element) argument.
Other operations are tasks done on groups of elements or the entire collection at once:
boolean The containsAll() method allows you to discover if the current
containsAll(Collection collection contains all the elements of another collection, a subset.
collection)
boolean addAll(Collection ensures all elements from another collection are added to the
collection) current collection, usually a union.
void removeAll(Collection method is like clear() but only removes a subset of elements
collection)
void retainAll(Collection This method is similar to the removeAll() method but does what
List interface
A list stores a sequence of elements.
Method Description
void add(int index, Inserts the specified element at the specified position in this
Object element) list (optional operation).
Boolean
Inserts all of the elements in the specified collection into this
addAll(int index,
list at the specified position (optional operation).
Collection c)
Object get(int index) Returns the element at the specified position in this list.
int indexOf(Object o) Returns the index in this list of the first occurrence of the
specified element, or -1 if this list does not contain this
element.
int Returns the index in this list of the last occurrence of the
lastIndexOf(Object o) specified element, or -1 if this list does not contain this
element.
ListIterator Returns a list iterator of the elements in this list (in proper
listIterator() sequence).
ListIterator
Returns a list iterator of the elements in this list (in proper
listIterator(int index) sequence), starting at the specified position in this list.
List
Returns a view of the portion of this list between the specified
subList(int fromIndex,
fromIndex, inclusive, and toIndex, exclusive.
int toIndex)
A set is a collection that contains no duplicate elements. It contains the methods of the
Collection interface. A SortedSet is a Set that maintains its elements in ascending order.
It adds the following methods:
Method Description
Comparator comparator() Returns the comparator associated with this
sorted set, or null if it uses its elements'
natural ordering.
Object first() Returns the first (lowest) element currently in
this sorted set.
SortedSet headset(Object Returns a view of the portion of this sorted set
toElement)
whose elements are strictly less than
toElement.
Object last() Returns the last (highest) element currently in
this sorted set.
SortedSet subset(Object Returns a view of the portion of this sorted set
fromElement, Object toElement)
whose elements range from fromElement,
Map Interface
A Map represents an object that maps keys to values. Keys have to be unique.
Method Description
void clear() Removes all mappings from this map
boolean Returns true if this map contains a mapping for
containsKey(Object key) the specified key.
boolean Returns true if this map maps one or more keys
containsValue(Object
to the specified value.
value)
Set entrySet() Returns a set view of the mappings contained in
this map.
boolean equals(Object o) Compares the specified object with this map for
equality.
Object get(Object key) Returns the value to which this map maps the
specified key.
int hashCode() Returns the hash code value for this map.
boolean isEmpty() Returns true if this map contains no key-value
mappings
Set keySet() Returns a set view of the keys contained in this
map.
Object put(Object key, Associates the specified value with the specified
Object value)
key in this map
void putAll(Map t) Copies all of the mappings from the specified
map to this map
Object remove(Object Removes the mapping for this key from this map
key) if it is present (optional operation).
int size() Returns the number of key-value mappings in this
map.
Collection values() Returns a collection view of the values contained
in this map
Implementations
List Implementations
Set Implementations
There are three general-purpose Set implementations — HashSet, TreeSet, and
LinkedHashSet.
1. TreeSet: The elements are internally stored in a search tree. It is useful when you
need to extract elements from a collection in a sorted manner.
2. HashSet: It creates a collection the uses a hash table for storage. The advantage
of HashSet is that it performs basic operations (add, remove, contains and size)
in constant time and is faster than TreeSet
3. LinkedHashSet: The only difference is that the LinkedHashSet maintains the
order of the items added to the Set, The elements are stored in a doubly linked list.
Iterator:
The Iterator interface provides methods using which we can traverse any collection. This
interface is implemented by all collection classes.
Methods:
hasNext() true if there is a next element in the collection.
next() Returns the next object.
remove() Removes the most recent element that was returned by next()
ListIterator
Forward iteration
hasNext() true if there is a next element in the collection.
next() Returns the next object.
Backward iteration
hasPrevious() true if there is a previous element.
previous() Returns the previous element.
previousIndex() Returns index of element that would be returned by subsequent call to previous().
Optional modification methods.
add(obj) Inserts obj in collection before the next element to be returned by next() and after
an element that would be returned by previous().
set() Replaces the most recent element that was returned by next or previous().
remove() Removes the most recent element that was returned by next() or previous().
• HashTable
This class implements a hashtable, which maps keys to values. It is similar to HashMap,
but is synchronized. The important methods of the HashTable class are:
Method name Description
void clear() Clears this hashtable so that it contains no keys.
boolean contains(Object
value) Tests if some key maps into the specified value in this hashtable.
boolean
Tests if the specified object is a key in this hashtable.
containsKey(Object key)
containsValue(Object value) Returns true if this Hashtable maps one or more keys to this value.
Enumeration elements() Returns an enumeration of the values in this hashtable.
Set entrySet() Returns a Set view of the entries contained in this Hashtable.
Returns the value to which the specified key is mapped in this
Object get(Object key)
hashtable.
Returns the hash code value for this Map as per the definition in the
int hashCode()
Map interface.
Boolean isEmpty() Tests if this hashtable maps no keys to values.
Enumeration keys() Returns an enumeration of the keys in this hashtable.
Set keySet() Returns a Set view of the keys contained in this Hashtable.
Object put(Object key,
Maps the specified key to the specified value in this hashtable.
Object value)
Copies all of the mappings from the specified Map to this Hashtable
void putAll(Map m) These mappings will replace any mappings that this Hashtable had
for any of the keys currently in the specified Map.
Increases the capacity of and internally reorganizes this hashtable,
void rehash()
in order to accommodate and access its entries more efficiently.
Object remove(Object key) Removes the key (and its corresponding value) from this hashtable.
int size() Returns the number of keys in this hashtable.
Collection values() Returns a Collection view of the values contained in this Hashtable.
Self Activity
1. Sample program
/* Program to demonstrate ArrayList and LinkedList */
import java.util.*;
class ArrayLinkedListDemo {
public static void main(String args[])
{
ArrayList al = new ArrayList();
LinkedList l1 = new LinkedList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("A");
al.add("B");
al.add("C");
al.add(2, "AA");
System.out.println("Contents of al: " + al);
al.remove("B");
al.remove(1);
System.out.println("Contents of al: " + al);
l1.add("A");
l1.add("B");
l1.add(new Integer(10));
System.out.println("The contents of list is " + l1);
l1.addFirst(“AA”);
l1.addLast("c");
l1.add(2,"D");
l1.add(1,"E");
l1.remove(3);
System.out.println("The contents of list is " + l1);
}
}
2. Sample program
/* Program to demonstrate iterator */
import java.util.*;
public class IteratorDemo
{
public static void main(String[] args)
{
ArrayList a1 = new ArrayList();
3. Sample program
/* Program to demonstrate HashTable*/
import java.util.*;
public class HashtableDemo
{
public static void main(String[] args)
{
Hashtable hashtable = new Hashtable();
String str, name = null;
hashtable.put( "A", 75.2 ); // adding value into hashtable
hashtable.put( "B", 65.9 );
hashtable.put( "C", 95.1 );
hashtable.put( "D", 85.7 );
Lab Assignments
SET A
1. 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).
2. Construct a linked List containing names of colors: red, blue, yellow and orange.
Then extend your program to do the following:
i. Display the contents of the List using an Iterator;
ii. Display the contents of the List in reverse order using a ListIterator;
iii. Create another list containing pink and green. Insert the elements of this list
between blue and yellow.
3. Create a Hash table containing student name and percentage. Display the details of
the hash table. Also search for a specific student and display percentage of that student.
SET B
2. Create two singly linked lists for string data (Do not allow duplicate elements in one
list). Perform
a. Union
b. Intersection
c. Combining corresponding elements of the lists into a new list (only if they
are of the same size)
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 the list:
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 the program.
Objectives
• To understand server-side programming
• Defining and executing servlets
Reading
You should read the following topics before starting this exercise:
1. Concept of servlet
2. Difference between applet and servlet
3. Introduction to Servlet (HTTP Servlet)
4. Lifecycle of a Servlet
5. Handling Get and Post requests (HTTP)
6. Data Handling using Servlet
7. Creating Cookies
8. Session Tracking using HTTP Servlet
Ready Reference
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.
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
Interface Description
The HttpServletRequest interface extends the ServletRequest interface and
HttpServletRequest
adds methods for accessing the details of an HTTP request.
The HttpServletResponse interface extends the ServletResponse interface
HttpServletResponse
and adds constants and methods for returning HTTP-specific responses.
This interface is implemented by servlets to enable them to support browser-
server sessions that span multiple HTTP request-response pairs. Since
HttpSession 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.
This interface is used to represent a collection of HttpSession objects that are
HttpSessionContext
associated with session IDs.
Class Description
Used to create HTTP servlets. The HttpServlet class extends the
HttpServlet
GenericServlet class.
This class represents an HTTP cookie. Cookies are used to maintain session
state over multiple HTTP requests. They are named data values that are
Cookie 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.
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
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
ServletRequest methods
String Obtains the value of a parameter sent to the servlet as part
getParameter(String name of a get or post request.
) The name argument represents the parameter name.
Enumeration Returns the names of all the parameters sent to the servlet
getParameterNames() as part of a post request.
String[]getParameterValu For a parameter with multiple values, this method Returns
es(String name) an array of strings containing the values for a specified
servlet parameter.
String getProtocol() Returns the name and version of the protocol the request
uses in the form protocol/majorVersion.minorVersion, for
example, HTTP/1.
String getRemoteAddr() Returns the Internet Protocol (IP) address of the client that
sent the request.
String getRemoteHost() Returns the fully qualified name of the client that sent the
request.
String getServerName() Returns the host name of the server that received the
request.
int getServerPort() Returns the port number on which this request was
received.
HttpServletRequest methods
String getServletPath() Returns the part of this request's URL that calls the servlet.
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 getPathInfo() Returns any extra path information associated with the URL
the client sent when it made this request.
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.
ServletResponse methods
ServletOutputStream Obtains a byte-based output stream for sending binary data
getOutputStream() to the client.
PrintWriter getWriter() Obtains a character-based output stream for sending text
data (usually HTML formatted text) to the client.
void Specifies the content type of the response to the browser.
setContentType(String The content type is also known as MIME (Multipurpose
type) Internet Mail Extension) type of the data. For examples,
"text/html" , "image/gif" etc.
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
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>SimpleServlet</servlet-name>
<servlet-class>SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleServlet</servlet-name>
<url-pattern>/SimpleServlet</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/FirstServlet.
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.
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.
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.
Returns an Enumeration of String objects
Enumeration
getAttributeNames() containing the names of all the objects bound to this
session.
Returns the time when this session was created,
long getCreationTime() measured in milliseconds since midnight January 1, 1970
GMT.
Returns the last time the client sent a request associated
with this session, as the number of milliseconds since
long getLastAccessedTime()
midnight January 1, 1970 GMT, and marked by the time
the container received the request.
Returns the maximum time interval, in seconds, that the
int
servlet container will keep this session open between
getMaxInactiveInterval()
client accesses.
void Removes the object bound with the specified name from
RemoveAttribute(String
this session.
name)
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)
Invalidates this session then unbinds any objects bound
void invalidate()
to it.
Boolean isNew() Returns true if it is a new session.
Returns a string containing the unique identifier
String getId()
assigned to this session.
Self Activity
1. Sample program
/* Program for simple servlet*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
After saving this servlet, compile it with the Java compiler as: javac SimpleServlet.java.
Run the servlet using http://server-ip:8080/SimpleServlet
int no1=Integer.parseInt(req.getParameter("No1"));
int no2=Integer.parseInt(req.getParameter("No2"));
int total=no1+no2;
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<h1> ans </h1> <h3>"+total+"</h3>");
pw.close();
}
}
cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/root","root","");
}
catch(ClassNotFoundException ce){}
catch(SQLException se){}
while(rs.next())
{
pw.print("<table border=1>");
pw.print("<tr>");
pw.print("<td>" + rs.getInt(1) + "</td>");
pw.print("<td>" + rs.getString(2) + "</td>");
pw.print("</tr>");
pw.print("</table>");
}
}
catch(Exception se){}
pw.close();
}
}
Run this program as http://server-ip:8080/ServJdbc
Cookie [] c=req.getCookies();
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
for(int i=0;i<c.length;i++)
pw.println("Cookie Name"+c[i].getName());
pw.close();
}
}
Run this program as http://server-ip:8080/AddCookie
Run this program as http://server-ip:8080/GetCookie
5. Sample program for sessions
String result1="success";
String result2="failure";
public void doGet(HttpServletRequest req,HttpServletResponse
res)
throws ServletException, IOException{
HttpSession hs=req.getSession(true);
String lname=req.getParameter("txt1");
String pwd=req.getParameter("txt2");
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
if((lname.equals("BCS"))&&(pwd.equals("CS")))
T.Y.B.Sc (Comp. Sc.) Lab – II, Sem – II [Page 45]
{
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();
}
}
<!—HTML File for NewInfo.html -->
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="http://localhost:8080/SessionInfo">
<input type="Submit" value=”Read Session Value”>
</form>
</body>
</html>
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.
Lab Assignments
SET A
1. Write a servlet which accepts the user name from an HTML page and returns a
message which greets the user.
T.Y.B.Sc (Comp. Sc.) Lab – II, Sem – II [Page 46]
2. Design a servlet that provides information about a HTTP request from a client, such
as IP address and browser type. The servlet also provides information about the server on
which the servlet is running, such as the operating system type, and the names of
currently loaded servlets.
3. Write a servlet which counts how many times a user has visited a web page. If the
user is visiting the page for the first time, display a welcome message. If the user is re-
visiting the page, display the number of times visited. (Use cookies)
4. Create an HTML page with text boxes for login id and password. Pass these to the
servlet. If the login name = “BSc” and password = “CS”, display welcome.html else
display an error.html (hint: Return the <a href=http://server-
ip:8080/Welcome.html> tag to the client machine)
SET C
2. Write a Java program to develop a GUI based shopping mall which allows the
user to select items and specify shopping quantity. Design separate HTML pages;
each containing 10 items. The total of each page should be stored using sessions. At
the end, the final bill should be presented to the user. Use Use a database to store
item details and a transaction table to store selected items and date. Provide necessary
validations for input.
Format of the bill.
Sr. No. Particulars Unit Rate Quantity Amount
1 Item1 Rs. ‘x’ Unit rate * quantity
…. ….. ….. ….. ……
N Itemn Rs. ‘x’ Unit rate * quantity
Total Amount ∑ (Amount)
Objectives
• To demonstrate the use of JSP
Reading
You should read the following topics before starting this exercise
1. Concept of Servlets.
2. JSP life-cycle.
3. JSP Directives
4. Scripting elements.
5. Actions in JSP.
Ready Reference
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 can not 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.
Causes the JSP container to perform a translation-time insertion of another
include resource's content. The file included can be either static ( HTML file) or dynamic (i.e.,
another tag file)
Allows programmers to use new tags from tag libraries that encapsulate more
taglib
complex functionality and simplify the coding of a JSP.
Syntax:-
<%@ 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
<%! Java declaration statements %>
Example,
<%! private int count = 0; %>
<%! int i = 0; %>
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
<%= expression %>
Example,
Your name is <%= request.getParameter("name") %>
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
<% statements %>
Example
<%
String name = request.getParameter("userName");
out.println(“Hello “ + name);
%>
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/Filename.jsp
Self Activity
Lab Assignments
SET A
1. Create a JSP page to accept a number from the user and display it in words:
Example: 123 – One Two Three. The output should be in red color.
2. Create a JSP page which accepts a number the user, and on submit button, calculates
the factorial of the number and displays it.
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. Example: User name : ABC
Good morning ABC ( if it is morning); Good Afternoon ABC (if it is afternoon);
Good Evening ABC (if it is evening)
2. Create a JSP page which accepts user name & password , check whether it is correct.
If correct, display Welcome message else displays an error message.
SET C
1. Create a JSP page which accepts user name & password , check whether it is correct or not.
Display Welcome message if correct else tells you fill the details once again. (Use a database)
Objectives
• Introduction to the java.net package
• Connection oriented transmission – Stream Socket Class
Reading
You should read the following topics before starting this exercise
1. Networking Basics
2. The java.net package – InetAddress class, URL class, URLConnection class
3. Connection oriented communication –ServerSocket class, Socket class
Ready Reference
Introduction
One of the important features of Java is its networking support. Java has classes that
range from low-level TCP/IP connections to ones that provide instant access to resources
on the World Wide Web. Java supports fundamental networking capabilities through
java.net package.
Networking Basics
Protocol
A protocol is a set of rules and standards for communication. A protocol specifies the
format of data being sent over the Internet, along with how and when it is sent. Three
important protocols used in the Internet are:
1. IP (Internet Protocol): is a network layer protocol that breaks data into small packets
and routes them using IP addresses.
2. TCP (Transmission Control Protocol): This protocol is used for connection-oriented
communication between two applications on two different machines. It is most reliable
and implements a connection as a stream of bytes from source to destination.
3. UDP (User Datagram Protocol): It is a connection less protocol and used typically for
request and reply services. It is less reliable but faster than TCP.
Addressing
1. MAC Address: Each machine is uniquely identified by a physical address, address of
the network interface card. It is 48-bit address represented as 12 hexadecimal
characters:
For Example: 00:09:5B:EC:EE:F2
2. IP Address: It is used to uniquely identify a network and a machine in the network. It
is referred as global addressing scheme. Also called as logical address. Currently used
type of IP addresses is: Ipv4 – 32-bit address and Ipv6 – 128-bit address.
For Example:
Ipv4 – 192.168.16.1 Ipv6 – 0001:0BA0:01E0:D001:0000:0000:D0F0:0010
3. Port Address: It is the address used in the network to identify the application on the
network.
URL
A URL (Uniform Resource Locator) is a unique identifier for any resource located on the
Internet. The syntax for URL is given as:
<protocol>://<hostname>[:<port>][/<pathname>][/<filename>[#<section>]]
Sockets
A socket represents the end-point of the network communication. It provides a simple
read/write interface and hides the implementation details network and transport layer
protocols. It is used to indicate one of the two end-points of a communication link
between two processes. When client wishes to make connection to a server, it will create
a socket at its end of the communication link.
The socket concept was developed in the first networked version of UNIX developed at
the University of California at Berkeley. So sockets are also known as Berkeley Sockets.
Ports
A port number identifies a specific application running in the machine. A port number is a
number in the range 1-65535.
Reserved Ports: TCP/IP protocol reserves port number in the range 1-1023 for the use of
specified standard services, often referred to as “well-known” services.
Client-Server
It is a common term related to networking. A server is a machine that has some resource
that can be shared. A server may also be a proxy server. Proxy server is a machine that
acts as an intermediate between the client and the actual server. It performs a task like
authentications, filtering and buffering of data etc. it communicates with the server on
behalf of the client.
A client is any machine that wants to use the services of a particular server. The server is
a permanently available resource, while the client is free to disconnect after it’s job is
done.
URL Class
As the name suggests, it provides a uniform way to locate resources on the web. Every
browser uses them to identify information on the web. The URL class provides a simple
API to access information across net using URLs.
The class has the following constructors:
1. URL(String url_str): Creates a URL object based on the string parameter. If the
URL cannot be correctly parsed, a MalformedURLException will be thrown.
2. URL(String protocol, String host, String path): Creates a URL object with the
specified protocol, host and path.
3. URL(String protocol, String host, int port, String path): Creates a URL object
with the specified protocol, host, port and file path.
4. URL(URL urlObj, String urlSpecifier): Allows you to use an existing URL as a
reference context and then create a new URL from that context.
URLConnection Class
This class is useful to actually connect to a website or resource on a network and get all
the details of the website. Using the openConnection() method, we should establish a
contact with the site on Internet. Method returns URLConnection object. Then using
T.Y.B.Sc (Comp. Sc.) Lab – II, Sem – II [Page 55]
URLConnection class methods, we can display all the details of the website and also
content of the webpage whose name is given in URL.
Socket Class
This class is used to represents a TCP client socket, which connects to a server socket and
initiate protocol exchanges. The various constructors of this class are:
Self Activity
Lab Assignments
SET A
1. Write a client-server program which displays the server machine’s date and time on
the client machine.
SET B
1. Write a program to accept a list of file names on the client machine and check how
many exist on the server. Display appropriate messages on the client side.
2. Write a server program which echoes messages sent by the client. The process
continues till the client types “END”.
SET C
1. Write a program for a simple GUI based chat application between client and server.
2. Write a program for an online test. The server randomly selects 10 questions from a
database and sends them to the client one by one. Each question is sent after the answer to
the previous question is received. The server sends the score at the end of the exam.