0% found this document useful (0 votes)
20 views157 pages

ADJ Manual

The document is a laboratory manual for the Advance Java Programming course at Government Polytechnic, Nashik, outlining the vision and mission of the institution and the Information Technology department. It details the teaching and examination scheme, course objectives, and outcomes, as well as practical assignments and rubrics for assessment. The manual emphasizes skill development in Java programming, including GUI design, network applications, and database operations.

Uploaded by

v11966852
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views157 pages

ADJ Manual

The document is a laboratory manual for the Advance Java Programming course at Government Polytechnic, Nashik, outlining the vision and mission of the institution and the Information Technology department. It details the teaching and examination scheme, course objectives, and outcomes, as well as practical assignments and rubrics for assessment. The manual emphasizes skill development in Java programming, including GUI design, network applications, and database operations.

Uploaded by

v11966852
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 157

A LABORATORY MANUAL FOR

ADVANCE JAVA
PROGRAMMING (ADJ) (6544)

EVEN SEMESTER- VI
DIPLOMA PROGRAMME IN
INFORMATION TECHNOLOGY

GOVERNMENT POLYTECHNIC, NASHIK


(AN AUTONOMOUS INSTITUTE OF GOVT. OF
MAHARASHTRA)
GOVERNMENT POLYTECHNIC NASHIK
(An Academic Autonomous Institute of Govt. of Maharashtra)

VISION:
To be a premier technical training and development institute catering to the skill and
professional development in multi-domain for successful employment/self-employment by
offering certified and accredited NSQF compliant programmes. The institute shall be the
center for excellence in skill development and community development through different
training programmes, business incubation and entrepreneurship development.

MISSION:
The Government Polytechnic Nashik, an autonomous institute of Government of
Maharashtra has the mission to provide education for skill development, engineering
diploma and continuing education programmes for enhancement of employability skills of
the aspirants in the job/self-employment through continually developing quality learning
systems. The institute aims at holistic and student centric education in collaboration with
business, industry and having practice based education.
GOVERNMENT POLYTECHNIC NASHIK
(An Academic Autonomous Institute of Govt. of Maharashtra)

Vision of Information Technology department


To emerge as a center of excellence in the domain of Information technology and be the player in Digital
India, having capability of producing technically proficient manpower which is competent of making
significant contributions as entrepreneurs or professionals to the industry and society.

Mission of Department of Information Technology is committed


Department of Information Technology is committed to,

M1. To impart quality engineering education and enhance problem solving skills.
M2. To develop innovative skills.
M3. To encourage students for employable, entrepreneurial and life-long learning skills.
M4. To mold students for integrity and ethics.
M5. To provide leadership with social sensitivity for the betterment of the society, humanity
and country as a whole.
PROGRAMME: Diploma Programme in Information Technology (IF) / Computer
Technology(CM)
COURSE: Advance Java Programming (ADJ) COURSE CODE: 6544

TEACHING AND EXAMINATION SCHEME:


Teaching Scheme Examination Scheme
Hrs/week Marks
TH
Credits
TH TU PR Paper Hrs. TH TEST TH+TEST PR OR TW TOTAL
Max. 80 20 100 -- 25 25 150
03 -- 04 07 03
Min. 32 -- 40 -- 10 10 --

1.0 RATIONALE:

In the current era of networking, online transaction processing and managing the
dataflow over network becomes an important issue. This course is essential for providing
knowledge and hands on experience over the issues of managing data on Web,
developing powerful GUI based friendly user interface, server side programming and
developing applications for communication over network using object oriented
fundamentals. Advanced Java enhances the Java programming. After learning this
course, the student will be able to develop standalone/network/web based software
projects required in curriculum as well as industry.

2.0 COURSE OBJECTIVES:


The student will be able to,

1. Develop applets, Frames using awt and swing components.


2. Develop network based applications.
3. Perform CURD operation on database.
4. Develop server side programs.
5. Develop small desktop or web applications.

3.0 COURSE OUTCOMES:


The course content should be taught and learning imparted in such a manner that
students are able to acquire required learning outcome in cognitive, psychomotor and
affective domain to demonstrate following course outcomes:
1. Design and Develop applets, Frames using awt and swing components.
2. Develop network based applications.
3. Use CURD operation in standalone and web applications.
4. Use server side programs for developing web applications,
5. Develop small desktop or web applications.
GOVERNMENT POYTECHNIC NASHIK
(An Academic Autonomous Institute of Govt. of Maharashtra)

CERTIFICATE

This is to certify that Mr./Ms.

Roll No. of Sixth Semester of diploma in

Engineering has completed the term work in subject Advance Java Programming (ADJ)
(6544) for academic year 20 to 20 as prescribed in curriculum.

Date: Exam Seat No:

Sign:

Name of Student:

Subject Teacher Head of Department Principal


GOVERNMENT POLYTECHNIC NASHIK
(An Academically autonomous Institute of Government of Maharashtra)
Diploma Programme in Information Technology / Rubrics for Laboratory Task Assessment (TW)

Academic Year:- 2022-23


Course Name and Code :- ADJ (6544)
Name of Student:-
Roll No.:-
Year:- III Term:-EVEN
Domain Criteria Total Experiment Number
Weightage(P/S/ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
P S D P P P P P P P P P P P P P P P
Cognitive Understand basic concept of advance java
Domain 2 4 2
Identify problem and find solution
2 4 2
Understand different type of classes,
2 4 2
packages and their methods
Average 6/12/6
Ability to implement Successful solution for
3 0 3
given problem
Ability to develop good solution of problem 3 0 2
Psychomotor
Ability to apply appropriate solution to
Domain
appropriate applicaton 4 0 3

Average 10/0/08
Affective Follow safety measures while handling 2 3 2
Domain Punctuality and working in team 1 2 2
Environmental Awareness 1 3 2
Average 4/8/6
Total out of 20

Type of Experiment/ Domain Congnitiv Psychom Affective


P- Performance Type 30 50 20
S- Study Type 60 0 40
D- Demonstration Type 30 40 30 Course HOD Student Sign
INDEX

Academic Year: Name of Faculty:


Programme: _ Course & Code: _
Name of Student:

Sr. Title of Practical Date Marks Sign of


No Performance Completion Lecturer
Write a program to design a form
1 using the components textfield,
label, checkbox, button, list.
Write a program to design a
2 calculator using Java components
and handle various events related to
each component and apply proper
layout to it.
Write a program to create a menu bar
3 with various menu items and sub
menu Items. Also create a checkable
menu item. On clicking a menu Item
display a suitable Dialog box.
Write a program using swing to
4 display a JcomboBox in an applet
with the items - cricket, football,
hockey, tennis
Write a program to create :
5 .-Jtree
-JTable
Write a program making use of
6 Adapter dass
Write a program to retrieve
7 hostname-using methods in Inet
Address class,
Write a program to demonstrates
8 TCP/IP based communication
between Client and server.
Write an Application program /Applet
9 to make connectivity with database
using JDBC , API
Write an application program/Applet
10 to sent queries through JDBC bridge
& handle result.
Write a servlet for demonstrating the
11 generic servlet class.

Create a web form which processes


12 servlet and demonstrates use of
cookies and sessions
Develop a simple JSP program for
13 user login form.

Develop a simple JSP program to


14 display the grade of a student by
accepting the marks of five courses.
Mini Project
15
Total
Average

Name & Signature of Student Signature of Faculty


Advance Java – 6544 Practical No :

Practical No. 01
Title : Write a program to design a form using the components textfield, label, checkbox, button,
list.

Theory:

AWT :

• AWT stands for Abstract window toolkit is an Application programming interface (API) for
creating Graphical User Interface (GUI) in Java.
• It allows Java programmers to develop window-based applications
• AWT provides various components like button, label, checkbox, etc. used as objects inside
a Java Program.
• AWT components use the resources of the operating system, i.e., they are platform- dependent,
which means, component's view can be changed according to the view of the operating system.
• The classes for AWT are provided by the Java.awt package for various AWT components

• The following image represents the hierarchy for Java AWT:


Advance Java – 6544 Practical No :

1. Component Class:
The component class stands at the top of the AWT hierarchy, is an abstract class that
contains all the properties of the component visible on the screen.
The Component object contains information about the currently selected foreground and
background color. It also has information about the currently selected text color.

2. Container:
The container is a component that contains other components like button, textfield, label, etc.
However, it is a subclass of the Component class.

3. Panel:
The panel can be defined as a container that can be used to hold other components. However,
it doesn't contain the title bar, menu bar, or border.

4. Window:
A window can be defined as a container that doesn't contain any border or menu bar. It creates
a top-level view. However, we must have a frame, dialog, or another window for creating a
window.

5. Frame:
The frame is a subclass of Window. It can be defined as a container with components like
button, textfield, label, etc. In other words, AWT applications are mostly created using frame
container.

Controls of AWT:

1. Button:

The button class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed.

Class constructors:

S.N. Constructor & Description

1
Button()
Constructs a button with an empty string for its label.

2
Button(String text)
Constructs a new button with specified label.
Advance Java – 6544 Practical No :

Class methods:
S.N. Method & Description

1
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this button.

2
void addNotify()
Creates the peer of the button.

3
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Button.

4
String getActionCommand()
Returns the command name of the action event fired by this button.

5
ActionListener[] getActionListeners()
Returns an array of all the action listeners registered on this button.

6
String getLabel()
Gets the label of this button.

7
<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Button.

8
protected String paramString()
Returns a string representing the state of this Button.

9
protected void processActionEvent(ActionEvent e)
Processes action events occurring on this button by dispatching them to any registered
ActionListener objects.
Advance Java – 6544 Practical No :

2. Label:
Label is a passive control because it does not create any event when accessed by the user. The
label control is an object of Label.
A label displays a single line of read-only text. However the text can be changed by the
application programmer but cannot be changed by the end user in any way.

Field:
Following are the fields for java.awt.Component class:
• static int CENTER -- Indicates that the label should be centered.
• static int LEFT -- Indicates that the label should be left justified.
• static int RIGHT -- Indicates that the label should be right justified.

Class constructors
S.N. Constructor & Description

1
Label()
Constructs an empty label.

2
Label(String text)
Constructs a new label with the specified string of text, left justified.

3
Label(String text, int alignment)
Constructs a new label that presents the specified string of text with the specified
alignment.

Class methods:
S.N. Method & Description

1
void addNotify()
Creates the peer for this label.

2
AccessibleContext getAccessibleContext()
Advance Java – 6544 Practical No :

Gets the AccessibleContext associated with this Label.

3
int getAlignment()
Gets the current alignment of this label.

4
String getText()
Gets the text of this label.

5
protected String paramString()
Returns a string representing the state of this Label.

6
void setAlignment(int alignment)
Sets the alignment for this label to the specified alignment.

7
void setText(String text)
Sets the text for this label to the specified text.

3. Checkbox:
Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox
representing what the checkbox does.The state of a checkbox can be changed by clicking on it.

Class constructors:
S.N. Constructor & Description

1
Checkbox()
Creates a check box with an empty string for its label.

2
Checkbox(String label)
Creates a check box with the specified label.
Advance Java – 6544 Practical No :

3
Checkbox(String label, boolean state)
Creates a check box with the specified label and sets the specified state.

4
Checkbox(String label, boolean state, CheckboxGroup group)
Constructs a Checkbox with the specified label, set to the specified state, and in the specified
check box group.

5
Checkbox(String label, CheckboxGroup group, boolean state)
Creates a check box with the specified label, in the specified check box group, and set to the
specified state.

Class methods:
S.N. Method & Description

1
void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this check box.

2
void addNotify()
Creates the peer of the Checkbox.

3
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Checkbox.

4
CheckboxGroup getCheckboxGroup()
Determines this check box's group.

5
ItemListener[] getItemListeners()
Returns an array of all the item listeners registered on this checkbox.

6
String getLabel()
Gets the label of this check box.
Advance Java – 6544 Practical No :

7
<T extends EventListener>T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Checkbox.

8
Object[] getSelectedObjects()
Returns an array (length 1) containing the checkbox label or null if the checkbox is not
selected.

9
boolean getState()
Determines whether this check box is in the on or off state.

10
protected String paramString()
Returns a string representing the state of this Checkbox.

11
protected void processEvent(AWTEvent e)
Processes events on this check box.

12
protected void processItemEvent(ItemEvent e)
Processes item events occurring on this check box by dispatching them to any registered
ItemListener objects.

13
void removeItemListener(ItemListener l)
Removes the specified item listener so that the item listener no longer receives item events
from this check box.

14
void setCheckboxGroup(CheckboxGroup g)
Sets this check box's group to the specified check box group.

15
void setLabel(String label)
Sets this check box's label to be the string argument.
Advance Java – 6544 Practical No :

4. List:
The List represents a list of text items. The list can be configured that user can choose either one
item or multiple items

Class constructors
S.N. Constructor & Description

1
List()
Creates a new scrolling list.

2
List(int rows)
Creates a new scrolling list initialized with the specified number of visible lines.

3
List(int rows, boolean multipleMode)
Creates a new scrolling list initialized to display the specified number of rows.

Class methods:
<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this List.

S.N. Method & Description

1
void add(String item)
Adds the specified item to the end of scrolling list.

2
void add(String item, int index)
Adds the specified item to the the scrolling list at the position indicated by the index.

3
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this list.

4
void addItem(String item)
Advance Java – 6544 Practical No :

Deprecated. replaced by add(String).

5
void addItem(String item, int index)
Deprecated. replaced by add(String, int).

6
void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this list.

7
void addNotify()
Creates the peer for the list.

8
boolean allowsMultipleSelections()
Deprecated. As of JDK version 1.1, replaced by isMultipleMode().

9
void clear()
Deprecated. As of JDK version 1.1, replaced by removeAll().

10
int countItems()
Deprecated. As of JDK version 1.1, replaced by getItemCount().

11
void delItem(int position)
Deprecated. replaced by remove(String) and remove(int).

12
void delItems(int start, int end)
Deprecated. As of JDK version 1.1, Not for public use in the future. This method is expected
to be retained only as a package private method.

13
void deselect(int index)
Deselects the item at the specified index.
Advance Java – 6544 Practical No :

5. Textfield:
The textField component allows the user to edit single line of text.When the user types a key in
the text field the event is sent to the TextField.

Class constructors
S.N. Constructor & Description

1
TextField()
Constructs a new text field.

2
TextField(int columns)
Constructs a new empty text field with the specified number of columns.

3
TextField(String text)
Constructs a new text field initialized with the specified text.

4
TextField(String text, int columns)
Constructs a new text field initialized with the specified text to be displayed, and wide
enough to hold the specified number of columns.

Class methods:
S.N. Method & Description

1
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this text field.

2
void addNotify()
Creates the TextField's peer.

3
boolean echoCharIsSet()
Indicates whether or not this text field has a character set for echoing.
Advance Java – 6544 Practical No :

4
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this TextField.

5
ActionListener[] getActionListeners()
Returns an array of all the action listeners registered on this textfield.

6
int getColumns()
Gets the number of columns in this text field.

7
char getEchoChar()
Gets the character that is to be used for echoing.

8
<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this TextField.

9
Dimension getMinimumSize()
Gets the minumum dimensions for this text field.

10
Dimension getMinimumSize(int columns) Gets the minumum dimensions for a text
field with the specified number of columns.

11
Dimension getPreferredSize()
Gets the preferred size of this text field.

12
Dimension getPreferredSize(int columns)
Gets the preferred size of this text field with the specified number of columns.

13
Dimension minimumSize()
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
Advance Java – 6544 Practical No :

6. Textarea:
The TextArea control in AWT provide us multiline editor area. The user can type here as much
as he wants. When the text in the text area become larger than the viewable area the scroll bar is
automatically appears which help us to scroll the text up & down and right & left.

Field:
Following are the fields for java.awt.TextArea class:
• static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal
scrollbars.
• static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal
scrollbar only.
• static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the text
area.
• static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical scrollbar
only.

Class constructors:
S.N. Constructor & Description

1
TextArea()
Constructs a new text area with the empty string as text.

2
TextArea(int rows, int columns)
Constructs a new text area with the specified number of rows and columns and the empty
string as text.

3
TextArea(String text)
Constructs a new text area with the specified text.

4
TextArea(String text, int rows, int columns)
Constructs a new text area with the specified text, and with the specified number of rows
and columns.

5
TextArea(String text, int rows, int columns, int scrollbars)
Constructs a new text area with the specified text, and with the rows, columns, and scroll bar
Advance Java – 6544 Practical No :

visibility as specified.

Class methods:
S.N. Method & Description

1
void addNotify()
Creates the TextArea's peer.

2
void append(String str)
Appends the given text to the text area's current text.

3
void appendText(String str)
Deprecated. As of JDK version 1.1, replaced by append(String).

4
AccessibleContext getAccessibleContext()
Returns the AccessibleContext associated with this TextArea.

5
int getColumns()
Returns the number of columns in this text area.

6
Dimension getMinimumSize()
Determines the minimum size of this text area.

7
Dimension getMinimumSize(int rows, int columns)
Determines the minimum size of a text area with the specified number of rows and columns.

8
Dimension getPreferredSize()
Determines the preferred size of this text area.

9
Dimension getPreferredSize(int rows, int columns)
Advance Java – 6544 Practical No :

Determines the preferred size of a text area with the specified number of rows and columns.

10
int getRows()
Returns the number of rows in the text area.

11
int getScrollbarVisibility()
Returns an enumerated value that indicates which scroll bars the text area uses.

12
void insert(String str, int pos)
Inserts the specified text at the specified position in this text area.

13
void insertText(String str, int pos)
Deprecated. As of JDK version 1.1, replaced by insert(String, int).

14
Dimension minimumSize()
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().

15
Dimension minimumSize(int rows, int columns)
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int, int).

