Java Manual
Java Manual
(Computer Science)
Semester II
Name ________________________________ Roll No. _______
EDITED BY :
Ms. Poonam Ponde
INPUTS GIVEN BY :
Mr. Jeevan Tonde
Ms. Rasika Rahalkar
PREVIOUS EDITION AUTHORS:
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 Database programming
3 Servlets
5 Multithreading
6 Networking
Total: _____ / 30
Signature of Incharge:
Examiner I :
Examiner II :
Date:
Assignment 1: Collections
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
elements.
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
collection) might be perceived as the opposite: it removes from the current
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,
inclusive, to toElement, exclusive.
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
value) to the specified 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 [Link].*;
class ArrayLinkedListDemo {
public static void main(String args[])
{
ArrayList al = new ArrayList();
LinkedList l1 = new LinkedList();
[Link]("Initial size of al: " + [Link]());
// add elements to the array list
[Link]("A");
[Link]("B");
[Link]("C");
[Link](2, "AA");
[Link]("Contents of al: " + al);
[Link]("B");
[Link](1);
[Link]("Contents of al: " + al);
[Link]("A");
[Link]("B");
[Link](new Integer(10));
[Link]("The contents of list is " + l1);
[Link](“AA”);
[Link]("c");
[Link](2,"D");
[Link](1,"E");
[Link](3);
[Link]("The contents of list is " + l1);
}
}
2. Sample program
/* Program to demonstrate iterator */
import [Link].*;
public class IteratorDemo
{
public static void main(String[] args)
{
ArrayList a1 = new ArrayList();
[Link]("C"); [Link]("A"); [Link]("E"); [Link]("B"); [Link]("D"); [Link]("F");
Iterator itr = [Link](); //obtain iterator
while([Link]())
{
String elt = (String)[Link]();
[Link]("Element = " + elt);
}
LinkedList l = new LinkedList();
[Link]("A"); [Link]("B"); [Link]("C"); [Link]("D");
ListIterator litr = [Link]();
while([Link]())
{
String elt = (String)[Link]();
[Link](elt);
}
[Link]("Traversing Backwards : ");
while([Link]())
[Link]([Link]());
}
}
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). Search for an particular element using predefined search method in the
Collection framework.
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
1. Create a java application to store city names and their STD codes using an appropriate
collection. The GUI ahould allow the following operations:
i. Add a new city and its code (No duplicates)
ii. Remove a city from the collection
iii. Search for a cityname and display the code
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:
[Link](“[Link]”);
Establishing a connection
To establish a connection with the database, use the getConnection method of the
DriverManager class. This method returns a Connection object.
[Link](“url”, “user”, “password”);
Example:
Connection conn = [Link]
(“jdbc:postgresql://[Link]/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.
Statement
createStatement(int Creates a Statement object that will generate ResultSet objects
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:
execute: Use this method if the query could return one or more ResultSet
objects.
executeQuery: Returns one ResultSet object.
[Link] (Comp. Sc.) Lab – II, Sem – II [Page 12]
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:
ResultSet rs = [Link](“SELECT * FROM Student”);
int result = [Link](“Update authors SET name = ‘abc’ WHERE id =
1”);
boolean ans = [Link](“DROP TABLE IF EXISTS test”);
Examples:
Statement stmt = [Link]();
ResultSet rs = [Link](“Select * from student”);
while([Link]())
{
//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
[Link](“stuname”));
[Link](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 = [Link](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 = [Link](sql);
[Link](1,’abc’); //assign abc to first placeholder
[Link](2,123); //assign 123 to second placeholder
Example:
Statement stmt = [Link] (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
st
beforeFirst() Default position. Puts cursor before 1 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.
Puts cursor at row number position where absolute (1) is a 1st 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.
updateXXX(String Updates the value of the designated column in the current row as a
columnName, XXX corresponding type in the Java programming language. XXX
value) represents a type: Int, String, Float, Short, Long, Time etc.
Example:
DatabaseMetaData dbmd = [Link]();
ResultSet rs = [Link](null, null, null,new String[] {"TABLE"});
while ([Link]())
[Link]( [Link]("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.
getColumnName(int column) Gives the column name associated with the column index.
getColumnTypeName(int column) Gives the designated column's SQL type.
isReadOnly(int column) Indicates whether the designated column is read-only.
isWritable(int column) Indicates whether you can write to the designated column.
Example:
ResultSet rs = [Link](query);
ResultSetMetaData rsmd = [Link]();
int noOfColumns = [Link]();
[Link]("Number of columns = " + noOfColumns);
for(int i=1; i<=noOfColumns; i++)
{
[Link]("Column No : " + i);
[Link]("Column Name : " + [Link](i));
[Link]("Column Type : " + [Link](i));
[Link]("Column display size : " + [Link](i));
}
Self Activity
2. Sample program to perform insert and delete operations on employee table using
PreparedStatement (id, name, salary)
import [Link].*;
import [Link].*;
class JDBCDemoOp
{
public static void main(String[] args) throws SQLException
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
PreparedStatement ps1 = null, ps2=null;
int id, sal;
String name;
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("[Link]");
conn =
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 in a tabular format on the screen (using
swing).
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 (Command line interface) to perform the following
operations on student table.
1. Insert 2. Modify 3. Delete 4. Search 5. View All 6. Exit
2. Design a following Phone Book Application Screen using swing & write a code for
various operations like Delete, Update, Next, Previous. Raise an appropriate
exception if invalid data is entered like name left blank and negative phone Number.
NAME
ADDRESS
PHONE
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
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 [Link] and [Link] 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
[Link] Several versions are available: Linux users should
download the rpm of Tomcat.
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 [Link] package, and
IOException, an exception in the [Link] 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 [Link].*;
import [Link].* ;
import [Link].*;
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 [Link](String) or getParameterValues(String) to obtain
parameters
PrintWriter out = [Link]();//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/[Link], 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.
String Sets the length of the content body in the response In
setContentLength(int HTTP servlets, this method sets the HTTP Content-Length
len) header.
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 [Link] 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 [Link] file. Restart the Tomcat service and run the servlet
by loading its address with a web browser as: [Link]
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.
[Link] 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.
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 [Link].*;
import [Link].*;
import [Link].*;
public class SimpleServlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse rs)
throws ServletException, IOException
{
[Link]("text/html");
PrintWriter pw=[Link]();
[Link]("<html>");
[Link]("<body>");
[Link]("<B>Hello, Welcome to Java Servlet’s");
After saving this servlet, compile it with the Java compiler as: javac [Link].
Run the servlet using [Link]
int no1=[Link]([Link]("No1"));
int no2=[Link]([Link]("No2"));
int total=no1+no2;
[Link]("text/html");
PrintWriter pw=[Link]();
[Link]("<h1> ans </h1> <h3>"+total+"</h3>");
[Link]();
}
}
String qry;
ResultSet rs;
Statement st;
[Link] (Comp. Sc.) Lab – II, Sem – II [Page 26]
Connection cn;
String ename,sal;
cn=[Link]("jdbc:mysql://localhost:3306/root","root","");
}
catch(ClassNotFoundException ce){}
catch(SQLException se){}
while([Link]())
{
[Link]("<table border=1>");
[Link]("<tr>");
[Link]("<td>" + [Link](1) + "</td>");
[Link]("<td>" + [Link](2) + "</td>");
[Link]("</tr>");
[Link]("</table>");
}
}
catch(Exception se){}
[Link]();
}
}
Run this program as [Link]
Cookie [] c=[Link]();
[Link]("text/html");
PrintWriter pw=[Link]();
for(int i=0;i<[Link];i++)
[Link]("Cookie Name"+c[i].getName());
[Link]();
}
}
Run this program as [Link]
Run this program as [Link]
5. Sample program for sessions
String result1="success";
String result2="failure";
public void doGet(HttpServletRequest req,HttpServletResponse
res)
throws ServletException, IOException{
HttpSession hs=[Link](true);
String lname=[Link]("txt1");
String pwd=[Link]("txt2");
[Link]("text/html");
PrintWriter pw=[Link]();
if(([Link]("BCS"))&&([Link]("CS")))
{
[Link]("<a href=[Link]
Login Success</a>");
[Link]("loginID",result1);
[Link] (Comp. Sc.) Lab – II, Sem – II [Page 28]
}
else
{
[Link]("<a href=[Link]
Kick Out</a>");
[Link]("loginID",result2);
}
[Link]();
}
}
<!—HTML File for [Link] -->
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="[Link]
<input type="Submit" value=”Read Session Value”>
</form>
</body>
</html>
HttpSession hs=[Link](true);
readloginid=[Link]();
[Link]("text/html");
PrintWriter pw=[Link]();
if([Link]("loginID").equals("success"))
[Link]("Your Session ID " + readloginid);
else
[Link]("<h1>Session Expired </h1>");
[Link]();
}
}
Create an html file for login and password and use [Link] in
the Form Action tag.
Lab Assignments
SET A
1. 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. Design an HTML page which passes student roll number to a search servlet. The
servlet searches for the roll number in a database (student table) and returns student
details if found or error message otherwise.
SET B
1. Write a program to create a shopping mall. User must be allowed to do purchase from
two pages. Each page should have a page total. The third page should display a bill,
which consists of a page total of what ever the purchase has been done and print the
total. (Use HttpSession)
SET C
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 resource's content. The file
include
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 complex functionality and
taglib
simplify the coding of a JSP.
Syntax:-
<%@ page
[ language="java" ]
[ extends="[Link]" ]
[ import="{[Link] | 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 <%= [Link]("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 = [Link]("userName");
[Link](“Hello “ + name);
%>
Implicit
Description
object
applicat A [Link] object that represents the container in which the JSP executes.
ion It allows sharing information between the jsp page's servlet and any web components with in
To run JSP files: all JSP code should be copied (Deployed) into webapps folder in the
tomcat server. To execute the file, type: [Link]
Self Activity
Lab Assignments
SET A
1. Write a Program to make use of following JSP implicit objects:
i. out: To display current Date and Time.
ii. request: To get header information.
iii. response: To Add Cookie
iv. config: get the parameters value defined in <init-param>
v. application: get the parameter value defined in <context-param>
vi. session: Display Current Session ID
vii. pageContext: To set and get the attributes.
viii. page: get the name of Generated Servlet
2. Create a JSP page which will accept the file extension and display all files in the
current directory having that extension. Each filename should appear as a hyperlink on
screen.
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
Output : Good morning ABC / Good Afternoon ABC/ Good Evening ABC
2. Create a JSP page for an online multiple choice test. The questions are randomly
selected from a database and displayed on the screen. The choices are displayed using
radio buttons. When the user clicks on next, the next question is displayed. When the user
clicks on submit, display the total score on the screen.
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.
[Link] (Comp. Sc.) Lab – II, Sem – II [Page 35]
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 ([Link])
2. By Extending the Thread class ([Link])
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
[Link](); //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 1000 integers
(generated randomly) using 10 threads. Each thread calculates the sum of 100 integers.
Use these values to calculate average. [Use join method ]
1. 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 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.
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.
SET C
3. 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.
Reading
You should read the following topics before starting this exercise
1. Networking Basics
2. The [Link] 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
[Link] 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 – [Link] 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
[Link] (Comp. Sc.) Lab – II, Sem – II [Page 43]
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.