ADJ Manual
ADJ Manual
ADVANCE JAVA
PROGRAMMING (ADJ) (6544)
EVEN SEMESTER- VI
DIPLOMA PROGRAMME IN
INFORMATION TECHNOLOGY
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)
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
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.
CERTIFICATE
Engineering has completed the term work in subject Advance Java Programming (ADJ)
(6544) for academic year 20 to 20 as prescribed in curriculum.
Sign:
Name of Student:
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
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
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:
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 :
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.
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 :
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 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);
Output:
Advance Java – 6544 Practical No :
Questions:
1. What is AWT ?
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
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:
Field:
Class constructors:
1
EventObject(Object source)
Constructs a prototypical Event.
Class methods:
1
Object getSource()
The object on which the Event initially occurred.
2
String toString()
Returns a String representation of this EventObject.
Event Classes:
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:
Class declaration:
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>
*/
TextField input;
Panel p1;
String btnS[]={"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"C", "0", "=", "/"};
addWindowListener(new WindowAdapter(){
}
});}
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:
____________________________________________________________________________
____________________________________________________________________________
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:
1
MenuBar()
Creates a new menu bar.
Class methods
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:
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 :
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:
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:
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 menubar03() {
initComponents();
setSize(600,600);
}
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 :
Questions:
1.What is DialogBox ?
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
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:
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 :
Program:
import javax.swing.*;
JFrame f;
public PR04(){
f=new JFrame("ComboBox");
String list[]={"CRICKET","FOOTBALL","HOCKEY","TENNIS"};
cb.setBounds(150, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
new PR04();
} }
Output:
Advance Java – 6544 Practical No :
Advance Java – 6544 Practical No :
Questions:
____________________________________________________________________________
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.
• Constructors of JTree:
Constructor Description
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:
• Constructors of JTable:
Constructor Description
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
• Functions in JTable :
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
Problem Statement:
Program:
import javax.swing.*;
/**
*/
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
*/
@SuppressWarnings("unchecked")
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");
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)
javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
202, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(44, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
*/
Advance Java – 6544 Practical No :
//<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.
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
java.util.logging.Logger.getLogger(JFrame01.class.getName()).log(java.util.logging.Level.
java.util.logging.Logger.getLogger(JFrame01.class.getName()).log(java.util.logging.Level.
java.util.logging.Logger.getLogger(JFrame01.class.getName()).log(java.util.logging.Level.
java.util.logging.Logger.getLogger(JFrame01.class.getName()).log(java.util.logging.Level.
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
new JFrame01().setVisible(true);
}); }
Output:
Program:
/**
*/
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
*/
@SuppressWarnings("unchecked")
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setBorder(new javax.swing.border.MatteBorder(null));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
},
new String [] {
){
java.lang.Integer.class
};
});
jScrollPane1.setViewportView(jTable1);
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)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
Advance Java – 6544 Practical No :
.addComponent(jLabel1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
255, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
/**
*/
//<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.
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
Advance Java – 6544 Practical No :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
java.util.logging.Logger.getLogger(Jtable01.class.getName()).log(java.util.logging.Level.S
java.util.logging.Logger.getLogger(Jtable01.class.getName()).log(java.util.logging.Level.S
java.util.logging.Logger.getLogger(Jtable01.class.getName()).log(java.util.logging.Level.S
java.util.logging.Logger.getLogger(Jtable01.class.getName()).log(java.util.logging.Level.S
java.awt.EventQueue.invokeLater(new Runnable() {
new Jtable01().setVisible(true);
} }); }
Output:
Advance Java – 6544 Practical No :
Questions:
____________________________________________________________________________
____________________________________________________________________________
Conclusion
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Advance Java – 6544 Practical No :
Practical No. 06
Title : Write a program making use of Adapter class.
Theory:
Adapter Class:
• When you inherit the adapter class implementation for all methods is not mandatory.
Thus writing excess code is saved.
• 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.
➢ 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
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.
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
3. javax.swing.event
• 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.
Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
Questions:
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 :
• 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.
• 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.
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.
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 :
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:
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:
• 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.
1 Attempts to create a server socket bound to the specified port. An exception occurs if the
port is already bound by another application.
2 Similar to the previous constructor, the backlog parameter specifies how many incoming
clients to store in a wait queue.
4 Creates an unbound server socket. When using this constructor, use the bind() method
when you are ready to bind the server socket.
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.
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.
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.
• 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 −
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()
5
Creates an unconnected socket. Use the connect() method to connect this socket to a server.
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.
7 Returns the output stream of the socket. The output stream is connected to the input stream
of the remote socket.
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;
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:
3.List the methods use for TCP/IP based communication between client and server.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
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.
• 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
Before establishing connection, let's first create a table in oracle database. Following is the SQL
query to create a table.
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
Advance Java – 6544 Practical No :
}
}
Advance Java – 6544 Practical No :
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 ?
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Conclusion
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :
Practical No. 10
Title: Write an Application program/Applet to send queries through JDBC Bridge & handle
result.
Theory:
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 :
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:
2.What are the advantages and disadvantages of JDBC – ODBC bridge driver ?
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
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:
Servlets Tasks:
• 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:
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
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 {
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 ?
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
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:
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.
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
Persistent cookie
Advantage of Cookies
Disadvantage of Cookies
Cookie class
Constructor Description
Cookie(String name, String value) constructs a cookie with a specified name and value.
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.
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.
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
1. bind objects
2. View and manipulate information about a session, such as the session identifier, creation
time, and last accessed time.
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.
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.
• 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">
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.
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 :
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.*;
3. myserv2.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
//Reading cookies
Cookie c[]=request.getCookies();
//Displaying User name value from cookie
pwriter.print("<h2>RETRIVING COOKIES</h2>");
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:
__________________________________________________________________________
__________________________________________________________________________
Conclusion
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
Advance Java – 6544 Practical No :
Practical No 13
Aim : Develop a simple JSP program for user login
Theory:
JSP:
• 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
It is easier to connect website to database and allows to read or write data easily to the
database.
In this we can create dynamic web pages which helps user to interact in real time
environment.
• Extension to Servlet :-
JSP syntax
• Java Scriplets :- It allows us to add any number of JAVA code, variables and
expressions.
Syntax:-
<% java code %>
• JAVA Comments :- It contains the text that is added for information which has to be
ignored.
Syntax:-
<% -- JSP Comments %>
Process of Execution
Problem Statement:
Program:
1. login.jsp:
2. login1.jsp:
Output:
Advance Java – 6544 Practical No :
Questions:
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
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.
• 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:
• 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 :
• 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.
• 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.
• 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.
• 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="" %>
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" />
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
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" />
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.
</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>
• 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.
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:
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:
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
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
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.
Environment
➢ Operating System: Windows 7 or later version