16
protected String paramString()
Returns a string representing the state of this TextArea.

17
Dimension preferredSize()
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().

18
Dimension preferredSize(int rows, int columns)
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int, int).
Advance Java – 6544 Practical No :

7. Choice:
Choice control is used to show pop up menu of choices. Selected choice is shown on the top of
the menu.

Class constructors:
S.N. Constructor & Description

1
Choice() ()
Creates a new choice menu.

Class methods:
S.N. Method & Description

1
void add(String item)
Adds an item to this Choice menu.

2
void addItem(String item)
Obsolete as of Java 2 platform v1.1.

3
void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this Choice menu.

4
void addNotify()
Creates the Choice's peer.

5
int countItems()
Deprecated. As of JDK version 1.1, replaced by getItemCount().

6
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Choice.
Advance Java – 6544 Practical No :

7
String getItem(int index)
Gets the string at the specified index in this Choice menu.

8
int getItemCount()
Returns the number of items in this Choice menu.

9
ItemListener[] getItemListeners()
Returns an array of all the item listeners registered on this choice.

10
<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Choice.

11
int getSelectedIndex()
Returns the index of the currently selected item.

12
String getSelectedItem()
Gets a representation of the current choice as a string.

13
Object[] getSelectedObjects()
Returns an array (length 1) containing the currently selected item.

14
void insert(String item, int index)
Inserts the item into this choice at the specified position.

15
protected String paramString()
Returns a string representing the state of this Choice menu.

16
protected void processEvent(AWTEvent e)
Processes events on this choice.
Advance Java – 6544 Practical No :

Problem Statement: Write a program to design a form using the components textfield, label,
checkbox, button, list.

Program:
import java.awt.*;
import java.awt.event.*;

/*
<applet code="PR01.class" height=300 width=600>
*/

public class PR01 extends Frame


{
Label l1,l2,l3,l4,l5,l6,l7;
TextField tf1,tf2,tf3;
TextArea ta;
CheckboxGroup cg;
Checkbox ch1,ch2;
Choice c;
Button sub,reset;

public PR01()
{
setTitle("STUDENT REGISTRATION FORM");
setSize(300,600);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.CENTER));
l1=new Label(" NAME :");
l2=new Label(" ROLL NUMBER:");
l3=new Label(" Email Address :");
l4=new Label(" Address :");
l5=new Label(" Gender : ");
l6=new Label("Department:");
tf1=new TextField(20);
tf2=new TextField(20);
tf3=new TextField(20);
ta=new TextArea(5,20);
cg=new CheckboxGroup();
ch1=new Checkbox("MALE",true,cg);
ch2=new Checkbox("FEMALE",true,cg);
c=new Choice();
c.add("COMPUTER");
Advance Java – 6544 Practical No :

c.add("CIVL");
c.add("MECHANICAL");
c.add("IT");
c.add("ENTC");
c.add("ELECTRICAL");
c.add("AUTOMOBILE");
c.add("PLASTIC");
sub=new Button("Submit");
sub.setBounds(100,300,10,10);
reset=new Button("Submit");
add(l1);
add(tf1);
add(l2);
add(tf2);
add(l3);
add(tf3);
add(l4);
add(ta);
add(l5);
add(ch1);
add(ch2);
add(l6);
add(c);
add(sub);

public static void main(String[] args) {


PR01 newf=new PR01();
}
}
Advance Java – 6544 Practical No :

Output:
Advance Java – 6544 Practical No :

Questions:

1. What is AWT ?
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

2.List the components.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

3.Define TextArea with example.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

4.Explain two ways for creation of frame.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

5.Write the action listener for the following components:


Button, TextField, List, Checkbox.
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

Conclusion
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No. 02
Title : Write a program to design a calculator using Java components and handle various events
related to each component and apply proper layout to it.

Theory:

Event:

• Change in the state of an object is known as event i.e. event describes the change in state of
source.
• Events are generated as result of user interaction with the graphical user interface
components

Event Handling:

• Event Handling is the mechanism that controls the event and decides what should happen
if an event occurs.
• This mechanism have the code which is known as event handler that is executed when an
event occurs.
• Java Uses the Delegation Event Model to handle the events.

EventObject class :
• It is the root class from which all event state objects shall be derived.
• All Events are constructed with a reference to the object, the source, that is logically
deemed to be the object upon which the Event in question initially occurred upon.
• This class is defined in java.util package.

Class declaration:

Following is the declaration for java.util.EventObject class:

public class EventObject


extends Object
implements Serializable

Field:

Following are the fields for java.util.EventObject class:


• protected Object source -- The object on which the Event initially occurred.
Advance Java – 6544 Practical No :

Class constructors:

S.N. Constructor & Description

1
EventObject(Object source)
Constructs a prototypical Event.

Class methods:

S.N. Method & Description

1
Object getSource()
The object on which the Event initially occurred.

2
String toString()
Returns a String representation of this EventObject.

Event Classes:

Following is the list of commonly used event classes.

Sr. Control & Description


No.

1
AWTEvent
It is the root event class for all AWT events. This class and its subclasses supercede the
original java.awt.Event class.

2
ActionEvent
The ActionEvent is generated when button is clicked or the item of a list is double clicked.
Advance Java – 6544 Practical No :

3
InputEvent
The InputEvent class is root event class for all component-level input events.

4
KeyEvent
On entering the character the Key event is generated.

