Professional Documents
Culture Documents
of Contents
Advanced JAVA Laboratory Manual
Unit 1
Introduction
Practical 1: Write an applet that draws a circle. The dimension of
the applet should be 500 x 300 pixels. The circle should be
centered in the applet and have a radius of 100 pixels. Display
your name centered in a circle. (USING DRAWOVAL ()
method)
Practical 2: Draw ten red circles in a vertical column in the center
of the applet.
Practical 3: Built an applet that displays a horizontal rectangle in
its center. Let the rectangle fill with color from left to right.
Practical 4: Write an applet that displays the position of the
mouse at the upper left corner of the applet when it is dragged or
moved. Draw a 10x10 pixel rectangle filed with black at the
current mouse position.
Practical 5: Write an applet that contains one button. Initialize the
label on the button to “start”, when the user presses the button
change the label between these two values each time the button is
pressed.
Practical 6: Write an applet that uses the mouse listener, which
overrides only two methods which are mouse Pressed and
mouseReleased.
Exercise:
Unit 2
Introduction
Practical 7: Write a program that has only one button in the
frame, clicking on the button cycles through the colors: red-
>green->blue->and so on. One color change per click. (use
getBackGround() method to get the current color)
Practical 8: Write an applet that contains three check boxes and
30 x 30 pixel canvas. The three checkboxes should be labeled
“Red”,”Green”,”Blue”. The selection of the check boxes
determines the color of the canvas. For example, if the user
selects both “Red” and “Blue”, the canvas should be purple.
Practical 9: Create an application that displays a frame with a
menubar. When a user selects any menu or menu item, display
that selection on a text area in the center of the frame
Practical 10: Write an applet that draws two sets of ever-
decreasing rectangles one in outline form and one filled
alternately in black and white.
Exercise:
Unit 3
Introduction
Practical 11: Write a database application that uses any JDBC
driver.
Practical 12: Develop a UI that performs the following SQL
operations:1) Insert 2)Delete 3)Update.
Practical 13: Write a program to present a set of choice for user to
select a product & display the price of product.
Exercise:
Unit 4
Introduction
Practical 14: Write a simple servlet program which maintains a
counter for the number of times it has been accessed since IT’S
loading; initialize the counter using deployment descriptor.
Practical 15: Create a form processing servlet which demonstrates
use of cookies.
Practical 16: Create a form processing servlet which demonstrates
use of sessions.
Unit 5
Introduction
Practical 17: WRITE a simple JSP program for user Registration
& then control will be transfer it into second page.
Practical 18 :Write a simple JSP program for user login form with
static & dynamic database.
Practical 19 :Write a JSP program to display the grade of a
student by accepting the marks of five subjects.
L EARNING O UTCOMES
Explain & Practice Graphic Drawing Applications using Applets.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
INTRODUCTION
What is an Applet?
According to Sun “An applet is a small program that is intended not to be
run on its own, but rather to be embedded inside another application….The
Applet class provides a standard interface between applets and their
environment.”
TestApplet.html
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE> </HEAD>
<BODY>
<APPLET code=“TestApplet.class” width=350 height=200></APPLET>
</BODY>
</HTML>
The import statements direct the Java compiler to include the
java.applet.Applet and java.awt.Graphics classes in the compilation. The import
statement allows these classes to be referenced in the source code using the
simple class name (i.e. Applet) instead of the fully qualified class name (i.e.
java.applet.Applet).
The Applet class provides the framework for the host application to display
and control the lifecycle of the applet. The Applet class is an Abstract
Windowing Toolkit (AWT) Component, which provides the applet with the
capability to display a graphical user interface (GUI) and respond to user events.
/*
Method Description
Example:
import java.applet.*;
import java.awt.*;
import java.net.*;
/*
*/
String arg;
public void start( ) {
arg=getParameter(“first”);
Output:
* AppletWithPara.java
*/
import java.applet.*;
import java.awt.*;
/*
Output:
drawLine (int x1, int y1, int x2, int y2); To draw a line at specific
location.
fillOval ( int x, int y, int width, int height To fill color in Oval
)
fillRect ( int x, int y, int width, int height To fill color in rectangle
)
fillArc (int x, int y, int width, int height, To fill color in Arc.
int arcwidth, int archeight )
Drawing Lines
Drawing straight lines with Java is easy. Just call g.drawLine(x1, y1, x2, y2)
where (x1, y1) and (x2, y2) are the endpoints of your lines and g is the
Graphics object you’re drawing with.
This program draws a line diagonally across the applet.
import java.applet.*; import java.awt.*;
Output
Drawing Rectangles
Drawing rectangles is simple. Start with a Graphics object g and call its
drawRect() method: public void drawRect(int x, int y, int width, int height) As
the variable names suggest, the first int is the left hand side of the rectangle, the
second is the top of the rectangle, the third is the width and the fourth is the
height. This is in contrast to some APIs where the four sides of the rectangle are
given.
This uses drawRect() to draw a rectangle around the sides of an applet.
import java.applet.*; import java.awt.*;
Output
Remember that getSize().width is the width of the applet and getSize().height
is its height.
Why was the rectangle drawn only to getSize().height-1 and
getSize().width-1?
Remember that the upper left hand corner of the applet starts at (0, 0), not at
(1, 1). This means that a 100 by 200 pixel applet includes the points with x
coordinates between 0 and 99, not between 0 and 100. Similarly the y
coordinates are between 0 and 199 inclusive, not 0 and 200.
Filling Rectangles
The drawRect() method draws an open rectangle, a box if you prefer. If you
want to draw a filled rectangle, use the fillRect() method. Otherwise the syntax
is identical.
This program draws a filled square in the center of the applet. This requires
you to separate the applet width and height from the rectangle width and height.
Here’s the code: import java.applet.*; import java.awt.*;
Output
import java.awt.*;
Output
Black 0 0 0
Red 255 0 0
Green 0 255 0
Blue 0 0 255
To change colors you change the color of your Graphics object. Then
everything you draw from that point forward will be in the new color until you
change it again.
When an applet starts running the color is set to black by default. You can
change this to red by calling g.setColor(Color.red). You can change it back to
black by calling g.setColor(Color.black). The following code fragment shows
how you’d draw a pink String followed by a green one: g.setColor(Color.pink);
g.drawString(“This String is pink!”, 50, 25); g.setColor(Color.green);
g.drawString(“This String is green!”, 50, 50); Example: AppletColor.java
import java.applet.*;
import java.awt.*;
/*
*/
c1=c1.darker( );
g.setColor(c1);
g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE =
“+b,10,40);
g.setColor(c2);
Output:
Fonts
You’ve already seen one example of drawing text in the HelloWorldApplet
program of the last chapter. You call the drawString() method of the Graphics
object. This method is passed the String you want to draw as well as an x and y
coordinate. If g is a Graphics object, then the syntax is g.drawString(String s, int
x, int y)
The String is simply the text you want to draw. The two integers are the x
and y coordinates of the lower left-hand corner of the String. The String will be
drawn above and to the right of this point. However letters with descenders like
y and p may have their descenders drawn below the line.
Until now all the applets have used the default font, probably some variation
of Helvetica though this is platform dependent. However unlike HTML Java
does allow you to choose your fonts. Java implementations are guaranteed to
have a serif font like Times that can be accessed with the name “Serif”, a
monospaced font like courier that can be accessed with the name “Mono”, and a
sans serif font like Helvetica that can be accessed with the name “SansSerif”.
The following applet lists the fonts available on the system it’s running on. It
does this by using the getFontList() method from java.awt.Toolkit. This method
returns an array of strings containing the names of the available fonts. These
may or may not be the same as the fonts installed on your system. It’s
implementation dependent whether or not all the fonts a system has are available
to the applet.
import java.awt.*;
import java.applet.*;
public class FontList extends Applet {
Output
Drawing Graphics
Example: GraphicsDemo.java import java.awt.*;
import java.applet.*;
/*<applet code=“GraphicsDemo” width=400 height=400> </applet>*/
setBackground(Color.pink);
setForeground(Color.blue);
Font f=new Font(“Arial”,Font.ITALIC,10);
g.setFont(f);
g.drawLine(20,20,50,50);
g.drawString(“Line”,20,70);
g.drawRect(100,20,50,50);
g.drawString(“Rectangle”,100,100);
g.fillRoundRect(200,20,80,50,10,10);
g.drawString(“Oval”,25,200);
g.fillOval(100,130,50,50);
g.drawString(“Circle”,110,200);
g.drawString(“WELCOME TO GRAPHICS”,130,350); }
Output:
import java.awt.*;
import java.applet.*;
/*
*/
int w,h;
public void init()
w=getWidth();
h=getHeight();
O UTPUT
S PECIFIC O BJECTIVES
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop an Applet Program in JAVA
Execute an Applet Program in JAVA using Appletviewer or web
browser
Learn How to use Graphics Class to draw Circle.
L EARNING O UTCOMES
Explain & Practice Graphic Drawing method drawOval () to draw
circles pattern and setColor() to fill Circle.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
C ODE
import java.awt.*;
import java.applet.*;
/*
*/
int w,h;
public void init()
{
w=getWidth();
h=getHeight();
int count=0;
g.setColor (Color.red);
for(int i=h;i>0;i=i-50)
g.fillOval(w/2-25,h-i,50,50);
count++;
if (count==10) break;
Output
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop an Applet Program in JAVA
Execute an Applet Program in JAVA using Appletviewer or web
browser
Learn How to use Graphics Class to draw and fill Rectangles.
L EARNING O UTCOMES
Explain & Practice Graphic Drawing method drawRect() and
fillRect() to create Progress bar.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
C ODE
import java.awt.*;
import java.applet.*;
/*
*/
w=getWidth();
h=getHeight();
g.setColor(java.awt.Color.red); g.drawRect(100,50,300,150);
for(x2=100;x2<=300;x2=x2+2)
try{
Thread.sleep(1000);
g.fillRect(x1,y1,x2,y2);
} catch(Exception e)
{}
O UTPUT
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop an Applet Program in JAVA
Execute an Applet Program in JAVA using Appletviewer or web
browser
Learn How to handle Mouse Events using MouseListener and
MouseMotionListeners interfaces.
L EARNING O UTCOMES
Explain & Practice Mouse Events like Move, Drag and Current
Position using init(), repaint() methods.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
C ODE
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
/*
*/
}
}
mx=m.getX( );
my=m.getY( );
s=“Dragging:”;
repaint( );
mx=m.getX( );
my=m.getY( );
s=“Moving:”;
repaint( );
}
}
O UTPUT :
When Moving When Dragging
PRACTICAL 5: WRITE AN APPLET THAT CONTAINS ONE
BUTTON. INITIALIZE THE LABEL ON THE BUTTON TO “START”,
WHEN THE USER PRESSES THE BUTTON CHANGE THE LABEL
BETWEEN THESE TWO VALUES EACH TIME THE BUTTON IS
PRESSED.
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop a GUI Applet Program in JAVA using AWT Button Control
Execute an Applet Program in JAVA using Appletviewer or web
browser
Learn How to handle AWT Button Events using ActionListener
interfaces.
L EARNING O UTCOMES
Explain & Practice AWT Button Events like using actionPerformed()
methods.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
C ODE
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.lang.String;
/*<applet code=ButtonsDemo.class width=300 height=300></applet>*/
public class ButtonsDemo extends java.applet.Applet implements
ActionListener{
Button b1;
public void init()
b1=new Button(“Start”);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1)
{
String s;
s=b1.getLabel(); if(s==“Start”) b1.setLabel(“Stop”); else
b1.setLabel(“Start”); }
}
}
O UTPUT :
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop an Applet Program in JAVA
Execute an Applet Program in JAVA using Appletviewer or web
browser
Learn How to handle Mouse Events using MouseListener and
MouseMotionListeners interfaces.
L EARNING O UTCOMES
Explain & Practice Mouse Events like Press and Released using
mousePressed(), mousePressed() methods.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
C ODE
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
/*
<applet code=MouseState height=300 width=400> </applet>
*/
}
O UTPUT :
W RITE A N APPLET THAT DRAWS A HUMAN FACE WITH ARC AND OVAL .
Code:
Output:
Code:
Output:
UNIT 2
G ENERAL O BJECTIVES
After performing this practical student will be able to:
Learn about Windows AWT Controls.
Develop an AWT Program in JAVA
Execute an AWT Program in JAVA
Learn How to use Graphics Class to draw Shapes.
L EARNING O UTCOMES
Explain & Practice AWT Controls using Applets and Frames.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
INTRODUCTION
Abstract Window Toolkit
The AWT contains numerous classes and methods that allow us to create and
manage windows. Although the main purpose of the AWT is to support applet
windows, it can also be used to create stand-alone windows that run in a GUI
environment, such as Windows.
AWT Classes
The AWT classes are contained in the java.awt package. It is one of Java’s
largest packages. Fortunately, because it is logically organized in a top-down,
hierarchical fashion, it is easier to understand and use than you might at first
believe.
AWTEvent Encapsulates AWT
events.
AWTEventMulticaster Dispatches
events to multiple listeners.
BorderLayout The border
layout manager. Border layouts use
five components: North, South, East,
West, and Center.
Button Creates a push button
control. Canvas A blank,
semantics-free window.
CardLayout The card layout
manager. Card layouts emulate index
cards. Only the one on top is showing.
Checkbox Creates a check box
control. CheckboxGroup Creates a
group of check box controls.
CheckboxMenuItem Creates an on/off
menu item.
Choice Creates a pop-up list.
Color Manages colors in
independent fashion.
Component An abstract superclass for various
AWT components.
Container A subclass of Component that
components.
Cursor Encapsulates a bitmapped
cursor. Dialog Creates a dialog
window.
Dimension Specifies the
dimensions of an object. The width is
stored in width, and the height is stored
in height.
Event Encapsulates
events. EventQueue Queues
events.
FileDialog Creates a window from which a
file can be selected. FlowLayout
The flow layout manager. Flow layout
components left to right, top to bottom.
Font Encapsulates a type font.
FontMetrics Encapsulates
various information related to a font.
This information helps you display text
in a window.
Frame Creates a standard
window that has a title bar, resize
corners, and a menu bar.
Graphics Encapsulates the
graphics context. This context is used
by the various output methods to
display output in a window.
GraphicsDevice Describes a
graphics device such as a screen or
printer.
GraphicsEnvironment Describes the
collection of available Font and
GraphicsDevice objects.
GridBagConstraints Defines various constraints
GridBagLayout class.
GridBagLayout The grid bag
layout manager. Grid bag layout
displays
components subject to the
constraints specified by
GridBagConstraints.
GridLayout The grid layout
components in a two-dimensional grid.
Image Encapsulates graphical images.
Insets Encapsulates the borders of a
container. Label Creates a label that
displays a string.
List Creates a list from which
the user can choose. Similar to the
standard Windows list box.
MediaTracker Manages
media objects. Menu Creates a
pull-down menu.
MenuBar Creates a menu bar.
MenuComponent An abstract class implemented
by various menu classes. MenuItem Creates a menu
item.
MenuShortcut Encapsulates a keyboard
shortcut for a menu item. Panel The simplest
concrete subclass of Container.
Point Encapsulates a Cartesian coordinate pair,
stored in x
and y.
Polygon Encapsulates a
polygon.
PopupMenu Encapsulates a pop-
up menu.
PrintJob An abstract class that
represents a print job.
Rectangle Encapsulates a rectangle.
Robot Supports automated testing of AWT-based
applications. Scrollbar Creates a scroll bar control.
ScrollPane A container that
provides horizontal and/or vertical
scroll bars for another component.
SystemColor Contains the
colors of GUI widgets such as
windows, scroll bars, text, and others.
TextArea Creates a multiline edit
control. TextComponent A superclass
for TextArea and TextField.
TextField Creates a single-line edit
control.
Toolkit Abstract class
implemented by the AWT.
Window Creates a window with no
frame, no menu bar,
Window Fundamentals
The AWT defines windows according to a class hierarchy that adds
functionality and specificity with each level. The two most common windows
are those derived from Panel, which is used by applets, and those derived from
Frame, which creates a standard window. Much of the functionality of these
windows is derived from their parent classes. Thus, a description of the class
hierarchies relating to these two classes is fundamental to their understanding.
Figure below shows the class hierarchy for Panel and Frame.
/*
*/
SampleFrame(String title)
{
super(title);
Frame f;
public void init()
f.setVisible(true);
{
{
f.setVisible(false);
Output:
Labels
Label defines the following constructors:
Label( ) ;
Label(String str) ;
Label(String str, int how);
We can set or change the text in a label by using the setText( ) method. We
can obtain the current label by calling getText( ). These methods are shown here:
void setText(String str) ;
String getText( );
To obtain the current alignment, call getAlignment( ). The methods are as
follows:
void setAlignment(int how);
int getAlignment( );
Example: The following example creates three labels and adds them to an
applet.
// Demonstrate Labels. LabelDemo.java
import java.awt.*; import java.applet.*;
/*
*/
Output:
Buttons
The most widely used control is the push button. A push button is a
component that contains a label and that generates an event when it is
pressed. Push buttons are objects of type Button. Button defines these two
constructors:
Button( );
Button(String str);
Example: Using button control
//ButtonDemo.java
import java.awt.*;
import java.applet.*;
/*
<applet code=“ButtonDemo” width=250 height=150>
</applet>
*/
g.drawString(msg, 6, 100);
Output:
Check Boxes
A check box is a control that is used to turn an option on or off. Check boxes
can be used individually or as part of a group. Check boxes are objects of the
Checkbox class. Checkbox supports these constructors:
Checkbox( );
Checkbox(String str);
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup);
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
The first form creates a check box whose label is initially blank. The state of
the check box is unchecked.
The second form creates a check box whose label is specified by str. The
state of the check box is unchecked.
The third form allows us to set the initial state of the check box. If on is true,
the check box is initially checked; otherwise, it is cleared.
The fourth and fifth forms create a check box whose label is specified by str
and whose group is specified by cbGroup. If this check box is not part of a
group, then cbGroup must be null. The value of on determines the initial state of
the check box.
In order to retrieve the current state of a check box, call getState( ). For
setting its state, call setState( ). We can obtain the current label associated with a
check box by calling getLabel( ). For setting the label, setLabel( ) is used. These
methods are as follows:
boolean getState( );
void setState(boolean on);
String getLabel( );
void setLabel(String str);
Example: Demonstrate check boxes.
//CheckboxDemo.java
import java.awt.*;
import java.applet.*;
/*
*/
Output:
/*
*/
Output:
Choice Controls
The Choice class is used to create a pop-up list of items from which the user
may choose. Choice only defines the default constructor, which creates an empty
list. In order to add a selection to the list, add( ) is used. It has this general form:
void add(String name)
Here, name is the name of the item being added. In order to determine which
item is currently selected, we may call either any of the following methods:
String getSelectedItem( );
int getSelectedIndex( );
The getSelectedItem( ) method returns a string containing the name of the
item. getSelectedIndex( ) returns the index of the item. The first item is at index
0. By default, the first item added to the list is selected. For obtaining the number
of items in the list, call getItemCount( ). We can set the currently selected item
using the select( ) method with either a zero-based integer index or a string that
will match a name in the list. These methods are shown here:
int getItemCount( );
void select(int index);
void select(String name);
Given an index, we can obtain the name associated with the item at that
index by calling getItem( ), which has this general form:
String getItem(int index);
Example: Demonstrate Choice lists.
//ChoiceDemo.java
import java.awt.*;
import java.applet.*;
/*
*/
{
Choice os, browser; String msg = ””;
public void init()
os = new Choice();
browser = new Choice();
os.add(“Windows 98/XP”); os.add(“Windows NT/2000”);
os.add(“Solaris”); os.add(“MacOS”); browser.add(“Netscape 3.x”);
browser.add(“Netscape 4.x”); browser.add(“Netscape 5.x”);
browser.add(“Netscape 6.x”);
browser.add(“Internet Explorer 4.0”); browser.add(“Internet Explorer
5.0”); browser.add(“Internet Explorer 6.0”); browser.add(“Lynx 2.4”);
browser.select(“Netscape 4.x”);
add(os);
add(browser);
Output:
Lists
The List class provides a compact, multiple-choice, scrolling selection list.
The List object can be constructed to show any number of choices in the visible
Window. It can also be created to allow multiple selections. List provides these
constructors:
List( );
List(int numRows);
List(int numRows, boolean multipleSelect);
The first version creates a List control that allows only one item to be
selected at any one time. In the second form, the value of numRows specifies the
number of entries in the list that will always be visible (others can be scrolled
into view as needed). In the third form, if multipleSelect is true, then the user
may select two or more items at a time. If it is false, then only one item may be
selected. For adding a selection to the list, we can call add( ). It has the following
two forms:
void add(String name);
void add(String name, int index);
Here, name is the name of the item added to the list. The first form adds
items to the end of the list. The second form adds the item at the index specified
by index.
For lists that allow multiple selection, we must use either getSelectedItems( )
or getSelectedIndexes( ), shown here, to determine the current selections:
String[ ] getSelectedItems( );
int[ ] getSelectedIndexes( );
The getSelectedItems( ) returns an array containing the names of the
currently selected items. getSelectedIndexes( ) returns an array containing the
indexes of the currently selected items. In order to obtain the number of items in
the list, call getItemCount( ). We can set the currently selected item by using the
select( ) method with a zero-based integer index. These methods are shown here:
int getItemCount( );
void select(int index);
Given an index, we can obtain the name associated with the item at that
index by calling getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
Example: List Demonstration
//ListDemo.java
import java.awt.*;
import java.applet.*;
/*
*/
int idx[];
msg = “Current OS: “;
idx = os.getSelectedIndexes();
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + ” “;
g.drawString(msg, 6, 120);
msg = “Current Browser: “;
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
Output:
TextField
TextComponent
TextArea
TextField
Fig. Text components hierarchy
The TextField class implements a single-line text-entry area, usually called
an edit control. Text fields allow the user to enter strings and to edit the text
using the arrow keys, cut and paste keys, and mouse selections. TextField is a
subclass of TextComponent. TextField defines the following constructors:
TextField( );
TextField(int numChars);
TextField(String str);
TextField(String str, int numChars);
The first version creates a default text field. The second form creates a text
field that is numChars characters wide. The third form initializes the text field
with the string contained in str. The fourth form initializes a text field and sets its
width. TextField (and its superclass TextComponent) provides several methods
that allow us to utilize a text field. In order to obtain the string currently
contained in the text field, we can use getText( ). For setting the text, we call
setText( ). These methods are as follows:
String getText( );
void setText(String str);
Here, str is the new string. The user can select a portion of the text in a text
field. Also, we can select a portion of text under program control by using select(
). Our program can obtain the currently selected text by calling the
getSelectedText( ). These methods are shown here:
String getSelectedText( );
void select(int startIndex, int endIndex);
The getSelectedText( ) returns the selected text. The select( ) method selects
the characters beginning at startIndex and ending at endIndex–1. We can control
whether the contents of a text field may be modified by the user by calling
setEditable( ). We can determine editability by calling isEditable( ). These
methods are shown here:
boolean isEditable( )
void setEditable(boolean canEdit)
The isEditable( ) returns true if the text may be changed and false if not. In
setEditable( ), if canEdit is true, the text may be changed. If it is false, the text
cannot be altered. There may be times when we will want the user to enter text
that is not displayed, such as a password. You can disable the echoing of the
characters as they are typed by calling setEchoChar( ). This method specifies a
single character that the TextField will display when characters are entered (thus,
the actual characters typed will not be shown). We can check a text field to see if
it is in this mode with the echoCharIsSet( ) method. We can retrieve the echo
character by calling the getEchoChar( ) method. These methods are as follows:
void setEchoChar(char ch);
boolean echoCharIsSet( );
char getEchoChar( );
Here, ch specifies the character to be echoed.
Example: Using TextField
//TextFieldDemo.java
import java.awt.*;
import java.applet.*;
/*
*/
}
public void paint(Graphics g)
Output:
TextArea
Sometimes a single line of text input is not enough for a given task. To
handle these situations, the AWT includes a simple multiline editor called
TextArea. Following are the constructors for TextArea:
TextArea( );
TextArea(int numLines, int numChars);
TextArea(String str);
TextArea(String str, int numLines, int numChars);
TextArea(String str, int numLines, int numChars, int sBars);
Here, numLines specifies the height, in lines, of the text area, and numChars
specifies its width, in characters. Initial text can be specified by str. In the fifth
form we can specify the scroll bars that we want the control to have. sBars must
be one of these values:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
TextArea is a subclass of TextComponent. Therefore, it supports the
getText( ), setText(), getSelectedText(), select( ), isEditable( ), and
setEditable( ) methods described in the preceding section. TextArea adds the
following methods:
void append(String str);
void insert(String str, int index);
void replaceRange(String str, int startIndex, int endIndex);
The append( ) method appends the string specified by str to the end of the
current text. The insert( ) inserts the string passed in str at the specified index. In
order to replace text, we call replaceRange( ). It replaces the characters from
startIndex to endIndex–1, with the replacement text passed in str. Text areas are
almost self-contained controls.
Example: Using TextArea Control
//TextAreaDemo.java
import java.awt.*;
import java.applet.*;
/*
*/
Output:
Layout Managers
All of the components that we have shown so far have been positioned by the
default layout manager. A layout manager automatically arranges our controls
within a window by using some type of algorithm.
Each Container object has a layout manager associated with it. A layout
manager is an instance of any class that implements the LayoutManager
interface. The layout manager is set by the setLayout( ) method. If no call to
setLayout( ) is made, then the default layout manager is used. Whenever a
container is resized (or sized for the first time), the layout manager is used to
position each of the components within it.
FlowLayout
FlowLayout is the default layout manager. Components are laid out from the
upper-left corner, left to right and top to bottom. When no more components fit
on a line, the next one appears on the next line. A small space is left between
each component, above and below, as well as left and right. Here are the
constructors for FlowLayout:
FlowLayout( );
FlowLayout(int how);
FlowLayout(int how, int horz, int vert);
The first form creates the default layout, which centers components and
leaves five pixels of space between each component. The second form lets us
specify how each line is aligned. Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
These values specify left, center, and right alignment, respectively. The third
form allows us to specify the horizontal and vertical space left between
components in horz and vert, respectively. Here is a version of the
CheckboxDemo applet shown earlier, modified so that it uses left-aligned flow
layout.
// FlowLayoutDemo.java
import java.awt.*;
import java.applet.*;
/*
*/
}
Output:
BorderLayout
The BorderLayout class implements a common layout style for top-level
windows. It has four narrow, fixed-width components at the edges and one large
area in the center. The four sides are referred to as north, south, east, and west.
The middle area is called the center. Here are the constructors defined by
BorderLayout:
BorderLayout( );
BorderLayout(int horz, int vert);
The first form creates a default border layout. The second allows us to
specify the horizontal and vertical space left between components in horz and
vert, respectively. BorderLayout defines the following constants that specify the
regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
When adding components, we will use these constants with the following
form of add( ), which is defined by Container:
void add(Component compObj, Object region);
Here, compObj is the component to be added, and region specifies where the
Here, compObj is the component to be added, and region specifies where the
component will be added. Here is an example of a BorderLayout with a
component in each layout area:
// BorderLayoutDemo.java
import java.awt.*; import java.applet.*;
/*
*/
setLayout(new BorderLayout());
add(new Button(“This is across the top.”), BorderLayout.NORTH);
add(new Label(“The footer message might go here.”),
BorderLayout.SOUTH);
add(new Button(“Right”), BorderLayout.EAST);
add(new Button(“Left”), BorderLayout.WEST);
String msg = “The reasonable man adapts ” +
“himself to the world;\n” +
“the unreasonable one persists in ” + “trying to adapt the world to
himself.\n” + “Therefore all progress depends ” +
“on the unreasonable man.\n\n” +
” - George Bernard Shaw\n\n”;
add(new TextArea(msg),
BorderLayout.CENTER);
Output:
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop an AWT Program in JAVA using Button Control
Learn How to handle Button Events using ActionListener interfaces.
L EARNING O UTCOMES
Explain & Practice Button Events.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
C ODE
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.lang.String;
class ChangeColor extends Applet implements ActionListener {
Button b1;
public void init()
if(e.getSource()==b1)
{
String s;
s=b1.getBackground();
if(s==“Change Color”)
{
this.setBackground(Color.RED);
b1.setLabel(“Green”);
}
if(s==“Green”)
{
this.setBackground(Color.GREEN);
b1.setLabel(“Blue”);
}
if(s==“Blue”)
{
this.setBackground(Color.BLUE);
b1.setLabel(“Change Color”);
}
}
public static void main(String [] args)
O UTPUT :
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop an AWT Program in JAVA using Checkbox and Canvas
Control
Learn How to handle Checkbox Events using ItemListener
interfaces.
L EARNING O UTCOMES
Explain & Practice Checkbox Events.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
C ODE :
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.lang.String;
public class CanvasColorDemo extends Applet implements ItemListener
Checkbox ch1,ch2,ch3;
int c1,c2,c3;
//c1=c2=c3=0;
Canvas c=new Canvas();
public void init()
{
setLayout(new GridLayout(1,4));
//ColorGroup=new CheckboxGroup();
ch1=new Checkbox(“RED”,false);
ch2=new Checkbox(“GREEN”,false);
ch3=new Checkbox(“BLUE”,false);
add(ch1);
add(ch2);
add(ch3);
ch1.addItemListener(this);
ch2.addItemListener(this);
ch3.addItemListener(this);
c.setBackground(Color.CYAN);
c.setVisible(true);
add(c);
if(e.getSource()==ch1)
if(c1!=255)
c1=255;
else
c1=0;
if(e.getSource()==ch2)
if(c2!=255)
c2=255;
else
c2=0;
if(e.getSource()==ch3)
if(c3!=255)
c3=255;
else
c3=0;
c.setBackground(new Color(c1,c2,c3));
repaint();
O UTPUT :
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop an AWT Program in JAVA using Menu and TextArea
Learn How to handle Menu Events using ActionListener interfaces.
L EARNING O UTCOMES
Explain & Practice Menu Events.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
C ODE :
/*MenuDemo.java*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MenuDemo extends Applet implements ActionListener
myFrame.show();
}
myFrame.dispose();
// use System.exit(0) for applications
O UTPUT :
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop an AWT Program in JAVA using Graphics Class Methods
like drawRect() and fillRect()
L EARNING O UTCOMES
Explain & Practice Graphics Class Methods.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
C ODE :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class RectApplet extends Applet
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE);
for (int x = 0; x < getWidth() / 2; x += 5)
int x1 = (getWidth() / 2) - x;
int y1 = (getHeight() / 2) - x;
g.drawRect(x1, y1, x 2, x 2);
public static void main(String args[])
{
System.exit(0);
});
frame.add(applet);
frame.setSize(W, H);
frame.show();
O UTPUT :
EXERCISE:
D EVELOP AN APPLET TO DISPLAY THE MESSAGE “H APPY N EW Y EAR ” WITHIN A
TEXT FIELD .
Code:
Output:
Code:
Output:
B UILD AN APPLET THAT RECEIVES THE RADIUS OF A CIRCLE THROUGH A TEXT FIELD
AND COMPUTES THE AREA WHEN THE BUTTON “A REA ” IS PUSHED . T HE AREA
SHOULD APPEAR IN A SEPERATE TEXT FIELD . THE FIRST TEXT FIELD SHOULD BE
PRECEEDED BY THE LABEL “E NTER THE R ADIUS ”, WHILE THE SECOND TEXT FIELD
SHOULD BE PRECEEDED BY THE LABEL “A REA IS EQUAL TO ”.
Code:
Output:
C REATE TWO CHECKBOXES WITH THE CAPTION “COM” AND “COBRA”. C REATE
TWO TEXT FIELDS . U SE THE FIRST TO INDICATE THE STATUS OF THE FIRST
CHECKBOX AND THE SECOND TEXT FIELD TO INDICATE THE STATUS OF THE SECOND
CHECKBOX .
Code:
Output:
Code:
Output:
A MENU BAR CONTAINS 3 MENUS NAMED S ALES F ILE 1, S ALES F ILE 2, AND
S ALES F ILE 3. E ACH ONE OF THESE 3 MENUS HAS THE 3 OPTIONS NAMED CREATE ,
UPDATE AND PRINT . W RITE AN APPLET FOR CREATING AND DISPLAYING ALL THE 3
MENUS WITH THEIR OPTIONS .
Code:
Output:
UNIT 3
G ENERAL O BJECTIVES
After performing this practical student will be able to:
Learn how to use JDBC to connect database.
Develop and execute a JDBC application to create/read/update/delete
records into database.
Learn how to use JDBC API and JDBC Drivers for databae
functions.
L EARNING O UTCOMES
Explain JDBC concepts and Practice JDBC programs.
A SSUMPTIONS
Oracle JDK installed, MySQL Java Connector installed and
configured.
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
INTRODUCTION
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 commonly associated
with database usage:
Making a connection to a database
Creating SQL or MySQL statements
Executing that SQL or MySQL queries in the database
Viewing & Modifying the resulting records
The basic steps to get your program up and running are:
Load the driver and register it with the driver manager
Connect to a database
Create a statement
Execute a query and retrieve the results, or make changes to the
database
Disconnect from the database
Steps 1 and 2 are the only DBMS-specific steps.
Here is the code that loads the driver and registers it with the JDBC driver
manager: DriverManager.registerDriver(new com.mysql.jdbc.Driver ()); Here is
another way of doing the above:
Class.forName(“com.mysql.jdbc.Driver”);
Following are driver string for some of the popular databases,
MySQL JDBC Connection URL:
jdbc:mysql://hostname:3306/ – 3306 is mysql default port
Java DB Connection URL:
jdbc:derby:testdb;create=true
Microsoft SQL Server JDBC Connection URL:
jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=northwind
Oracle JDBC connection URL:
jdbc:oracle:thin:@hostname:1521:MyDatabase
Connecting to a Database
The DriverManager class provides the static getConnection() method for
opening a database connection. Below is the method description for
getConnection():
public static Connection getConnection(String url, String userid, String
password) throws SQLException Getting connection
Connection connection =
DriverManager.getConnection(“jdbc:jdbcDriver:database”, username,
password); Query execution and getting result
Statement statement = connection.createStatement(); ResultSet resultSet =
statement.executeQuery(“SELECT * FROM table”); Parsing the result from
ResultSet
while (resultSet.next()) {
int field1= rs.getInt(“field1”);
String field2= rs.getString(“field2”);
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Learn how to use JDBC to connect to database.
Learn how to use JDBC API and JDBC Drivers for databae
functions.
L EARNING O UTCOMES
Explain JDBC concepts and Practice JDBC programs to connect to
MySQL Database.
A SSUMPTIONS
Oracle JDK installed, MySQL Java Connector installed and
configured.
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, path, classpath are
configured.
C ODE
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = “com.mysql.jdbc.Driver”; static
final String DB_URL = “jdbc:mysql://localhost/”;
// Database credentials static final String USER = “root”; static final
String PASS = ””; public static void main(String[] args) {
Connection conn = null; Statement stmt = null; try{
//STEP 2: Register JDBC driver
Class.forName(“com.mysql.jdbc.Driver”);
//STEP 3: Open a connection System.out.println(“Connecting to
database…”); conn = DriverManager.getConnection(DB_URL, “USER”,
“PASS” ); //STEP 4: Execute a query System.out.println(“Creating
database…”); stmt = conn.createStatement(); String sql = “CREATE
DATABASE STUDENTS”; stmt.executeUpdate(sql);
System.out.println(“Database created successfully…”); }catch(SQLException
se){
//Handle errors for JDBC
se.printStackTrace(); }catch(Exception e){
//Handle errors for Class.forName e.printStackTrace(); }finally{
//finally block used to close resources try{
if(stmt!=null) stmt.close(); }catch(SQLException se2){
}// nothing we can do try{
if(conn!=null) conn.close(); }catch(SQLException se){
se.printStackTrace(); }//end finally try }//end try
System.out.println(“Goodbye!”); }//end main
}//end JDBCExample
O UTPUT :
Connecting to database…
Creating database…
Database created successfully…
Goodbye!
Process completed.
L EARNING O UTCOMES
Explain JDBC concepts and Practice database operations using
JDBC.
A SSUMPTIONS
Oracle JDK installed, MySQL Java Connector installed and
configured.
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, path, classpath are
configured.
C ODE
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JDBCCRUD implements ActionListener {
JLabel lblFname,lblLname,lblf,lbll;
JLabel lblfVal,lbllVal;
JTextField txtFname,txtLname;
JButton btnInsert,btnUpdate,btnDelete,btnPrev,btnNext,btnClear;
Connection con;
ResultSet rs ;
}
private void createUI()
pnlInput.add(lblLname);
pnlInput.add(txtLname);
pnlAns.add(lblf);
pnlAns.add(lblfVal);
pnlAns.add(lbll);
pnlAns.add(lbllVal);
frame.add(pnlInput);
frame.add(pnlButton);
frame.add(pnlAns);
frame.add(pnlNavigate);
frame.pack();
frame.setVisible(true);
@Override
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
if(cmd.equals(“Insert”))
next();
}else if(cmd.equals(“Clear”))
clearControls();
try
Class.forName(“com.mysql.jdbc.Driver”);
con =
DriverManager.getConnection(“jdbc:mysql://localhost/students”,“root”, ””); }
catch(Exception e)
System.out.println(“Unable to connect”);
con.close(); }
catch(Exception e) {}
catch(Exception e)
{
createMessageBox(e.getMessage()); }
try
catch(Exception e)
createMessageBox(e.getMessage()); }
try
catch(Exception e)
createMessageBox(e.getMessage()); }
try
if(rs == null) {
String sql = “Select FName,LName from StudentData”;
Statement statement =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDAT
rs = statement.executeQuery(sql); }
if(rs.previous()&& !rs.isBeforeFirst()) {
populateControls();
}
catch(Exception e)
{
{
e.printStackTrace(); }
try
if(rs == null) {
String sql = “Select FName,LName from StudentData”;
Statement statement =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_O
rs = statement.executeQuery(sql);
}
if(rs.next() && !rs.isAfterLast())//After Last was giving invalid cursor
state error {
populateControls(); }
catch(Exception e)
e.printStackTrace(); }
}
private void createMessageBox(String msg)
{
txtFname.setText(empty);
txtLname.setText(empty);
lblfVal.setText(empty);
lbllVal.setText(empty);
try{
lblfVal.setText(rs.getString(“fName”));
lbllVal.setText(rs.getString(“lName”));
txtFname.setText(lblfVal.getText());
txtLname.setText(lbllVal.getText()); }
catch(SQLException e)
e.printStackTrace(); }
O UTPUT
JDBC Insert Operation
PRACTICAL 13: WRITE A PROGRAM TO PRESENT A SET OF
CHOICE FOR USER TO SELECT A PRODUCT & DISPLAY THE
PRICE OF PRODUCT.
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop a JDBC Program in JAVA using MySQL as backend.
Learn How to handle JComboBox Control Events using ItemListener
interface.
L EARNING O UTCOMES
Explain & Practice fetching values based on selection in JComboBox
Events.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
Following database and table created in MySQL
Database: ProductInfo
Table: ProductTable {ProductName Char(50), Price
Number}
ProductName Price
ProductName Price
CD 30
PenDrive 250
C ODE
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JComboBox;
public class JDBCPriceDemo {
JLabel lblItem;
JComboBox cmbItemList;
JLabel lblSelectedItem,lblItemPrice;
String product;
int price;
Connection con;
ResultSet rs1 ;
ResultSet rs2;
cmbItemList.addItem(rs1.getString(“ProductName”)); }
stmt.close();
rs1.close();
}
}
catch(Exception e) {}
lblSelectedItem = new JLabel(“Item:”);
lblItemPrice = new JLabel(“Price:”);
frame.add(lblItem);
frame.add(cmbItemList);
frame.add(lblSelectedItem);
frame.add(lblItemPrice);
};
cmbItemList.addItemListener(itemListener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void connect()
try
Class.forName(“com.mysql.jdbc.Driver”);
con =
DriverManager.getConnection(“jdbc:mysql://localhost/ProductInfo”,“root”,
””); }
catch(Exception e)
System.out.println(“Unable to connect”);
}
con.close(); }
catch(Exception e) {}
}
}
O UTPUT
EXERCISE:
W RITE A JDBC PROGRAM TO IMPLEMENT THE L OGIN _I D F ORM USING JDBC.
Code:
Output:
W RITE A JDBC PROGRAM TO SELECT THE VALUES FROM THE DEPARTMENT TABLE .
Code:
Output:
W RITE A JDBC PROGRAM TO INSERT THE VALUES INTO THE STUDENT TABLE .
Code:
Output:
W RITE A JDBC PROGRAM TO ALTER AND INSERT THE VALUES INTO TABLE .
Code:
Output:
W RITE A JDBC PROGRAM TO DELETE A RECORD BY TAKING THE INPUT FROM
KEYBOARD .
Code:
Output:
UNIT 4
G ENERAL O BJECTIVES
After performing this practical student will be able to:
Learn how to use Servlet to develop web applications.
Develop and deploy a Servlet application using Apache web server.
Learn how to read parameters in Servlet.
Learn how to read initialization parameters using web.xml file.
L EARNING O UTCOMES
Explain Servlet concepts
Practice Servlet programs.
A SSUMPTIONS
Oracle JDK installed, Apahe Web Server and Servlet API installed,
configured and running.
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
INTRODUCTION
Servlets: For development of web basd components Servlets are the Java
platform technology of choice for extending and enhancing Web servers.
Servlets provide a component-based, platform-independent method for building
Web-based applications, without the performance limitations of CGI programs.
And unlike proprietary server extension mechanisms (such as the Netscape
Server API or Apache modules), servlets are server-and platform-independent.
This leaves you free to select a “best of breed” strategy for your servers,
platforms, and tools. Servlets have access to the entire family of Java APIs,
including the JDBC API to access enterprise databases. Servlets can also access
a library of HTTP-specific calls and receive all the benefits of the mature Java
language, including portability, performance, reusability, and crash protection.
Today servlets are a popular choice for building interactive Web
applications. Third-party servlet containers are available for Apache Web
Server, Microsoft IIS, and others. Servlet containers are usually a component of
Web and application servers, such as BEA WebLogic Application Server, IBM
WebSphere, Sun Java System Web Server, Sun Java System Application Server,
and others.
As we know that the servlet extends the HttpServlet and overrides the doGet
() method which it inherits from the HttpServlet class. The server invokes doGet
() method whenever web server receives the GET request from the servlet. The
doGet() method takes two arguments first is HttpServletRequest object and the
second one is HttpServletResponse object and this method throws the
ServletException.
Whenever the user sends the request to the server then server generates two
objects’ first is HttpServletRequest object and the second one is
HttpServletResponse object. HttpServletRequest object represents the client’s
request and the HttpServletResponse represents the servlet’s response.
Inside the doGet() method our servlet has first used the setContentType()
method of the response object which sets the content type of the response to
text/html It is the standard MIME content type for the html pages.After that it
has used the method getWriter () of the response object to retrieve a PrintWriter
object. To display the output on the browser we use the println () method of the
PrintWriter class.
Session
A session is a conversation between the server and a client. A conversation
consists of series of continuous request and response.
When there is a series of continuous request and response from a same client
to a server, the server cannot identify from which client it is getting requests.
Because HTTP is a stateless protocol.
When there is a need to maintain the conversational state, session tracking is
needed. For example, in a shopping cart application a client keeps on adding
items into his cart using multiple requests. When every request is made, the
server should identify in which client’s cart the item is to be added. So in this
scenario, there is a certain need for session tracking.
Solution is, when a client makes a request it should introduce itself by
providing unique identifier every time. There are five different methods to
achieve this.
Session tracking methods:
1. User authorization
2. Hidden fields
3. URL rewriting
4. Cookies
5. Session tracking API
Cookies
Also known as browser cookies or tracking cookies, cookies are small, often
encrypted text files, located in browser directories. They are used by web
developers to help users navigate their websites efficiently and perform certain
functions. Due to their core role of enhancing/enabling usability or site
processes, disabling cookies may prevent users from using certain websites.
Cookies are created when a user’s browser loads a particular website. The
website sends information to the browser which then creates a text file. Every
time the user goes back to the same website, the browser retrieves and sends this
file to the website’s server. Computer Cookies are created not just by the website
the user is browsing but also by other websites that run ads, widgets, or other
elements on the page being loaded. These cookies regulate how the ads appear or
how the widgets and other elements function on the page.
Cookie Class
In JSP cookie is the object of the class javax.servlet.http.Cookie. This class is
used to create a cookie, a small amount of information sent by a servlet to a Web
browser, saved by the browser, and later sent back to the server. A cookie’s
value can uniquely identify a client, so cookies are commonly used for session
management. 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.
The getCookies() method of the request object returns an array of Cookie
objects. Cookies can be constructed using the following code: Cookie
(java.lang.String name, java.lang.String value)
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Learn how to use SERVLET to maintain hit of web pages.
L EARNING O UTCOMES
Understand the servlet initialization parameters using web.xml file.
A SSUMPTIONS
Oracle JDK installed, Apache Web Serverinstalled and configured.
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, path, classpath are
configured.
C ODE
Index.html
<html>
<head>
<title>Hit Counter using Session</title> </head>
<body>
<form id=“HitDemo” action=”/pagehit/PageHitCounter” method=“GET”>
<label>Click to test Hit Counter for Servlet</label> <br><br>
<input type=submit value=“Submit”> </form>
</body>
</html>
PageHitCounter.java
import java.util.Enumeration; import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletException; import
javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import
javax.servlet.ServletConfig; public class PageHitCounter extends
HttpServlet{
private int hitCount; public void init(ServletConfig servletConfig)
throws ServletException{
this.hitCount = Integer.valueOf(servletConfig.getInitParameter(“hit”)); }
public void doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException,IOException {
// Set response content type
response.setContentType(“text/html”);
// This method executes whenever the servlet is hit // increment hitCount
hitCount++;
PrintWriter out=response.getWriter(); String title =“Total Number of
Hits”; String docType=
“<!doctype html public "-//w3c//dtd html 4.0 “+
“transitional//en">\n”;
out.println(docType+
“<html>\n”+
“<head><title>”+ title +”</title></head>\n”+
“<body bgcolor="#f0f0f0">\n”+
“<h1 align="center">”+ title +”</h1>\n”+
“<h2 align="center">”+hitCount+”</h2>\n”+
“</body></html>”);
web.xml
<?xml version=“1.0” encoding=“UTF-8”?>
<web-app >
<servlet>
<servlet-name>PageHitCounter</servlet-name> <servlet-
class>PageHitCounter</servlet-class> <init-param>
<param-name>hit</param-name>
<param-value>0</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>PageHitCounter</servlet-name> <url-
pattern>/PageHitCounter</url-pattern> </servlet-mapping>
</web-app>
O UTPUT
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Learn how to use cookie in servlet to track sessions.
L EARNING O UTCOMES
Understand the use of cookie for session tracking.
A SSUMPTIONS
Oracle JDK installed, Apache Web Serverinstalled and configured.
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, path, classpath are
configured.
C ODE
index.html
<html>
<head>
<title>Cookies Example in Servlets</title> </head>
<body bgcolor=wheat>
<center>
<h1>Cookies Example in Java</h1> <form action=“CookieExample”
method=“Post”> First name: <input type=“text” name=“fname”> Last name:
<input type=“text” name=“lname”> <input type=“submit”value=“SUBMIT”>
</form>
</center>
</body>
</html>
CookieExample.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CookieExample extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
String fname=req.getParameter(“fname”); String
lname=req.getParameter(“lname”);
Cookie f=new Cookie(“first_name”,fname); Cookie l=new
Cookie(“last_name”,lname);
res.addCookie(f);
res.addCookie(l);
res.setContentType(“text/html”);
PrintWriter out=res.getWriter(); out.print(“<a href=‘GetCookie’>Cookies
Created Successfully!!!Click to Read cookies</a>”); }
GetCookie.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class GetCookie extends HttpServlet
Web.xml
<web-app>
<servlet>
<servlet-name>CookieExample</servlet-name> <servlet-
class>CookieExample</servlet-class> </servlet>
<servlet-mapping> <servlet-name>CookieExample</servlet-name>
<url-pattern>/CookieExample</url-pattern> </servlet-mapping> <servlet>
<servlet-name>GetCookie</servlet-name> <servlet-
class>GetCookie</servlet-class> </servlet>
<servlet-mapping> <servlet-name>GetCookie</servlet-name> <url-
pattern>/GetCookie</url-pattern> </servlet-mapping> </web-app>
O UTPUT
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Learn how to use session in servlet to track sessions.
L EARNING O UTCOMES
Understand the use of session for session tracking.
A SSUMPTIONS
Oracle JDK installed, Apache Web Serverinstalled and configured.
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, path, classpath are
configured.
C ODE
index.htm
<html>
<head>
<title>Get a Hi!!! </title> </head>
<body>
<form action=“SessionExample” method=“get”> <input type=“text”
name=“user”/> <input type=“submit” value=“Get”/> </form>
</body>
</html>
Web.XMl
<web-app>
<servlet>
<servlet-name>SessionExample</servlet-name> <servlet-
class>SessionExample</servlet-class> </servlet>
<servlet-mapping> <servlet-name>SessionExample</servlet-name>
<url-pattern>/SessionExample</url-pattern> </servlet-mapping>
<servlet>
<servlet-name>SessionTrack</servlet-name> <servlet-
class>SessionTrack</servlet-class> </servlet>
<servlet-mapping> <servlet-name>SessionTrack</servlet-name> <url-
pattern>/SessionTrack</url-pattern> </servlet-mapping> </web-app>
SessionExample.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SessionExample extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse
res)throws ServletException,IOException {
String st=req.getParameter(“user”);
HttpSession ses=req.getSession();
ses.setAttribute(“uname”,st); res.setContentType(“text/html”);
PrintWriter out=res.getWriter(); out.print(“<a href=‘SessionTrack’>Session
Created Successfully!!!Click to Read Session</a>”); }
SessionTrack.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse
res)throws ServletException,IOException {
PrintWriter pw=res.getWriter(); HttpSession ses=req.getSession();
String st=(String)ses.getAttribute(“uname”); pw.println(“<h1> Hi
“+st+”</h1>”); }
O UTPUT
UNIT 5
G ENERAL O BJECTIVES
After performing this practical student will be able to:
Learn how to use JSP to develop web applications.
Develop and deploy a JSP application using Apache web server.
L EARNING O UTCOMES
Explain JSP concepts
Practice JSP programs.
A SSUMPTIONS
Oracle JDK installed, Apahe Web Server installed, configured and
running.
Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are
configured.
INTRODUCTION
JavaServer Pages (JSP) is a Java technology that allows software
developers to dynamically generate HTML, XML or other types of documents in
response to a Web client request. The technology allows Java code and certain
pre-defined actions to be embedded into static content.
The JSP syntax adds additional XML-like tags, called JSP actions, to be used
to invoke built-in functionality. Additionally, the technology allows for the
creation of JSP tag libraries that act as extensions to the standard HTML or
XML tags.
Step 5: Before run this code, start apache tomcat as you have done following
Section.
Apache Tomcat port information
Iamgivingthefollowinginformation
1.Tomcatportinformation
2.ChangeTomcatusernameandpassword(optional)
3 . Start, Stop and Restart tomcat 1 . Tomcat port information
D:/ …/Tomcat6.0/conf/server.xml
This file have default port number (During installation specified…) you can
able to change that port number.
Server.xml
The connector tags have your tomcat port number.
2 . Change the tomcat manger username and password. (optional) If you
want to change the tomcat username and password, then you edit the tomcat-
user.xmlfile
<tomcat-users>
<role rolename=“admin”/>
<role rolename=“manager”/>
<role rolename=“tomcat”/>
<role rolename=“role1”/>
<user username=“admin” password=“admin123”
roles=“admin,manager”/> <user username=“tomcat” password=“tomcat”
roles=“tomcat”/> <user username=“both” password=“tomcat”
roles=“tomcat,role1”/> <user username=“role1” password=“tomcat”
roles=“role1”/> </tomcat-users>
Here I showed, changed tomcat admin username and password
Theusername:admin
The password : admin123
3.Start , Stop and Resart tomcat
If you have change (server.xml or tomcat-user.xml), then better you will
restart your tomcat.
Start or Restart (if already running) Apache Tomcat Server from command
line D:\apache-tomcat-8.0.15\bin>startup.
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop a JSP Program in JAVA.
Learn How to handle page redirecting in Web browser.
L EARNING O UTCOMES
Explain & Practice Jsp scriplet tags and HTML tags.
A SSUMPTIONS
Oracle JDK, Apache-tomcat-8.0.15 installed.
Editor Like notepad, Netbeans available for program development.
Environment variables like JAVA_Home, Path, and Classpath are
configured.
C ODE
Registration.jsp
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop a JSP Program in JAVA.
Learn How to handle static and dynamic database in Web browser.
L EARNING O UTCOMES
Explain & Practice how to access mysql database from JSP
programme.
A SSUMPTIONS
Oracle JDK, Apache-tomcat-8.0.15 and wampserver2.2c-x32
installed.
Editor Like notepad, Netbeans available for program development.
Environment variables like JAVA_Home, Path, and Classpath are
configured and copy mysql-connector jar file to folder C:\Program
Files\Java\jdk1.8.0_25\jre\lib\ext.
C ODE ( A )
(a) Write a simple JSP program for user login form with static
database.
Login.jsp
<html>
<head>
<title>JSP Page</title> </head>
<body>
<h1><center>Login Page</center></h1> <center>
<h2>Signup Details</h2> <form action=“logincheck.jsp”
method=“post”> <br/>Username:<input type=“text”
name=“username”> <br/>Password:<input type=“password”
name=“password”> <br/><input type=“submit” value=“Submit”>
</form>
</center>
</body>
</html>
Logincheck.jsp
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter(“username”);
String password=request.getParameter(“password”);
if((username.equals(“kdp”) && password.equals(“kdp123”))) {
session.setAttribute(“username”,username);
response.sendRedirect(“home.jsp”);
else
response.sendRedirect(“error.jsp”);
%>
</body>
</html>
Home.jsp
Logout.jsp
Error.jsp
<%@page contentType=“text/html” pageEncoding=“UTF-8”%>
<html>
<head>
<title>JSP Page</title> </head>
<body>
<h1>Sorry Invalid Username or Password…</h1> </body>
</html>
O UTPUT
C ODE ( B )
(b) Write a simple JSP program for user login form with dynamic
database.
->Create logindatabase Database in MySQL.
->Create members Table under logindatabase Database.
Members:
login.jsp
Logincheck.jsp
Newregistration.jsp
Registrationsubmit.jsp
Welcome.jsp
Registration is Successful.
Please Login Here <a href=‘login.jsp’>Go to Login</a>
Success.jsp
<%
if ((session.getAttribute(“userid”) == null) ||
(session.getAttribute(“userid”) == ””)) {
%>
You are not logged in<br/>
<a href=“login.jsp”>Please Login</a>
<%} else {
%>
Welcome <%=session.getAttribute(“userid”)%>
<a href=‘logout.jsp’>Log out</a>
<%
%>
OUTPUT:
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Develop a JSP Program in JAVA.
Learn How to handle page redirecting in web browser.
L EARNING O UTCOMES
Explain & Practice Jsp scriplet tags and HTML tags.
A SSUMPTIONS
Oracle JDK, Apache-tomcat-8.0.15 installed.
Editor Like notepad, Jcreator available for program development.
Environment variables like JAVA_Home, Path, and Classpath are
configured.
C ODE
<%@ page language=“java” contentType=“text/html; charset=ISO-8859-1”
pageEncoding=“ISO-8859-1”%> <html>
<head>
<title>Student Marks</title>
</head>
<body>
<h2>Student Grading System</h2>
<form action=”” method=“post”>
<table>
<tr>
<td></td>
<td>
Enter Five Subject Marks out of 100
</td>
</tr>
</table>
<table>
<tr>
<th>Subject</th>
<th>Obtained Marks</th>
<th>Total Marks</th>
</tr>
<tr>
<td align=“center”>C</td>
<td align=“center”><input type=“text” size=“5” name=“c”><td> <td
align=“center”>100</td>
</tr>
<tr>
<td align=“center”>Java</td>
<td align=“center”><input type=“text” size=“5” name=“java”><td> <td
align=“center”>100</td>
</tr>
<tr>
<td align=“center”>.Net</td>
<td align=“center”><input type=“text” size=“5” name=“net”><td> <td
align=“center”>100</td>
</tr>
<tr>
<td align=“center”>VB</td>
<td align=“center”><input type=“text” size=“5” name=“vb”><td> <td
align=“center”>100</td>
</tr>
<tr>
<td align=“center”>DBMS</td>
<td align=“center”><input type=“text” size=“5” name=“dbms”><td> <td
align=“center”>100</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr><td></td><td align=“center”><input type=“submit” value=“submit”>
<td></tr> </table>
</form>
<%
String c = request.getParameter(“c”);
String j = request.getParameter(“java”);
String n = request.getParameter(“net”);
String v = request.getParameter(“vb”);
String d = request.getParameter(“dbms”);
if(!(c == null || c.isEmpty()))
}
else if(percent >=70 && percent <=74){
grade = “B”;
%>
</body>
</html>
O UTPUT