5
MouseEvent
This event indicates a mouse action occurred in a component.

6
TextEvent
The object of this class represents the text events.

7
WindowEvent
The object of this class represents the change in state of a window.

8
AdjustmentEvent
The object of this class represents the adjustment event emitted by Adjustable objects.

9
ComponentEvent
The object of this class represents the change in state of a window.

10
ContainerEvent
The object of this class represents the change in state of a window.

11
MouseMotionEvent
The object of this class represents the change in state of a window.

12
PaintEvent
The object of this class represents the change in state of a window.
Advance Java – 6544 Practical No :

EventListener interface:

• It is a marker interface which every listener interface has to extend.


• This class is defined in java.util package.

Class declaration:

Following is the declaration for java.util.EventListener interface:

public interface EventListener

AWT Event Listener Interfaces:

Following is the list of commonly used event listeners.

Sr. No. Control & Description

1
ActionListener
This interface is used for receiving the action events.

2
ComponentListener
This interface is used for receiving the component events.

3
ItemListener
This interface is used for receiving the item events.

4
KeyListener
This interface is used for receiving the key events.

5
MouseListener
This interface is used for receiving the mouse events.

6
TextListener
This interface is used for receiving the text events.
Advance Java – 6544 Practical No :

7
WindowListener
This interface is used for receiving the window events.

8
AdjustmentListener
This interface is used for receiving the adjusmtent events.

9
ContainerListener
This interface is used for receiving the container events.

10
MouseMotionListener
This interface is used for receiving the mouse motion events.

11
FocusListener
This interface is used for receiving the focus events.
Advance Java – 6544 Practical No :

Problem Statement: Write a program to design a calculator using Java components and
handle various events related to each component and apply proper layout to it.

Program:
import java.awt.*;
import java.awt.event.*;

/*
<applet code="PR02.class" height=300 width=600>
*/

public class PR02 extends Frame implements ActionListener


{
int num1 = 0, num2 = 0, res = 0;
char op;

TextField input;
Panel p1;
String btnS[]={"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"C", "0", "=", "/"};

Button btn[]= new Button[16];


Font f = new Font("Times New Roman", Font.BOLD, 18);
public PR02()
{
input=new TextField(10);
input.setFont(f);
p1=new Panel();
add(input, "North");
add(p1, "Center");
p1.setLayout(new GridLayout(4,4));
for (int i=0;i<16 ;i++ ) {
btn[i]=new Button(btnS[i]);
btn[i].setFont(f);
btn[i].addActionListener(this);
p1.add(btn[i]);
}

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we) {


System.exit(0);
Advance Java – 6544 Practical No :

}
});}

public void actionPerformed(ActionEvent ae)


{
String str=ae.getActionCommand();
if(str.equals("+"))
{
op = '+';
num1 = Integer.parseInt(input.getText());
input.setText("");

else if(str.equals("-"))
{
op = '-';
num1 = Integer.parseInt(input.getText());
input.setText("");

else if(str.equals("*"))
{
op = '*';
num1 = Integer.parseInt(input.getText());
input.setText("");

else if(str.equals("/"))
{
op = '/';
num1 = Integer.parseInt(input.getText());
input.setText("");

else if(str.equals("="))
{

num2 = Integer.parseInt(input.getText());
switch(op)
{
case '+': res= num1 + num2;
Advance Java – 6544 Practical No :

break;
case '-': res= num1 - num2;
break;
case '*': res= num1 * num2;
break;
case '/': res= num1 / num2;
break;
}
input.setText(res+"");
res=0;
}
else if (str.equals("C")) {
input.setText("");
num1=0;
num2=0;
res=0;
}
else {
input.setText(input.getText() + str);
}}
public static void main(String[] args) {
PR02 pq=new PR02();
pq.setTitle("CALCULATOR");
pq.setSize(250,300);
pq.setVisible(true); }}

Output:
9*6=54
Advance Java – 6544 Practical No :
Advance Java – 6544 Practical No :

Questions:

1.What are Action Listeners in java ?


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

2.Explain events in java.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

3.Enlist methods used for the developing the calculator.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

4.Enlist different types of events in java.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

____________________________________________________________________________
____________________________________________________________________________

5.What are the features of Swing ?


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

Conclusion
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No. 03

Title : Write a program to create a menu bar with various menu items and sub menu items. Also
create a checkable menu item. On clicking a menu Item display a suitable Dialog box.

Theory:
1. Menu Bar:
The MenuBar class provides menu bar bound to a frame and is platform specific.

Class declaration:

Following is the declaration for java.awt.MenuBar class:


public class MenuBar
extends
MenuComponent
implements MenuContainer, Accessible
Class constructors:

S.N. Constructor & Description

1
MenuBar()
Creates a new menu bar.

Class methods

S.N. Method & Description

1
void dispatchEvent(AWTEvent e)

2
Menu add(Menu m)
Adds the specified menu to the menu bar.

3
void addNotify()
Creates the menu bar's peer.
Advance Java – 6544 Practical No :

4
int countMenus()
Deprecated. As of JDK version 1.1, replaced by getMenuCount().

5
void deleteShortcut(MenuShortcut s)
Deletes the specified menu shortcut.

6
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this MenuBar.

7
Menu getHelpMenu()
Gets the help menu on the menu bar.

8
Menu getMenu(int i)
Gets the specified menu.

9
int getMenuCount()
Gets the number of menus on the menu bar.

10
MenuItem getShortcutMenuItem(MenuShortcut s)
Gets the instance of MenuItem associated with the specified MenuShortcut object, or null if
none of the menu items being managed by this menu bar is associated with the specified menu
shortcut.

11
void remove(int index)
Removes the menu located at the specified index from this menu bar.

12
void remove(MenuComponent m)
Removes the specified menu component from this menu bar.

13
void removeNotify()
Removes the menu bar's peer.
Advance Java – 6544 Practical No :

14
void setHelpMenu(Menu m)
Sets the specified menu to be this menu bar's help menu.

15
Enumeration shortcuts()
Gets an enumeration of all menu shortcuts this menu bar is managing.

2. MenuItem:
The MenuBar class represents the actual item in a menu. All items in a menu should derive from
class MenuItem, or one of its subclasses. By default, it embodies a simple labeled menu item.

Class declaration:

Following is the declaration for java.awt.MenuItem class:


public class MenuItem
extends
MenuComponent
implements Accessible
Class constructors:

S.N. Constructor & Description

1
MenuItem()
Constructs a new MenuItem with an empty label and no keyboard shortcut.

2
MenuItem(String label)
Constructs a new MenuItem with the specified label and no keyboard shortcut.

3
MenuItem(String label, MenuShortcut s)
Create a menu item with an associated keyboard shortcut.

Class methods
Advance Java – 6544 Practical No :

S.N. Method & Description

1
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this menu item.

2
void addNotify()
Creates the menu item's peer.

3
void deleteShortcut()
Delete any MenuShortcut object associated with this menu item.

4
void disable()
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).

5
protected void disableEvents(long eventsToDisable)
Disables event delivery to this menu item for events defined by the specified event mask
parameter.

6
void enable()
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).

7
void enable(boolean b)
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).

8
protected void enableEvents(long eventsToEnable)
Enables event delivery to this menu item for events to be defined by the specified event
mask parameter.

9
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this MenuItem.
Advance Java – 6544 Practical No :

3. Menu Class:
The Menu class represents pull-down menu component which is deployed from a menu bar.

Class declaration:

Following is the declaration for java.awt.Menu class:


public class Menu
extends
MenuItem
implements MenuContainer, Accessible
Class constructors:

S.N. Constructor & Description

1
Menu()
Constructs a new menu with an empty label.

2
Menu(String label)
Constructs a new menu with the specified label.

3
Menu(String label, boolean tearOff)
Constructs a new menu with the specified label, indicating whether the menu can be torn off.

Class methods:

S.N. Method & Description

1
MenuItem add(MenuItem mi)
Adds the specified menu item to this menu.

2
void add(String label)
Adds an item with the specified label to this menu.
Advance Java – 6544 Practical No :

3
void addNotify()
Creates the menu's peer.

4
void addSeparator()
Adds a separator line, or a hypen, to the menu at the current position.

5
int countItems()
Deprecated. As of JDK version 1.1, replaced by getItemCount().

6
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Menu.

7
MenuItem getItem(int index)
Gets the item located at the specified index of this menu.

8
int getItemCount()
Get the number of items in this menu.

9
void insert(MenuItem menuitem, int index)
Inserts a menu item into this menu at the specified position.

10
void insert(String label, int index)
Inserts a menu item with the specified label into this menu at the specified position.

11
void insertSeparator(int index)
Inserts a separator at the specified position.

12
boolean isTearOff()
Indicates whether this menu is a tear-off menu.
Advance Java – 6544 Practical No :

public class menubar03 extends java.awt.Frame {

public menubar03() {
initComponents();
setSize(600,600);
}

// <editor-fold defaultstate="collapsed" desc="Generated Code">


private void initComponents() {

label1 = new java.awt.Label();


label2 = new java.awt.Label();
menuBar1 = new java.awt.MenuBar();
menu1 = new java.awt.Menu();
menuItem1 = new java.awt.MenuItem();
menuItem4 = new java.awt.MenuItem();
menuItem5 = new java.awt.MenuItem();
menuItem6 = new java.awt.MenuItem();
menuItem7 = new java.awt.MenuItem();
menu2 = new java.awt.Menu();
menuItem2 = new java.awt.MenuItem();
menuItem3 = new java.awt.MenuItem();
menuItem8 = new java.awt.MenuItem();
menuItem9 = new java.awt.MenuItem();
menuItem10 = new java.awt.MenuItem();
menu3 = new java.awt.Menu();
menu5 = new java.awt.Menu();
Advance Java – 6544 Practical No :

addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});

label1.setText("label1");
add(label1, java.awt.BorderLayout.CENTER);

label2.setName("MenuBar"); // NOI18N
label2.setText("MenuBar");
add(label2, java.awt.BorderLayout.NORTH);

menu1.setLabel("File");
menu1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menu1ActionPerformed(evt);
}
});

menuItem1.setLabel("New");
menuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem1ActionPerformed(evt);
}
});
menu1.add(menuItem1);
Advance Java – 6544 Practical No :

menuItem4.setLabel("Open");
menu1.add(menuItem4);

menuItem5.setLabel("Save");
menu1.add(menuItem5);

menuItem6.setLabel("Save As...");
menu1.add(menuItem6);

menuItem7.setLabel("Close");
menu1.add(menuItem7);

menuBar1.add(menu1);

menu2.setLabel("Edit");

menuItem2.setLabel("Undo");
menu2.add(menuItem2);

menuItem3.setLabel("Redo");
menu2.add(menuItem3);

menuItem8.setLabel("Cut");
menu2.add(menuItem8);

menuItem9.setLabel("Copy");
menu2.add(menuItem9);
Advance Java – 6544 Practical No :

menuItem10.setLabel("Delete");
menu2.add(menuItem10);

menuBar1.add(menu2);

menu3.setLabel("View");
menu3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menu3ActionPerformed(evt);
}
});
menuBar1.add(menu3);

menu5.setLabel("Help");
menu5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menu5ActionPerformed(evt);
}
});
menuBar1.add(menu5);

setMenuBar(menuBar1);

pack();
}
Advance Java – 6544 Practical No :

private void exitForm(java.awt.event.WindowEvent evt) {


System.exit(0);
}

private void menu3ActionPerformed(java.awt.event.ActionEvent evt) { }


private void menuItem1ActionPerformed(java.awt.event.ActionEvent evt) { }
private void menu1ActionPerformed(java.awt.event.ActionEvent evt) { }
private void menu5ActionPerformed(java.awt.event.ActionEvent evt) { }

public static void main(String args[]) {


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new menubar03().setVisible(true);
}
});
}
private java.awt.Label label1;
private java.awt.Label label2;
private java.awt.Menu menu1;
private java.awt.Menu menu2;
private java.awt.Menu menu3;
private java.awt.Menu menu5;
private java.awt.MenuBar menuBar1;
private java.awt.MenuItem menuItem1;
private java.awt.MenuItem menuItem10;
private java.awt.MenuItem menuItem2;
private java.awt.MenuItem menuItem3;
private java.awt.MenuItem menuItem4;
Advance Java – 6544 Practical No :

private java.awt.MenuItem menuItem5;


private java.awt.MenuItem menuItem6;
private java.awt.MenuItem menuItem7;
private java.awt.MenuItem menuItem8;
private java.awt.MenuItem menuItem9;
}
Output:
Advance Java – 6544 Practical No :

Questions:

1.What is DialogBox ?
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

2.List down constructor of MenuBar?


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

3.Write the methods of:


i)MenuItems ,ii)File DialogBox
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

4.Define Checkbox MenuItem with example.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

5.Difference MenuBar and MenuItems.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

Conclusion
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No. 04

Title : Write a program using swing to display a JcomboBox in an applet with the items –
cricket,football,hockey,tennis.

Theory:
JComboBox:

• JComboBox is a part of Java Swing package.


• JComboBox inherits JComponent class .
• JComboBox shows a popup menu that shows a list and the user can select a option from
that specified list .
• JComboBox can be editable or read- only depending on the choice of the programmer .

Constructors of the JComboBox :

1. JComboBox() : creates a new empty JComboBox .


2. JComboBox(ComboBoxModel M) : creates a new JComboBox with items from specified
ComboBoxModel
3. JComboBox(E [ ] i) : creates a new JComboBox with items from specified array.
4. JComboBox(Vector items) : creates a new JComboBox with items from the specified
vector

Methods of the JComboBox :

1. addItem(E item) : adds the item to the JComboBox


2. addItemListener( ItemListener l) : adds a ItemListener to JComboBox
3. getItemAt(int i) : returns the item at index i
4. getItemCount(): returns the number of items from the list
5. getSelectedItem() : returns the item which is selected
6. removeItemAt(int i) : removes the element at index i
7. setEditable(boolean b) : the boolean b determines whether the combo box is editable or
not .If true is passed then the combo box is editable or vice versa.
8. setSelectedIndex(int i): selects the element of JComboBox at index i.
9. showPopup() :causes the combo box to display its popup window.
Advance Java – 6544 Practical No :

10. setUI(ComboBoxUI ui): sets the L&F object that renders this component.
11. setSelectedItem(Object a): sets the selected item in the combo box display area to the
object in the argument.
12. setSelectedIndex(int a): selects the item at index anIndex.
13. setPopupVisible(boolean v): sets the visibility of the popup.
14. setModel(ComboBoxModel a) : sets the data model that the JComboBox uses to obtain
the list of items.
15. setMaximumRowCount(int count): sets the maximum number of rows the JComboBox
displays.
16. setEnabled(boolean b): enables the combo box so that items can be selected.
17. removeItem(Object anObject) : removes an item from the item list.
18. removeAllItems(): removes all items from the item list.
19. removeActionListener(ActionListener l): removes an ActionListener.
20. isPopupVisible() : determines the visibility of the popup.
21. addPopupMenuListener(PopupMenuListener l) : adds a PopupMenu listener which will
listen to notification messages from the popup portion of the combo box.
22. getActionCommand() : returns the action command that is included in the event sent to
action listeners.
23. getEditor(): returns the editor used to paint and edit the selected item in the JComboBox
field.
24. getItemCount() : returns the number of items in the list.
25. getItemListeners(): returns an array of all the ItemListeners added to this JComboBox
with addItemListener().
26. createDefaultKeySelectionManager() : returns an instance of the default key-selection
manager.
27. fireItemStateChanged(ItemEvent e) : notifies all listeners that have registered interest for
notification on this event type.
28. firePopupMenuCanceled() : notifies PopupMenuListeners that the popup portion of the
combo box has been canceled.
29. firePopupMenuWillBecomeInvisible() : notifies PopupMenuListeners that the popup
portion of the combo box has become invisible.
Advance Java – 6544 Practical No :

30. firePopupMenuWillBecomeVisible() : notifies PopupMenuListeners that the popup


portion of the combo box will become visible.
31. setEditor(ComboBoxEditor a): sets the editor used to paint and edit the selected item in
the JComboBox field.
32. setActionCommand(String a) : sets the action command that should be included in the
event sent to actionListeners.
33. getUI() : returns the look and feel object that renders this component.
34. paramString() : returns a string representation of this JComboBox.
35. getUIClassID() : returns the name of the Look and feel class that renders this component.
36. getAccessibleContext() : gets the AccessibleContext associated with this JComboBox

Problem Statement : Write a program using swing to display a JcomboBox in an applet


with the items –cricket,football,hockey,tennis.
Advance Java – 6544 Practical No :

Program:

import javax.swing.*;

public class PR04 {

JFrame f;

public PR04(){

f=new JFrame("ComboBox");

String list[]={"CRICKET","FOOTBALL","HOCKEY","TENNIS"};

JComboBox cb=new JComboBox(list);

cb.setBounds(150, 50,90,20);

f.add(cb);

f.setLayout(null);

f.setSize(400,500);

f.setVisible(true);

public static void main(String[] args) {

new PR04();

} }

Output:
Advance Java – 6544 Practical No :
Advance Java – 6544 Practical No :

Questions:

1.What are events performed on JComboBox ?


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

2.List constructor of JComboBox.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

3.Why we use Swing ?


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

4.Explain methods of JComboBox.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

____________________________________________________________________________

5.Difference between JComboBox and JList.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

Conclusion
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No. 05

Title :
Write a program to create:

-JTree

-JTable

Theory:

1. JTree:

• The JTree class is used to display the tree structured data or hierarchical data.
• JTree is a complex component.
• It has a 'root node' at the top most which is a parent for all nodes in the tree.
• It inherits JComponent class.

• Tree class declaration

public class JTree extends JComponent implements Scrollable, Accessible

• Constructors of JTree:

Constructor Description

JTree() Creates a JTree with a sample model.

JTree(Object[] Creates a JTree with every element of the specified array as the
value) child of a new root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which
root) displays the root node.
Advance Java – 6544 Practical No :

2. JTable:

• The JTable class is used to display data in tabular form.


• It is composed of rows and columns.

• Constructors of JTable:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

• Functions in JTable :

1. addColumn(TableColumn []column) : adds a column at the end of the JTable.

2. clearSelection() : Selects all the selected rows and columns.

3. editCellAt(int row, int col) : edits the intersecting cell of the column number col and row

number row programmatically, if the given indices are valid and the corresponding cell is

editable.

4. setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’ for the position

row, col in the JTable.


Advance Java – 6544 Practical No :

Problem Statement:

1. Write a program to create JTree:

Program:

import javax.swing.*;

public class JFrame01 extends javax.swing.JFrame {

/**

* Creates new form JFrame01

*/

public JFrame01() {

initComponents();

/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {


Advance Java – 6544 Practical No :

jScrollPane1 = new javax.swing.JScrollPane();

jTree1 = new javax.swing.JTree();

jLabel1 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jTree1.setBorder(new javax.swing.border.MatteBorder(null));

jTree1.setAlignmentY(1.5F);

jTree1.setDropMode(javax.swing.DropMode.ON);

jScrollPane1.setViewportView(jTree1);

jLabel1.setText("JTree");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addContainerGap(125, Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
Advance Java – 6544 Practical No :

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,

145, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 157,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(118, 118, 118))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addComponent(jLabel1)

.addGap(29, 29, 29)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,

202, javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(44, Short.MAX_VALUE))

);

pack();

}// </editor-fold>

/**

* @param args the command line arguments

*/
Advance Java – 6544 Practical No :

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and

feel.

* For details see

http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

try {

for (javax.swing.UIManager.LookAndFeelInfo info :

javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(JFrame01.class.getName()).log(java.util.logging.Level.

SEVERE, null, ex);

} catch (InstantiationException ex) {


Advance Java – 6544 Practical No :

java.util.logging.Logger.getLogger(JFrame01.class.getName()).log(java.util.logging.Level.

SEVERE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(JFrame01.class.getName()).log(java.util.logging.Level.

SEVERE, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(JFrame01.class.getName()).log(java.util.logging.Level.

SEVERE, null, ex);

//</editor-fold>

/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new JFrame01().setVisible(true);

}); }

private javax.swing.JLabel jLabel1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JTree jTree1; }


Advance Java – 6544 Practical No :

Output:

2. Write a program to create JTable:

Program:

public class Jtable01 extends javax.swing.JFrame {

/**

* Creates new form Jtable01

*/

public Jtable01() {

initComponents();

}
Advance Java – 6544 Practical No :

/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();

jTable1 = new javax.swing.JTable();

jLabel1 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jTable1.setBorder(new javax.swing.border.MatteBorder(null));

jTable1.setModel(new javax.swing.table.DefaultTableModel(

new Object [][] {

{"Kalyani Shirsath ", new Integer(186151), "Computer", new Integer(3)},

{"Tejal Yawalkar", new Integer(186159), "Computer", new Integer(3)},

{"Shweta Jangam", new Integer(181202), "Civil", new Integer(1)},

{"Mansi Nikam", new Integer(185142), "ENTC", new Integer(2)},

{"Sarthak Wakchoure", new Integer(182151), "Mechanical", new Integer(3)},


Advance Java – 6544 Practical No :

{"Utkarsha Godse", new Integer(184134), "Electrical", new Integer(2)},

{"Anushka Nikam", new Integer(182208), "Plastic", new Integer(1)},

{"Vaishnavi Patil", new Integer(186107), "Automobile", new Integer(2)},

{"Ankita Patil", new Integer(185137), "IT", new Integer(1)},

{"Varsha Patil ", new Integer(187101), "IDD", new Integer(2)}

},

new String [] {

"Name ", "Roll Number", "Programme", "Year"

){

Class[] types = new Class [] {

java.lang.String.class, java.lang.Integer.class, java.lang.String.class,

java.lang.Integer.class

};

public Class getColumnClass(int columnIndex) {

return types [columnIndex];

});

jScrollPane1.setViewportView(jTable1);

jLabel1.setText("STUDENTS RECORD ");


Advance Java – 6544 Practical No :

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap(15, Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addComponent(jScrollPane1,

javax.swing.GroupLayout.PREFERRED_SIZE, 375,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap())

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addComponent(jLabel1)

.addGap(182, 182, 182))))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()
Advance Java – 6544 Practical No :

.addGap(0, 11, Short.MAX_VALUE)

.addComponent(jLabel1)

.addGap(15, 15, 15)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,

255, javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap())

);

pack();

}// </editor-fold>

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and

feel.

* For details see

http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

try {
Advance Java – 6544 Practical No :

for (javax.swing.UIManager.LookAndFeelInfo info :

javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(Jtable01.class.getName()).log(java.util.logging.Level.S

EVERE, null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(Jtable01.class.getName()).log(java.util.logging.Level.S

EVERE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(Jtable01.class.getName()).log(java.util.logging.Level.S

EVERE, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(Jtable01.class.getName()).log(java.util.logging.Level.S

EVERE, null, ex);


Advance Java – 6544 Practical No :

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new Jtable01().setVisible(true);

} }); }

private javax.swing.JLabel jLabel1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JTable jTable1; }

Output:
Advance Java – 6544 Practical No :

Questions:

1.Write a definition of JTree and JTable ?


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

2.Explain constructor of JTable?


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

3.Write the features of JTable.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

4.Why we use JTable.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

____________________________________________________________________________
____________________________________________________________________________

5.List Constructor of JTree.


____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

Conclusion
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No. 06
Title : Write a program making use of Adapter class.

Theory:

Adapter Class:

• Adapter classes provide an implementation of listener interfaces.

• When you inherit the adapter class implementation for all methods is not mandatory.
Thus writing excess code is saved.

• These adapter classes can be found in java.awt.event, java.awt.dnd and


javax.swing.event packages.

• Some of the common adapter classes with corresponding listener interfaces are given
below.
1. java.awt.event
2. java.awt.dnd
3. javax.swing.event
1. java.awt.event

• The java.awt.event package defines classes and interfaces used for event handling in
the AWT and Swing.

• The members of this package fall into three categories:

➢ Events

The classes with names ending in "Event" represent specific types of events,
generated by the AWT or by one of the AWT or Swing components.

➢ Listeners

The interfaces in this package are all event listeners; their names end with "Listener".

➢ Adapters

Each of the classes with a name ending in "Adapter" provides a no-op


implementation for an event listener interface that defines more than one method.
Advance Java – 6544 Practical No :

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

2. java.awt.dnd

• This package defines the classes and interfaces necessary to perform Drag and Drop
operations in Java.

• It defines classes for the drag-source and the drop-target, as well as events for
transferring the data being dragged.

• This package also provides a means for giving visual feedback to the user throughout
the duration of the Drag and Drop operation.

Adapter class Listener interface

DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener

3. javax.swing.event

• Provides for events fired by Swing components.

• It contains event classes and corresponding event listener interfaces for events fired
by Swing components in addition to those events in the java.awt.event package.

Adapter class Listener interface


MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Advance Java – 6544 Practical No :

Problem Statement: Write a program making use of Adapter class.

Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Adapter01 extends Applet {


public void init()
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
Adapter01 ad;
public MyMouseAdapter(Adapter01 ad)
{
this.ad=ad;
}
public void mouseClicked(MouseEvent me)
{
ad.showStatus("Mouse Clicked by USER");
}
}
class MyMouseMotAdapter extends MouseMotionAdapter
{
Adapter01 ad;
public MyMouseMotAdapter(Adapter01 ad)
{
this.ad=ad;
Advance Java – 6544 Practical No :
}
public void mouseDragged(MouseEvent me)
{
ad.showStatus("Mouse dragged by USER");
}
}
Output:
Advance Java – 6544 Practical No :
Advance Java – 6544 Practical No :

Questions:

1.What is Adapter class ?


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

2.Why we used Adapter class ?


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

3.List down the Adapter classes in java.


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

4.What is inner class ?


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Advance Java – 6544 Practical No :

5.Write down advantages of inner class.


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

Conclusion
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No. 07
Title: Write a program to retrieve hostname--using methods in Inet Address class.

Theory:

Java InetAddress :

• Java InetAddress class represents an IP address.

• The java.net.InetAddress class provides methods to get the IP of any host name for
example www.javatpoint.com, www.google.com, www.facebook.com, etc.

• An IP address is represented by 32-bit or 128-bit unsigned number. An instance of


InetAddress represents the IP address with its corresponding host name.

• There are two types of address types:


1. Unicast : The Unicast is an identifier for a single interface
2. Multicast: Multicast is an identifier for a set of interfaces.

• Moreover, InetAddress has a cache mechanism to store successful and unsuccessful


host name resolutions.
Subclasses of InetAddress:
➢ Inet4Address and Inet6Address:

• and Inet6Address represent IPv4 and IPv6 addresses, respectively.


Inet4Address
However, when writing network applications, you don’t have to
concern about IPv4 or IPv6 as Java hides all the details.
• The InetAddresscan refer to either Inet4Address or Inet6Address so most of the
time, using InetAddressis enough.
• Inetaddreass can handle both Ipv4 and Ipv6 addresses.Inet Address class has
no visible constructors.To create an inet Address object,you have to use
Factory Methods.
Factory Methods:

• Factory Methods are static methods in a class that return an object of that class.

• This method returns the instance of InetAddress containing the local hostname and
address.

• This method returns the instance of InetAddress containing LocalHost IP and


name.
Advance Java – 6544 Practical No :

Factory methods available in InetAddressclass :


Method Description
static InetAddressgetLocalHost() throws This method returns the instance of InetAddress
UnknownHostException containing the local hostname and address.
public static InetAddressgetByName( String This method returns the instance of InetAddress
host ) throws UnknownHostException containing LocalHost IP and name.
static InetAddress[] getAllByName( String This method returns the array of the instance of
hostName ) throws UnknownHostException InetAddress class which contains IP addresses.
static InetAddressgetByAddress( byte This method returns an InetAddress object
IPAddress[] ) throws UnknownHostException created from the raw IP address.
static InetAddressgetByAddress( String
This method creates and returns an InetAddress
hostName, byte IPAddress[] ) throws
based on the provided hostname and IP address.
UnknownHostException

Instance Methods:

• Instance Methods are the non static methods of any class which are defined in that
class and accessed only by object of that class.

• Instance method means member methods of object of a class.

• Instance methods of InetAddress returns IP Address information of any host stored


by its object.

Method Description
This function compares this object against the
equals(Object obj)
specified object.
This method returns the raw IP address of this
getAddress()
InetAddress object, in bytes.
This method returns the fully qualified domain
getCanonicalHostName()
name for this IP address.
getHostAddress() This method gets the IP address in string form.
This method returns the host name for this IP
getHostName()
address.
hashCode() This method gets a hashcode for this IP address.
This method utility routine to check if the
isAnyLocalAddress()
InetAddress is an unpredictable address.
This method utility routine to check if the
isLinkLocalAddress()
address is not linked to local unicast address.
This method used to check if the InetAddress
isLoopbackAddress()
represents a loopback address.
isMCGlobal() This method utility routine check if this address
Advance Java – 6544 Practical No :
has a multicast address of global scope.
This method utility routine check if this address
isMCLinkLocal()
has a multicast address of link-local scope.
This method utility routine check if the multicast
isMCNodeLocal()
address has node scope.
This method utility routine check if the multicast
isMCOrgLocal()
address has an organization scope.
This method utility routine check if the multicast
isMCSiteLocal()
address has site scope.
This method checks whether the site has
isMulticastAddress()
multiple servers.
This method tests whether that address is
isReachable(int timeout)
reachable.
isReachable(NetworkInterfacenetif, intttl, int This method tests whether that address is
timeout) reachable.
This method utility routine check if the
isSiteLocalAddress()
InetAddress is a site-local address.
This method converts and returns an IP address
toString()
in string form.
Advance Java – 6544 Practical No :

Problem Statement: Write a program to retrieve hostname--using methods in Inet Address


class.

Program:
import java.io.*;
import java.net.*;
public class inet {
public static void main(String [] args) throws UnknownHostException
{
InetAddress add=InetAddress.getLocalHost();

System.out.println("LocalHost : "+add.getHostName());
System.out.println("LocalHost Address: "+add.getHostAddress());
InetAddress add1=InetAddress.getByName("www.google.com");
System.out.println("******************************");
System.out.println("Host Name: "+add1.getHostName());
System.out.println("Host Address: "+add1.getHostAddress());
InetAddress add2=InetAddress.getByName("www.gpnashik.ac.in");
System.out.println("******************************");
System.out.println("Host Name: "+add2.getHostName());
System.out.println("Host Address: "+add2.getHostAddress());
}
}

Output:
Advance Java – 6544 Practical No :

Questions:

1.What is Inet Address ?


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

2.List the methods of the Inet Address ?


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

3.Explain the isLoopbackAddress()?


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

4.What is the use of gerHostName() method ?


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Advance Java – 6544 Practical No :

Conclusion
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No. 08
Title : Write a program that demonstrates TCP/IP based communication between client
and server.

Theory:

Computer Network:

• A computer network is a group of computers systems and other computing hardware


devoces that are linked together through communication channels to facilitate
communication and resource sharing among a wide range of users.

• Networks are classified based on their characteristics. EgLAN,MAN,WAN,Internet,WiFi.


Java.net Package:

• The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.

• The java.net package provides support for the two common network protocols −
➢ TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
➢ UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.
This practical gives a good understanding on the following two subjects −

• Socket Programming − This is the most widely used concept in Networking and it has been
explained in very detail.

• URL Processing − This would be covered separately. Click here to learn about URL
Processing in Java language.

Socket Programming
• Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that
socket to a server.

• When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and reading
from the socket.

• The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
Advance Java – 6544 Practical No :
The following steps occur when establishing a TCP connection between two computers using
sockets −
➢ The server instantiates a ServerSocket object, denoting which port number communication is
to occur on.
➢ The server invokes the accept() method of the ServerSocket class. This method waits until a
client connects to the server on the given port.
➢ After the server is waiting, a client instantiates a Socket object, specifying the server name
and the port number to connect to.
➢ The constructor of the Socket class attempts to connect the client to the specified server and
the port number. If communication is established, the client now has a Socket object capable
of communicating with the server.
➢ On the server side, the accept() method returns a reference to a new socket on the server that
is connected to the client's socket.

• After the connections are established, communication can occur using I/O streams. Each
socket has both an OutputStream and an InputStream. The client's OutputStream is
connected to the server's InputStream, and the client's InputStream is connected to the
server's OutputStream.

• TCP is a two-way communication protocol, hence data can be sent across both streams at
the same time. Following are the useful classes providing complete set of methods to
implement sockets.

ServerSocket Class Methods:


The java.net.ServerSocket class is used by server applications to obtain a port and listen for client
requests.
The ServerSocket class has four constructors −

Sr.No. Method & Description


public ServerSocket(int port) throws IOException

1 Attempts to create a server socket bound to the specified port. An exception occurs if the
port is already bound by another application.

public ServerSocket(int port, int backlog) throws IOException

2 Similar to the previous constructor, the backlog parameter specifies how many incoming
clients to store in a wait queue.

public ServerSocket(int port, int backlog, InetAddress address) throws IOException


3 Similar to the previous constructor, the InetAddress parameter specifies the local IP address
to bind to. The InetAddress is used for servers that may have multiple IP addresses,
Advance Java – 6544 Practical No :
allowing the server to specify which of its IP addresses to accept client requests on.

public ServerSocket() throws IOException

4 Creates an unbound server socket. When using this constructor, use the bind() method
when you are ready to bind the server socket.

Following are some of the common methods of the ServerSocket class −

Sr.No. Method & Description


public intgetLocalPort()

1 Returns the port that the server socket is listening on. This method is useful if you passed in
0 as the port number in a constructor and let the server find a port for you.

public Socket accept() throws IOException

2 Waits for an incoming client. This method blocks until either a client connects to the server
on the specified port or the socket times out, assuming that the time-out value has been set
using the setSoTimeout() method. Otherwise, this method blocks indefinitely.

public void setSoTimeout(int timeout)


3 Sets the time-out value for how long the server socket waits for a client during the accept().

public void bind(SocketAddress host, int backlog)

4 Binds the socket to the specified server and port in the SocketAddress object. Use this
method if you have instantiated the ServerSocket using the no-argument constructor.

Socket Class Methods:


• The java.net.Socket class represents the socket that both the client and the server use to
communicate with each other.

• The client obtains a Socket object by instantiating one, whereas the server obtains a Socket
object from the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server −

Sr.No. Method & Description


public Socket(String host, int port) throws UnknownHostException, IOException.

This method attempts to connect to the specified server at the specified port. If this
1
constructor does not throw an exception, the connection is successful and the client is
connected to the server.
Advance Java – 6544 Practical No :
public Socket(InetAddress host, int port) throws IOException

2
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object.

public Socket(String host, int port, InetAddresslocalAddress, intlocalPort) throws


IOException.
3
Connects to the specified host and port, creating a socket on the local host at the specified
address and port.

public Socket(InetAddress host, int port, InetAddresslocalAddress, intlocalPort)


throws IOException.
4
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object instead of a String.

public Socket()
5
Creates an unconnected socket. Use the connect() method to connect this socket to a server.

Some methods of interest in the Socket class are listed here:

Sr.No. Method & Description


public void connect(SocketAddress host, int timeout) throws IOException

1 This method connects the socket to the specified host. This method is needed only when
you instantiate the Socket using the no-argument constructor.

public InetAddressgetInetAddress()
2 This method returns the address of the other computer that this socket is connected to.

public intgetPort()
3 Returns the port the socket is bound to on the remote machine.

public intgetLocalPort()
4 Returns the port the socket is bound to on the local machine.

public SocketAddressgetRemoteSocketAddress()
5 Returns the address of the remote socket.

public InputStreamgetInputStream() throws IOException


6
Returns the input stream of the socket. The input stream is connected to the output stream
Advance Java – 6544 Practical No :
of the remote socket.

public OutputStreamgetOutputStream() throws IOException

7 Returns the output stream of the socket. The output stream is connected to the input stream
of the remote socket.

public void close() throws IOException

8 Closes the socket, which makes this Socket object no longer capable of connecting again to
any server.
Advance Java – 6544 Practical No :

Problem Statement:

Program:
1. myclient.java:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class myclient {

public static void main(String [] args) throws Exception


{
Socket s=new Socket("127.0.0.1",1342);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str1="",str2="";
while(!str1.equals("NET"))
{
str1=br.readLine();
dout.writeUTF(str1);
str2=din.readUTF();
System.out.println("SERVER SAYS: "+str2); }
dout.close();
s.close();
}
}

2. myserver.java:

import java.net.*;
import java.io.*;
public class myserver {
public static void main(String [] args) throws Exception
{
ServerSocket s1=new ServerSocket(1342);
Socket s=s1.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str1="",str2="";
while(!str1.equals("NET"))
{
Advance Java – 6544 Practical No :
str1=din.readUTF();
System.out.println("CLIENT SAYS: "+str1);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
s1.close(); } }

Output:
1. Client:

2. Server:
Advance Java – 6544 Practical No :

Questions:

1. Define TCP/IP protocol.


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

2.Write down difference between TCP/IP and UDP.


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

3.List the methods use for TCP/IP based communication between client and server.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

4.What is socket programming.


___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

Conclusion
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Advance Java – 6544 Practical No :
Advance Java – 6544 Practical No :

Practical No. 9
Title: Write an Application program /Applet to make connectivity with database usingJDBC,
API

Theory:

1. Introduction to JDBC
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.

2. Common JDBC Components

The JDBC API provides the following interfaces and classes −


• Driver Manager − This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication
sub protocol. The first driver that recognizes a certain sub protocol under JDBC will be
used to establish a database Connection.
• Driver − This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager objects,
which manages objects of this type. It also abstracts the details associated with working
with Driver objects.
• Connection − This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is through
connection object only.
• Statement − You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
Advance Java – 6544 Practical No :

• ResultSet − These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its data.
• SQLException − This class handles any errors that occur in a database application

3. Java Database Connectivity

1) Java Database Connectivity with Oracle


To connect java application with the oracle database, we need to follow 5 following steps.
In this example, we are using Oracle 10g as the database. So we need to know following
information for the oracle database:
1. Driver class: The driver class for the oracle database is
oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin
is the driver, localhost is the server name on which oracle is running, we may also use IP
address, 1521 is the port number and XE is the Oracle service name. You may get all these
information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database

Before establishing connection, let's first create a table in oracle database. Following is the SQL
query to create a table.

create table emp(id number(10),name varchar2(40),age number(3));

• Example to Connect Java Application with Oracle database:


In this example, we are connecting to an Oracle database and getting data from emp table. Here,
system and oracle are the username and password of the Oracle database.

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
Advance Java – 6544 Practical No :

//step1 load the driver class


Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object


Statement
stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection


objectcon.close();

}catch(Exception e){ System.out.println(e);}

}
}
Advance Java – 6544 Practical No :

Problem Statement: Write an Application program /Applet to make connectivity with


database using JDBC, API.

Program:

import java.sql.*;
public class mysql{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db1","root","root" );

Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from students");
/*while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "); */
if(con!=null)
{System.out.println("Connection created successfully\n"+con);}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Advance Java – 6544 Practical No :

Ouput:
Advance Java – 6544 Practical No :

Questions:

1. What is JDBC ?
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

2.List the types of JDBC Driver.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

3.Write down the steps for creating JDBC Application.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

4.Define Resultset with syntax.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

5.Define Connection interface with example.


__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :

__________________________________________________________________________
__________________________________________________________________________

__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

Conclusion
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No. 10
Title: Write an Application program/Applet to send queries through JDBC Bridge & handle
result.

Theory:

• JDBC Drivers and Types:


JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates.
Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which is

1. Type 1 Driver : JDBC/ODBC Bridge
2. Type 2 Driver :Native API Driver
3. Type 3 Driver :Network Protocol,Pure Java Driver
4. Type 4 Driver : Native Protocol,Pure Java Driver

• JDBC-ODBC Bridge Driver:

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine.
Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents
the target database.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.
Type-1 driver is also called Universal driver because it can be used to connect to any of the
databases.

Characteristics:
1) As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
2) The ODBC bridge driver is needed to be installed in individual client machines.
3) Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
4) This driver software is built-in with JDK so no need to install separately.
5) It is a database independent driver.
Advance Java – 6544 Practical No :

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Advantages:
1. Easy to use.
2. Allow easy connectivity to all database supported by ODBC Driver.
3. It is free there is no any money change.
4. Can be easily connected to any database.

Disadvantages:
1. Slow Execution time.
2. Dependent on ODBC Driver.
3. Uses Java Native Interface (JNI) to make ODBC call.
4. ODBC drivers must also be loaded on the target machine.
5. Translation between JDBC and ODBC affects performance.
6. Consumes more time and it is not a platform independent.
Advance Java – 6544 Practical No :

Problem Statement: Write an Application program/Applet to send queries through JDBC


Bridge & handle result.

Program:

import java.sql.*;
public class mysql{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db1","root","root" );

Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from students");
if(con!=null)
{System.out.println("Connection created successfully\n"+con);}
System.out.println("************STUDENT DATA*******************");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" ");

con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Advance Java – 6544 Practical No :

Output:
Advance Java – 6544 Practical No :

Questions:

1.Enlist the types of JDBC drivers.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

2.What are the advantages and disadvantages of JDBC – ODBC bridge driver ?
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

3.Explain Statement Interface.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

4.Enlist methods of Resultset Interface.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :

Conclusion
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No. 11
Title: Write a servlet for demonstrating the generic servlet class.
Theory:
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from
a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
• Performance is significantly better.
• Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.

Servlets Architecture:

The following diagram shows the position of Servlets in a Web Application.

Servlets Tasks:

Servlets perform the following major tasks −


• Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.
Advance Java – 6544 Practical No :

• Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.

Servlets Packages:

Java Servlets are Java classes run by a web server that has an interpreter that supports the Java
Servlet specification.
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.
These classes implement the Java Servlet and JSP specifications. At the time of writing this
tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Generic Servlet class:

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It


provides the implementation of all the methods of these interfaces except the service method.

GenericServlet class can handle any type of request so it is protocol-independent.

You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.

Methods of GenericServlet class:

There are many methods in GenericServlet class. They are as follows:

1. public void init(ServletConfigconfig) is used to initialize the servlet.


2. public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time when user
requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that
servlet is being destroyed.
4. publicServletConfiggetServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no
need to call super.init(config)
7. publicServletContextgetServletContext() returns the object of ServletContext.
Advance Java – 6544 Practical No :

8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet
log file and a stack trace.
Advance Java – 6544 Practical No :

Problem Statement: Write a servlet for demonstrating the generic servlet class.
Program:
1. index.html:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Welcome to Admin Panel</h1>
<a href="add">Click to call Servlet</a>
</body>
</html>

2. add.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.*;
public class add extends GenericServlet {

public void service(ServletRequest request, ServletResponse response) throws


ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html><body>");
out.println("<b><h2>HELLO USER!!!</b></h2>");
out.println("Username:Kalyani Shirsath");
out.println("<br><br>");
out.println("Email id:[email protected]");
out.println("<br><br>");
out.println("Mobile No:1234567860");
out.println("</body></html>");
out.close(); }}
Advance Java – 6544 Practical No :

3. web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>add</servlet-name>
<servlet-class>add</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Output:
Advance Java – 6544 Practical No :
Advance Java – 6544 Practical No :

Questions:

1. What is Servlet ?
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

2.Enlist types of servlet.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

3.Why we use servlet over the CGI ?


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

4.Write the execution steps of servlet.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

Conclusion
__________________________________________________________________________
Advance Java – 6544 Practical No :

__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No 12
Aim : Create web form which process servlet and demonstrate use of cookies and sessions

Theory:

Session Tracking in Servlets

• Session simply means a particular interval of time.


• Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
• Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we
need to maintain the state of an user to recognize to particular user.
• HTTP is stateless that means each request is considered as the new request. It is shown in
the figure given below:

Why use Session Tracking?

• To recognize the user


• It is used to recognize the particular user.

Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies
2. HttpSession
3. Hidden Form Field
Advance Java – 6544 Practical No :

4. URL Rewriting

1. Cookies in Servlet

• A cookie is a small piece of information that is persisted between the multiple client
requests.
• A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.

How Cookie works

• By default, each request is considered as a new request. In cookies technique, we add


cookie with response from the servlet. So cookie is stored in the cache of the browser.
• After that if request is sent by the user, cookie is added with request by default. Thus, we
recognize the user as the old user.

Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

• It is valid for single session only.


• It is removed each time when user closes the browser.

Persistent cookie

• It is valid for multiple session .


• It is not removed each time when user closes the browser. It is removed only if user
logout or signout.
Advance Java – 6544 Practical No :

Advantage of Cookies

• Simplest technique of maintaining the state.


• Cookies are maintained at client side.

Disadvantage of Cookies

• It will not work if cookie is disabled from the browser.


• Only textual information can be set in Cookie object

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of


useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

Method Description

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

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

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

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


name)
Advance Java – 6544 Practical No :

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


value)

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by
other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to
add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return
all the cookies from the browser.

How to create Cookie?

Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Cookie ck=new Cookie("user","");//deleting value of


cookieck.setMaxAge(0);//changing the maximum age to
0 secondsresponse.addCookie(ck);//adding cookie in the
response
How to get Cookies?

Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
Sytem.out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
//printing name and value of cookie
}
Advance Java – 6544 Practical No :

2. HttpSession interface

• Container creates a session id for each user.


• The container uses this id to identify the particular user.An object of HttpSession can be
used to perform two tasks:

1. bind objects
2. View and manipulate information about a session, such as the session identifier, creation
time, and last accessed time.

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. public HttpSession getSession():Returns the current session associated with this request,
or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns a
new session.

Commonly used methods of HttpSession interface

1. public String getId():Returns a string containing the unique identifier value.


2. public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
Advance Java – 6544 Practical No :

3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

3. Hidden Form Field

• In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the
state of an user.
• In such case, we store the information in the hidden field and get it from another servlet.
This approach is better if we have to submit form in all the pages and we don't want to
depend on the browser.
• SYNTAX : <input type="hidden" name="uname" value="Vimal Jaiswal">

Real application of hidden form field

It is widely used in comment form of a website. In such case, we store page id or page name in
the hidden field so that each page can be uniquely identified.

Advantage of Hidden Form Field

• It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

• It is maintained at server side.


• Extra form submission is required on each pages.
• Only textual information can be used.

4. URL Rewriting

• In URL rewriting, we append a token or identifier to the URL of the next Servlet or the
next resource.
• We can send parameter name/value pairs using the following format:
• url?name1=value1&name2=value2&??
Advance Java – 6544 Practical No :

Advantage of URL Rewriting

• It will always work whether cookie is disabled or not (browser independent).


• Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

• It will work only with links.


• It can send Only textual information.
Advance Java – 6544 Practical No :

Problem Statement: Create web form which process servlet and demonstrate use of cookies
and sessions.

Program:

1. index1.html:
<html>
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="login">
User Name:<input type="text" name="userName"/><br/><br />
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

2. myserv1.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class myserv1 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();

String name = request.getParameter("userName");


String password = request.getParameter("userPassword");
pwriter.print("<h2>Hello "+name+"</h2>");
System.out.print("\n\n");

//Creating two cookies


Cookie c1=new Cookie("userName",name);
Cookie c2=new Cookie("userPassword",password);
Advance Java – 6544 Practical No :

//Adding the cookies to response header


response.addCookie(c1);
response.addCookie(c2);
pwriter.print("<br><a href='welcome'>View Details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}}

3. myserv2.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class myserv2 extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();

//Reading cookies
Cookie c[]=request.getCookies();
//Displaying User name value from cookie
pwriter.print("<h2>RETRIVING COOKIES</h2>");

pwriter.print("Value of cookie is: "+c[1].getValue());

pwriter.print("<h2>SESSION DETAILS</h2>");
HttpSession session=request.getSession(false);
pwriter.print("USERNAME is: "+c[1].getValue());
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}

}
Advance Java – 6544 Practical No :

4. web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<welcome-file-list>
<welcome-file>index1.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>myserv1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>myserv2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Advance Java – 6544 Practical No :

Output:
Advance Java – 6544 Practical No :
Advance Java – 6544 Practical No :

Questions:

1. What is Cookies and Session ?


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

2.Difference between doGet & doPost.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

3.Advantages and Disadvantages of Cookie.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

4.List any four interface of javax.servlet.http package.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :

__________________________________________________________________________
__________________________________________________________________________

Conclusion
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No 13
Aim : Develop a simple JSP program for user login
Theory:
JSP:

• It stands for Java Server Pages.


• It is a server side technology.It is used for creating web application.
• It is used to create dynamic web content.
• In this JSP tags are used to insert JAVA code into HTML pages.
• It is an advanced version of Servlet Technology.
• It is a Web based technology helps us to create dynamic and platform independent web
pages.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into servlet by JSP container before processing the client’s request.

JSP pages are more advantageous than Servlet:

• They are easy to maintain.


• No recompilation or redeployment is required.
• JSP has access to entire API of JAVA .
• JSP are extended version of Servlet.

The Lifecycle of a JSP Page


Advance Java – 6544 Practical No :

• As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator.
• The JSP translator is a part of the web server which is responsible for translating the JSP
page into Servlet.
• After that, Servlet page is compiled by the compiler and gets converted into the class file.
• Moreover, all the processes that happen in Servlet are performed on JSP later like
initialization, committing response to the browser and destroy.

Features of JSP

• Coding in JSP is easy :-

As it is just adding JAVA code to HTML/XML.

• Reduction in the length of Code :-

In JSP we use action tags, custom tags etc.

• Connection to Database is easier :-

It is easier to connect website to database and allows to read or write data easily to the
database.

• Make Interactive websites :-

In this we can create dynamic web pages which helps user to interact in real time
environment.

• Portable, Powerful, flexible and easy to maintain :-

As these are browser and server independent.

• No Redeployment and No Re-Compilation :-

It is dynamic, secure and platform independent so no need to re-compilation.

• Extension to Servlet :-

As it has all features of servlets, implicit objects and custom tags

JSP syntax

Syntax available in JSP are following


Advance Java – 6544 Practical No :

• Declaration Tag :-It is used to declare variables.


Syntax:-
<%! Dec var %>
Example:-
<%! int var=10; %>

• Java Scriplets :- It allows us to add any number of JAVA code, variables and
expressions.
Syntax:-
<% java code %>

• JSP Expression :- It evaluates and convert the expression to a string.


Syntax:-
<%= expression %>
Example:-
<% num1 = num1+num2 %>

• JAVA Comments :- It contains the text that is added for information which has to be
ignored.
Syntax:-
<% -- JSP Comments %>

Process of Execution

Steps for Execution of JSP are following:-


• Create html page from where request will be sent to server eg try.html.
• To handle to request of user next is to create .jsp file Eg. new.jsp
• Create project folder structure.
• Create XML file eg my.xml.
• Create WAR file.
• Start Tomcat
• Run Application
Advantages of using JSP

• It does not require advanced knowledge of JAVA


• It is capable of handling exceptions
• Easy to use and learn
• It can tags which are easy to use and understand
• Implicit objects are there which reduces the length of code
• It is suitable for both JAVA and non JAVA programmer

Disadvantages of using JSP

• Difficult to debug for errors.


• First time access leads to wastage of time
Advance Java – 6544 Practical No :

• It’s output is HTML which lacks features.

Problem Statement:
Program:

1. login.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LOGIN</title>
</head>
<body>
<h1>LOGIN HERE!</h1>
<form action="login1.jsp" method="post">
User Name:<input type="text" name="userName"/><br/><br />
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

2. login1.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%
try
{
String uname=request.getParameter("userName");
out.print("<h2>Welcome "+ uname +" </h2>");
out.print("<h4>Example of JSP </h4>");
}
catch(Exception e)
{}
%>
Advance Java – 6544 Practical No :

Output:
Advance Java – 6544 Practical No :

Questions:

1. What is meant by JSP?


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

2.Enlist the lifecycle phases of JSP and explain in short.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

3.Enlist and explain JSP directives.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

4.Enlist element of JSP.


Advance Java – 6544 Practical No :

__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

5.State the advantages and disadvantages of JSP.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

Conclusion
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
_______________________________________
Advance Java – 6544 Practical No :

Practical No 14

Aim: Develop a simple JSP program to to display the grade of a student by accepting the marks
of five courses
Theory
1. JSP Implicit Object
• There is another concept of JSP, which are Java objects made available by the developers
for each page, allowing developers to call them directly without any explicit declaration.
• JSP implicit objects are essential components used in this regard. In this chapter, you will
learn how to deal with implicit objects and implement them.

Implicit Objects of JSP

• The JSP engine produces these objects during the translation phase (i.e., at the time of
translation from JSP to Servlet). They are being formed within the service method so that
JSP developers can use them directly in Scriptlet without declaration and initialization.
• There are a total of nine implicit objects supported by the JSP. These are:

1. out: javax.servlet.jsp.JspWriter
2. request: javax.servlet.http.HttpServletRequest
3. response: javax.servlet.http.HttpServletResponse
4. session: javax.servlet.http.HttpSession
5. application: javax.servlet.ServletContext
6. exception: javax.servlet.jsp.JspException
7. page: java.lang.Object
8. pageContext: javax.servlet.jsp.PageContext
9. config: javax.servlet.ServletConfig

The brief information about the implicit objects are given below:

The out Implicit Object

• An out object is an implicit object for writing data to the buffer and sending output as a
response to the client's browser.
• The out implicit object is an instance of a javax.servlet.jsp.jspWriter class.
Advance Java – 6544 Practical No :

The request Implicit Object

• A request object is an implicit object that is used to request an implicit object, which is to
receive data on a JSP page, which has been submitted by the user on the previous
JSP/HTML page.
• The request implicit object used in Java is an instance of
a javax.servlet.http.HttpServletRequest interface where a client requests a page every
time the JSP engine has to create a new object for characterizing that request.
• The container creates it for every request.
• It is used to request information such as parameters, header information, server names,
cookies, and HTTP methods.
• It uses the getParameter() method to access the request parameter.

The response Implicit Object

• A response object is an implicit object implemented to modify or deal with the reply sent to
the client (i.e., browser) after processing the request, such as redirect responding to another
resource or an error sent to a client.
• The response implicit object is an instance of
a javax.servlet.http.HttpServletResponse interface.
• The container creates it for every request.

The session Implicit Object

• A session object is the most commonly used implicit object implemented to store user data
to make it available on other JSP pages until the user's session is active.
• The session implicit object is an instance of a javax.servlet.http.HttpSession interface.
• This session object has different session methods to manage data within the session scope.

The application Implicit Object

• An application object is another implicit object implemented to initialize application-


wide parameters and maintain functional data throughout the JSP application.

The exception Implicit Object

• An exception implicit object is implemented to handle exceptions to display error


messages.
• The exception implicit object is an instance of the java.lang.Throwable class.
• It is only available for JSP pages, with the isErrorPage value set as "True". This means
Exception objects can only be used in error pages.
Advance Java – 6544 Practical No :

The page Implicit Object

• A page object is an implicit object that is referenced to the current instance of the servlet.
You can use it instead. Covering it specifically is hardly ever used and not a valuable
implicit object while building a JSP application.
The config Implicit Object
• A config object is a configuration object of a servlet that is mainly used to access and
receive configuration information such as servlet context, servlet name, configuration
parameters, etc.
• It uses various methods used to fetch configuration information.

2. JSP Directives
• Directives supply directions and messages to a JSP container. The directives provide
global information about the entire page of JSP. Hence, they are an essential part of the
JSP code.
• These special instructions are used for translating JSP to servlet code. In this chapter, you
will learn about the different components of directives in detail.
• In JSP's life cycle phase, the code must be converted to a servlet that deals with the
translation phase.
• They provide commands or directions to the container on how to deal with and manage
certain JSP processing portions. Directives can contain several attributes that are
separated by a comma and act as key-value pairs. In JSP, directives are described with a
pair of <%@ ..... %> tags.
• The syntax of Directives looks like:
<%@ directive attribute="" %>

There are 3 types of directives:

1. Page directive
2. Include directive
3. Taglib directive

Page Directive

• The page directive is used for defining attributes that can be applied to a complete JSP
page. You may place your code for Page Directives anywhere within your JSP page.
Advance Java – 6544 Practical No :

• However, in general, page directives are implied at the top of your JSP page.
• The basic syntax of the page directive is:
<%@ page attribute = "attribute_value" %>
• The XML equivalent for the above derivation is:
<jsp:directive.page attribute = "attribute_value" />

The attributes used by the Page directives are:

1. buffer: Buffer attribute sets the buffer size in KB to control the JSP page's output.
2. contentType: The ContentType attribute defines the document's MIME (Multipurpose Internet
Mail Extension) in the HTTP response header.
3. autoFlush: The autofill attribute controls the behavior of the servlet output buffer. It monitors
the buffer output and specifies whether the filled buffer output should be flushed automatically
or an exception should be raised to indicate buffer overflow.
4. errorPage: Defining the "ErrorPage" attribute is the correct way to handle JSP errors. If an
exception occurs on the current page, it will be redirected to the error page.
5. extends: extends attribute used for specifying a superclass that tells whether the generated
servlet has to extend or not.
6. import: The import attribute is used to specify a list of packages or classes used in JSP code,
just as Java's import statement does in a Java code.
7. isErrorPage: This "isErrorPage" attribute of the Page directive is used to specify that the
current page can be displayed as an error page.
8. info: This "info" attribute sets the JSP page information, which is later obtained using
the getServletInfo() method of the servlet interface.
9. isThreadSafe: Both the servlet and JSP are multithreaded. If you want to control JSP page
behavior and define the threading model, you can use the "isThreadSafe" attribute of the page
directive.
10. Language: The language attribute specifies the programming language used in the JSP page.
The default value of the language attribute is "Java".
11. Session: In JSP, the page directive session attribute specifies whether the current JSP page
participates in the current HTTP session.
12. isELIgnored: This isELIgnored attribute is used to specify whether the expression language
(EL) implied by the JSP page will be ignored.
13. isScriptingEnabled: This "isScriptingEnabled" attribute determines if the scripting elements
are allowed for use or not.

Include Directive
Advance Java – 6544 Practical No :

• The JSP "include directive" is used to include one file in another JSP file.
• This includes HTML, JSP, text, and other files. This directive is also used to create
templates according to the developer's requirement and breaks the pages in the header,
footer, and sidebar.
• To use this Include Directive, you have to write it like:
<%@ include file = "relative url" >
• The XML equivalent of the above way of representation is:
<jsp:directive.include file = "relative url" />

Taglib Directive

• The JSP taglib directive is implemented to define a tag library with "taglib" as its prefix.
Custom tag sections of JSP use taglib. JSP's taglibdirective is used as standard tag
libraries.
• To implement taglib, you have to write it like this:
<%@ taglib uri="uri" prefix="value"%>

3. JSP Action

• It is necessary to control the servlet engine's behavior, which can be controlled


dynamically by inserting the file by reusing the JavaBeans components or redirecting or
forwarding the user to another page., i.e., by forwarding the request to another resource,
which will possibly be a JSP, HTML, or other resources.

Actions Tags

• The JSP specification provides a standard tag called Action tag used within JSP code and
is used to remove or eliminate Scriptlet code from your JSP code as JSP Scriptlets are
obsolete and are not considered nowadays.
• There are many JSP action tags or elements, and each of them has its own uses and
characteristics. Each JSP action tag is implemented to perform some precise tasks.
• The action tag is also implemented to streamline flow between pages and to employ a
Java Bean. As it coincides with the XML standard, the syntax for the action element is:
• Syntax:
<jsp:action_name attribute = "attribute_value" />

Here is the list of JSP Actions:


Advance Java – 6544 Practical No :

1. jsp:forward: is used for forwarding the request and response to other resources.
2. jsp:include: is used for including another resource.
3. jsp:body: is used for defining dynamically-defined body of XML element.
4. jsp:useBean: is used for creating or locating bean objects.
5. jsp:setProperty: is used for setting the value of property in the bean object.
6. jsp:getProperty: is used for printing the value of the property of the bean.
7. jsp:element: is used for defining XML elements dynamically.
8. jsp:plugin: is used for embedding other components (applets).
9. jsp:param: is used for setting the parameter for (forward or include) value.
10. jsp:text: is used for writing template text in JSP pages and documents.
11. jsp:fallback: is used for printing the message if plugins are working.
12. jsp:attribute: is used for defining attributes of dynamically-defined XML element.

4. JSP Expressions
• Expression tags are one of the most useful scripting elements of JSP. Expression tags use
special tags to print the different java expressions and output directly on the client-side.
• You can also use this for displaying information on your client browser.

What is Expression Tag?


• The expression tag is used to evaluate Java's expression within the JSP, which then
converts the result into a string and forwards the result back to the client browser via the
response object.
• Essentially, it is implemented for printing the result to the client (browser). An expression
tag can hold any java language expression that can be employed as an argument to the
out.print() method.
Expression of Values
In this case, you have to pass the expression of values within the expression tag.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example1</title>
</head>
<body>
<%= 2+4*5 %>
Advance Java – 6544 Practical No :

</body>
</html>

Expression of Variables

In this case, you have to initialize a few variables, which can then be passed as the expression of
variables within the expression tag in order to evaluate the result.
Example:

<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>
<% int g = 60; int k = 40; int r = 20; %>
<%= g+k+r %>
</body>
</html>

Difference Between Scriptlet Tag and Expression Tag

• In Scriptlet tag, it evaluates your Java expression but does not print or show your result in
conjunction with the HTML created. The declared variables have a local scope only and
hence can't take access from another place in the .jsp. In contrast, the Expression Tag has
the capability to evaluate the Java expression. It is used for inserting the result in the form
of a string in conjunction with the HTML in the JSP.
• You don't have to write the out.println in the expression tag to print the expression based
output because these are changed into out.print() statement (as shown above the process
of transformation of expression), which gets inserted by the container in
the _jspService(-, -) of the servlet class.
Advance Java – 6544 Practical No :

5. JSTL:

• The JSP library has a collection of useful JSP tags, responsible and functionally capable
of encapsulating the core utilities typically found in a JSP application. JSTL, known
as JSP Standard Tag Library, is a set of tags.
• This helps make coding in JSP much easier and simplifies the JSP development process.
In this lesson, you will learn how to start using this JSP standard library and its various
methods and tags.

Advantages of JSTL

• Neat and Clean Coding approach: Since scripts confuse developers a bit, their usage
can be replaced with JSTL, making coding easier.
• Standard Tag: JSTL provides an affluent layer of manageable functionality in your JSP
pages. This makes the JSP code easier to understand.
• Automatic Support of Javabeans Introspection: It is also beneficial to use JSTL over
JSP's normal scriptlet. The JSTL Expression language is efficient in handling JavaBean
code. Downcasting of objects is not required, which can also be retrieved as scoped
attributes. JSP scriptlet generates a range of complicated codes, but JSTL has cut down to
ease that.
• Easy for computers to understand: There are applications like Dreamweaver and front
page, which generate more and more HTML code. In such tools, the HTML code gets
mixed with the JSP scriptlet code in the back end of the development. However, since
JSTL is expressed as an XML yielding tag, it becomes easy for HTML generation in
parsing these JSTL codes without many hurdles within your document code.
• Easier for humans to read: JSTL is XML based custom tags similar to that of HTML.
Hence, this makes it easy for developers to read and understand.

Tag Categories in JSTL

There are mainly five categories of JSTL tags under the standard tag library of JSP:

1. Core tags: Core tags have variable support, flow control, URL management, etc. The URL
used in the core tag is http://java.sun.com/jsp/jstl/core. These tags are prefixed with a
'c' followed by a colon and then the tag name.
2. Function tags: Function tags holds a collection of standard function. The URL used in this
function tag is http://java.sun.com/jsp/jstl/functions. These tags are prefixed by an 'fn' followed
by a colon.
3. Formatting tags: Formatting tags give support to format the messages, numbers, and dates,
etc. Its URL is http://java.sun.com/jsp/jstl/fmt. It is prefixed with a 'fmt' followed by a colon.
Advance Java – 6544 Practical No :

4. XML tags: XML tags offer a flow control mechanism, transformation, and some other
features. Its URL is http://java.sun.com/jsp/jstl/xml. It is prefixed with a 'x' followed by
a colon.
5. SQL Tags: SQL Tags offers SQL support. The URL is http://java.sun.com/jsp/jstl/sql. It is
prefixed with a 'SQL' followed by a colon.
Advance Java – 6544 Practical No :

Problem Statement: Develop a simple JSP program to to display the grade of a student by
accepting the marks of five courses.

Program:

1. pr14.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MARKSHEET</title>
</head>
<body>
<h1 align="center">STUDENT MARKSHEET</h1>
<form action="pr1.jsp" method="">
Student Name:<input type="text" name="userName"/><br/><br />
Enter marks of ADJ:<input type="number" name="n1"/><br/><br />
Enter marks of PHP:<input type="number" name="n2"/><br/><br />
Enter marks of ASP.NET:<input type="number" name="n3"/><br/><br />
Enter marks of LINUX:<input type="number" name="n4"/><br/><br />
Enter marks of EDP:<input type="number" name="n5"/><br/><br />
<input type="submit" value="submit"/>
</form>
</body>
</html>

2. pr1.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FINAL GRADE</title>
</head>
<body>
<h3>
<%
String uname=request.getParameter("userName");
out.print("<h2>Welcome "+ uname +" </h2>");
int java=Integer.parseInt(request.getParameter("n1"));
int php=Integer.parseInt(request.getParameter("n2"));
int asp=Integer.parseInt(request.getParameter("n3"));
int los=Integer.parseInt(request.getParameter("n4"));
Advance Java – 6544 Practical No :

int edp=Integer.parseInt(request.getParameter("n5"));
int total=java+asp+los+edp+php;
float per=total/5;
%>
Total marks:<%=total %>
<br>
Percentage:<%=per %>

</h3 >
<%
char grade;
if(per>=90)
grade='A';
else if(per<=90&&per>=75)
grade='B';
else if(per<=75&&per>=60)
grade='C';
else if(per<=60&&per>=35)
grade='D';
else
grade='F';

%>
<h3>Grade: <%=grade%></h3>
</body>
</html>
Advance Java – 6544 Practical No :

Output:
Advance Java – 6544 Practical No :

Questions:

1. What are Implient Objects ? Enlist its advantages.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

2.What are the various attributes of page directives.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

3.Explain directives of JSP.


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

4.What is difference between JSP include action and include directive?


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :

__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

5.What is JSP Page Redirection ?


__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

Conclusion
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :

Practical No.15
Title : Mini Project
PROJECT TOPIC: ONLINE RECRUITMENT
SYSTEM

Introduction:
This project Online Recruitment System is an online website in which jobseekers can register
themselves online and apply for job. Online Recruitment System provides online help to the
users all over the world. Using web recruitment systems like recruitment websites or jobsites
also play a role in simplifying the recruitment process. Such websites have facilities where
prospective candidates can upload their CV's and apply for jobs suited to them. Such sites
also make it possible for recruiters and companies to post their staffing requirements and view
profiles of interested candidates.

Existing System
Presently recruitment is done manually. That is if a company or organization needs
employees they make an announcement through newspaper. People who are eligible send
application to the organization or company. From these applications they are called for
interviews or tests. After tests company has to do short listing manually. From these
shortlisted candidates, they are called for interviews. After interview short listed candidates
are employed. So it's all a time consuming procedure.

Proposed System
This project Online Recruitment System is an online website in which jobseekers can
register themselves.People all around the world can apply and register. It has made all the
process easy.
Advance Java – 6544 Practical No :

Hardware requirements
➢ Processor Speed : 2ghz.
➢ Coprocessor : Built In
➢ Total Ram: 128 Mb
➢ Diskette A: 1.44 Mb Floppy 3.5".
➢ Hard Disk:40 Gb

Software requirements

➢ Front End J2EE

➢ Operating System Windows Xp/2007

➢ Back End My SQL

Modules
➢ Jobseeker: A jobseeker can register himself. After registration, he will be directed to his
homepage. Here he can update his profile, change password and see the examination
details and all.

➢ Jobprovider: A company can register itself, conduct online examination, approve or


disapprove candidates attending examination and provides results about the selected
candidates.

Environment
➢ Operating System: Windows 7 or later version

➢ Data Base Server: MY SOL

➢ Clients: Windows 7 or later version

➢ User Interface: 12EE

➢ Code Behind: JAVA


Advance Java – 6544 Practical No :

You might also like