Documente Academic
Documente Profesional
Documente Cultură
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 ITS 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.
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 ITS 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.
UNIT 1
G ENERAL O BJECTIVES
After performing this practical student will be able to:
Learn about Applet.
Develop an Applet Program in JAVA
Execute an Applet Program in JAVA using AppletViewer
Execute an Applet in Web Browser
Learn How to use Graphics Class to draw Shapes.
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.
file is. The CODE attribute is the name of the .class file itself. For instance if
on the HTML page of the previous section you had written
The HEIGHT and WIDTH attributes specify how big a rectangle the browser
should set aside for the applet. These numbers are specified in pixels and are
required.
<APPLET
CODE=TestApplet.class
CODEBASE=classes
WIDTH=200 HEIGHT=200>
</APPLET>
then the browser would have tried to find TestApplet.class in the classes directory in
the same directory as the HTML page that included the applet. On the other hand if you
had written
<APPLET
CODE= TestApplet.class
CODEBASE=http://www.foo.bar.com/classes
WIDTH=200
HEIGHT=200>
</APPLET>
then the browser would try to retrieve the applet from http://www.foo.bar.com/classes/
TestApplet.class regardless of where the HTML page was.
In short the applet viewer will try to retrieve the applet from the URL given by the
formula (CODEBASE + / + code). Once this URL is formed all the usual rules about
relative and absolute URLs apply.
You can leave off the .class extension and just use the class name in the CODE
attribute. For example,
<APPLET CODE=TestApplet
CODEBASE=http://www.foo.bar.com/classes
WIDTH=200
HEIGHT=200>
</APPLET>
import java.applet.*;
import java.awt.*;
public class TestApplet extends Applet {
public void paint(Graphics g)
{
g.drawString(Welcome to the applet world,20,40);
}
}
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.
{
public void paint (Graphics g)
{
g.drawString(Welcome to Applet world,20,40);
}
}
Description
void
setBackground
To set the background of an
(Color colorname )
applet window.
void
setForeground
To set the foreground color of an
(Color colorname )
applet window.
Color getBackground (
Color getForeground ( )
Applet getApplet
String name )
Void
showStatus(
To display the status message in
String status )
the status bar of applet window
URL
getDocumentBase ( )
URL getCodeBase( )
Example:
import java.applet.*;
import java.awt.*;
import java.net.*;
/*
<applet code=AppletMethods height=300 width=400>
<param name=first value=KDP >
</applet>
*/
public class AppletMethods extends Applet
{
String arg;
public void start( )
{
arg=getParameter(first);
}
public void paint(Graphics g)
{
setBackground(Color.black);
setForeground(Color.white);
URL codename=getCodeBase( );
URL docname=getDocumentBase( );
g.drawString(String = Welcome to KDP,30,40);
g.drawString(Parameter Value = +arg,30,70);
g.drawString(Class name= +codename.toString( ),30,100);
g.drawString(DocumentBase = +docname.toString(),30,130);
}
}
Output:
NAME = appletInstanceName
WIDTH = pixels HEIGHT = pixels
ALIGN = alignment
>
<PARAM NAME = appletAttribute1 VALUE = value>
<PARAM NAME = appletAttribute2 VALUE = value>
alternateHTML
</APPLET>
Example Applet with parameters
/*
* AppletWithPara.java
*
*/
import java.applet.*;
import java.awt.*;
/*
<applet code=AppletWithPara width=200 height =150>
<param name=author value=J.B.Patel>
<param name=age value=27>
<param name=designation value=Lecturer>
<param name=institute value=SSPC Visnagar>
</applet>
*/
public class AppletWithPara extends java.applet.Applet
{
public void paint (Graphics gp)
{
String au=getParameter(author);
String ag=getParameter(age);
String desg=getParameter(designation);
String inst=getParameter(institute);
gp.drawString(Author:+au,20,40);
gp.drawString(Age:+ag,20,70);
gp.drawString(Designation:+desg,20,100);
gp.drawString(Institute:+inst,20,130);
showStatus(Parameter methods);
}
}
Output:
Graphics Objects
In Java all drawing takes place via a Graphics object. This is an instance of the class
java.awt.Graphics. Initially the Graphics object you use will be the one passed as an
argument to an applets paint() method.
Each Graphics object has its own coordinate system, and all the methods of Graphics
including those for drawing Strings, lines, rectangles, circles, polygons and more.
Drawing in Java starts with particular Graphics object. You get access to the Graphics
object through the paint(Graphics g) method of your applet. Each draw method call will
look like g.drawString(Hello World, 0, 50) where g is the particular Graphics object
with which youre drawing.
Commonly used methods of Graphics class are as follows:
drawString ( String s, int x, int y )
height)
setColor ( Color c )
)
drawRect ( int x, int y, int width, int
To draw a rectangle at specific
height )
location
fillRect ( int x, int y, int width, int height
)
drawArc (int x, int y, int width, int
height, int arcwidth, int archeight )
To draw an Arc
setFont ( Font f)
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
youre drawing with.
This program draws a line diagonally across the applet.
import java.applet.*;
import java.awt.*;
public class SimpleLine extends Applet {
public void paint(Graphics g) {
g.drawLine(0, 0, this.getSize().width, this.getSize().height);
}
}
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.*;
public class RectangleApplet extends Applet {
public void paint(Graphics g) {
g.drawRect(0, 0, this.getSize().width - 1, this.getSize().height - 1);
}
}
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. Heres the code:
import java.applet.*;
import java.awt.*;
The arguments to drawOval() are the same as the arguments to drawRect(). The first
int is the left hand side of the enclosing rectangle, the second is the top of the enclosing
rectangle, the third is the width and the fourth is the height.
Example:
import java.applet.*;
import java.awt.*;
public class Bullseye extends Applet {
public void paint(Graphics g) {
int appletHeight = this.getSize().height;
int appletWidth = this.getSize().width;
for (int i=8; i >= 0; i) {
if ((i % 2) == 0) g.setColor(Color.red);
else g.setColor(Color.white);
// Center the rectangle
int rectHeight = appletHeight*i/8;
int rectWidth = appletWidth*i/8;
int rectLeft = appletWidth/2 - i*appletWidth/16;
int rectTop = appletHeight/2 - i*appletHeight/16;
g.fillOval(rectLeft, rectTop, rectWidth, rectHeight);
}
}
}
Output
Red
Value
Green
Value
Blue
Value
White
255
255
255
Black
Light Gray
192
192
192
Dark Gray
128
128
128
Red
255
Green
255
Blue
255
Yellow
255
255
Purple
255
255
Color.gray
Color.orange
Color.yellow
Color.blue
Color.green
Color.pink
Color.cyan
Color.lightGray
Color.red
Color.darkGray
Color.magenta
Color.white
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 youd 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.*;
/*
<applet code=AppletColor height=300 width=400>
</applet>
*/
public class AppletColor extends Applet
{
public void paint(Graphics g)
{
Color c1=new Color(255,0,255);
Fonts
Youve 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 its 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. Its 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 {
private String[] availableFonts;
public void init () {
Toolkit t = Toolkit.getDefaultToolkit();
availableFonts = t.getFontList();
}
public void paint(Graphics g) {
for (int i = 0; i < availableFonts.length; i++) {
g.drawString(availableFonts[i], 5, 15*(i+1));
}
}
}
Output
Drawing Graphics
Example: GraphicsDemo.java
import java.awt.*;
import java.applet.*;
/*<applet code=GraphicsDemo width=400 height=400>
</applet>*/
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
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(Filled Round Rect,200,100);
g.drawOval(20,100,50,80);
g.drawString(Oval,25,200);
g.fillOval(100,130,50,50);
g.drawString(Circle,110,200);
g.drawString(WELCOME TO GRAPHICS,130,350);
}
}
Output:
g.setColor (Color.green);
showStatus (This applet draws circle in the center of the applet);
}
}
O UTPUT
{
w=getWidth();
h=getHeight();
}
public void paint(Graphics g)
{
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;
}
}
}
O UTPUT
}
O UTPUT
When Dragging
b1.setLabel(Stop);
else
b1.setLabel(Start);
}
}
}
O UTPUT :
When You Press Stop
When You Press Start
Button
Button
</applet>
*/
public class MouseState
MouseMotionListener
extends
Applet
{
String s=;
int mx=0, my=0;
public void init( )
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent m) { }
public void mouseEntered(MouseEvent m){ }
public void mouseExited(MouseEvent m) { }
public void mousePressed(MouseEvent m)
{
mx=m.getX( );
my=m.getY( );
s= Pressed:;
repaint( );
}
public void mouseReleased(MouseEvent m)
{
mx=m.getX( );
my=m.getY( );
s= Released:;
repaint( );
}
public void mouseDragged(MouseEvent m) { }
public void mouseMoved(MouseEvent m) { }
public void paint(Graphics g)
implements
MouseListener,
{
g.drawString(Mouse+s+mx+,+my, 10, 10);
g.setColor (Color.red);
g.drawRect ( mx,my, 10, 10);
//g.drawString(Mouse moving at: +mx+,+my,20,40);
}
}
O UTPUT :
When You Press Mouse
EXERCISE:
W RITE AN APPLET THAT DISPLAYS A SIMPLE MESSAGE : H ELLO A PPLET .
Code:
Output:
W RITE A J AVA PROGRAM TO DRAW LINES , RECTANGLES AND OVALS .
Code:
Output:
W RITE A N APPLET THAT DRAWS A HUMAN FACE WITH ARC AND OVAL .
Code:
Output:
T O DEVELOP A PROGRAM TO SET THE GIVEN STRING IN A DESIRED FONT AND COLOR .(F ONT :
A RIEL , B OLD AND
POINT SIZE 20, COLOR : PINK )
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 Javas 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.
compObj is returned. Once a control has been added, it will automatically be visible
whenever its parent window is displayed. Sometimes we will want to remove a control
from a window when the control is no longer needed. For doing this, call remove( ).
This method is also defined by Container. It has this general form:
void remove(Component obj)
Here, obj is a reference to the control that we want to remove. We can remove all
controls by calling removeAll( ).
Responding to Controls
Except for labels, which are passive controls, all controls generate events when they
are accessed by the user. For example, when the user clicks on a push button, an event is
sent that identifies the push button. In general, our program simply implements the
appropriate interface and then registers an event listener for each control that we need to
monitor.
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.*;
/*
<applet code=LabelDemo width=300 height=200>
</applet>
*/
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>
*/
public class ButtonDemo extends Applet
{
String msg = ;
Button yes, no, maybe;
public void init()
{
yes = new Button(Yes);
no = new Button(No);
maybe = new Button(Undecided);
add(yes); add(no); add(maybe);
}
public void paint(Graphics g)
{
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.*;
/*
<applet code=CheckboxDemo width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet
{
String msg = ;
}
}
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:
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.*;
/*
<applet code=ListDemo width=300 height=180>
</applet>
*/
public class ListDemo extends Applet
{
List os, browser; String msg = ; public void init()
{
os = new List(4, true); browser = new List(4, false); 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(1);
add(os);
add(browser);
}
public void paint(Graphics g)
{
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
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.*;
/*
<applet code=TextFieldDemo width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet
{
TextField name, pass;
public void init()
{
Label namep = new Label(Name: , Label.RIGHT); Label passp = new
Label(Password: , Label.RIGHT); name = new TextField(12);
pass = new TextField(8); pass.setEchoChar(?); add(namep);
add(name);
add(passp);
add(pass);
}
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 endIndex1, with the
replacement text passed in str. Text areas are almost self-contained controls.
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.
Whenever the container needs to be resized, the layout manager is consulted via its
minimumLayoutSize( ) and preferredLayoutSize( ) methods. Each component that is
being managed by a layout manager contains the getPreferredSize( ) and
getMinimumSize( ) methods. These return the preferred and minimum size required to
display each component. Java has several predefined LayoutManager classes, several of
which are described next. We can use the layout manager that best fits our application.
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.*;
/*
<applet code=FlowLayoutDemo width=400 height=200>
</applet>
*/
public class FlowLayoutDemo extends Applet
{
String msg = ;
Checkbox Win98, winNT, solaris, mac;
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
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.*;
/*
<applet code=BorderLayoutDemo width=400 height=200>
</applet>
*/
public class BorderLayoutDemo extends Applet
{
public void init()
{
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:
import java.applet.*;
import java.awt.event.*;
import java.lang.String;
class ChangeColor extends Applet implements ActionListener {
Button b1;
public void init()
{
b1=new Button(Change Color);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
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 class ColorPickerDemo extends Frame
{
public static void main(String [] args)
{
Frame f = new Frame(Color Picker Demo);
ChangeColor c = new ChangeColor();
c.init();
f.add(Center, c);
f.pack();
f.show();
}
}
O UTPUT :
ch2.addItemListener(this);
ch3.addItemListener(this);
c.setBackground(Color.CYAN);
c.setVisible(true);
add(c);
}
public void itemStateChanged(ItemEvent e)
{
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
{
private TextField myTextField;
private Frame myFrame;
myFrame.show();
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() instanceof MenuItem)
myTextField.setText(Your Choice:
+ e.getActionCommand());
}
public class Terminator
extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
myFrame.dispose();
// use System.exit(0) for applications
}
}
}
O UTPUT :
PRACTICAL 10: WRITE AN APPLET THAT DRAWS TWO SETS OF EVERDECREASING RECTANGLES ONE IN OUTLINE FORM AND ONE FILLED
ALTERNATELY IN BLACK AND WHITE.
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
{
public static final int W = 200;
public static final int H = 200;
public void paint(Graphics g)
{
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;
EXERCISE:
D EVELOP AN APPLET TO DISPLAY THE MESSAGE H APPY N EW Y EAR WITHIN A TEXT FIELD .
Code:
Output:
E XTEND THE PREVIOUS PROGRAM SO THAT THE MESSAGE H APPY N EW Y EAR WILL APPEAR
WITHIN A TEXT FIELD WHEN THE BUTTON WITH THE CAPTION Y EAR IS PUSHED , WHILE THE
MESSAGE H APPY N EW M ILLENIUM WILL APPEAR WITHIN THE TEXT FIELD WHEN THE
BUTTON WITH THE CAPTION MILLENIUM IS PUSHED .
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:
W RITE AN APPLET TO DISPLAY FOUR RADIO BUTTONS WITH THE CAPTIONS S ANDWICH 1,
S ANDWICH 2, S ANDWICH 3 AND S ANDWICH 4. C REATE A TEXT FIELD AND USE IT TO
INDICATE WHICH DISH IS SELECTED .
Code:
Output:
C REATE A CHOICE CONTROL TO SELECT ONE OF THE FOUR FONTS T IMES , S ARIF , S AN
S ARIF AND R OMAN . C REATE ANOTHER CHOICE CONTROL TO SELECT ON OF THE FIVE
COLOURS GREEN , RED , YELLOW , WHITE AND ORANGE . M AKE PROVISION TO REPORT THE
SELECTED COLOUR IN THE FORM OF A LABEL .
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);
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
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 ;
public static void main(String[] args) {
JDBCCRUD obj = new JDBCCRUD();
obj.createUI();
obj.connect();
}
private void createUI()
{
JFrame frame = new JFrame(JDBC CREATE/READ/UPDATE/DELETE);
//Layout of Main Window
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c,BoxLayout.Y_AXIS));
lblFname = new JLabel(First Name :);
lblLname = new JLabel(Last Name :);
txtFname = new JTextField(,15);//To adjust width
txtLname = new JTextField();
JPanel pnlInput = new JPanel(new GridLayout(4,2));
pnlInput.add(lblFname);
pnlInput.add(txtFname);
pnlInput.add(lblLname);
pnlInput.add(txtLname);
btnInsert = new JButton(Insert);
btnInsert.addActionListener(this);
btnUpdate = new JButton(Update);
btnUpdate.addActionListener(this);
btnDelete = new JButton(Delete);
btnDelete.addActionListener(this);
btnClear = new JButton(Clear);
btnClear.addActionListener(this);
JPanel pnlButton = new JPanel(new GridLayout(1,4));
pnlButton.add(btnInsert);
pnlButton.add(btnUpdate);
pnlButton.add(btnDelete);
pnlButton.add(btnClear);
JPanel pnlAns = new JPanel(new GridLayout(4,2));
lblf = new JLabel(First Name :);
lbll = new JLabel(Last Name :);
lblfVal = new JLabel();
lbllVal = new JLabel();
pnlAns.add(lblf);
pnlAns.add(lblfVal);
pnlAns.add(lbll);
pnlAns.add(lbllVal);
btnPrev = new JButton( << );
btnPrev.setActionCommand(Prev);
btnPrev.addActionListener(this);
btnNext = new JButton( >> );
btnNext.setActionCommand(Next);
btnNext.addActionListener(this);
JPanel pnlNavigate = new JPanel(new GridLayout(1,2));
pnlNavigate.add(btnPrev);
pnlNavigate.add(btnNext);
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))
{
insertData();
}else if(cmd.equals(Update))
{
updateData();
}else if(cmd.equals(Delete))
{
deleteData();
}else if(cmd.equals(Prev))
{
previous();
}else if(cmd.equals(Next))
{
next();
}else if(cmd.equals(Clear))
{
clearControls();
}
}
private void connect()
{
try
{
Class.forName(com.mysql.jdbc.Driver);
con = DriverManager.getConnection(jdbc:mysql://localhost/students,root, );
}
catch(Exception e)
{
System.out.println(Unable to connect);
}
}
private void disconnect()
{
try
{
con.close();
}
catch(Exception e) {}
}
private void insertData()
{
try
{
String sql = Insert Into StudentData(FName,LName) +Values
(+txtFname.getText()+,+txtLname.getText()+);
Statement statement = con.createStatement();
statement.execute(sql);
createMessageBox(Inserted Successfully);
clearControls();
rs.close();
rs=null;
}
catch(Exception e)
{
createMessageBox(e.getMessage());
}
}
private void updateData()
{
try
{
String sql = Update StudentData Set LName=+txtLname.getText()+Where
FName=+txtFname.getText()+;
Statement statement = con.createStatement();
int count=statement.executeUpdate(sql);
createMessageBox(Updated Successfully);
clearControls();
rs.close();
rs=null;
}
catch(Exception e)
{
createMessageBox(e.getMessage());
}
}
private void deleteData()
{
try
{
String sql = delete
+txtFname.getText()+;
from
StudentData
where
FName
//statement.execute(sql);
statement.executeUpdate(sql);
createMessageBox(Record of +txtFname.getText()+ Deleted Successfully);
clearControls();
rs.close();
rs=null;
}
catch(Exception e)
{
createMessageBox(e.getMessage());
}
}
private void previous()
{
try
{
if(rs == null)
{
String sql = Select FName,LName from StudentData;
Statement
statement
=
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABL
rs = statement.executeQuery(sql);
}
if(rs.previous()&& !rs.isBeforeFirst())
{
populateControls();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void next()
{
try
{
if(rs == null)
{
String sql = Select FName,LName from StudentData;
Statement
statement
=
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONL
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)
{
JFrame frame = new JFrame(Result);
JLabel lbl = new JLabel(msg);
frame.add(lbl);
frame.setSize(200,200);
frame.setVisible(true);
}
private void clearControls()
{
String empty = ;
txtFname.setText(empty);
txtLname.setText(empty);
lblfVal.setText(empty);
lbllVal.setText(empty);
}
private void populateControls()
{
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
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;
public static void main(String[] args) {
JDBCPriceDemo obj = new JDBCPriceDemo();
obj.connect();
obj.createUI(); }
private void createUI()
{
JFrame frame = new JFrame(JDBC Product Price Demo);
frame.setLayout(new GridLayout(3,3));
lblItem = new JLabel(Select Product to check price:);
JComboBox cmbItemList=new JComboBox();
try{
Statement stmt = con.createStatement();
String query = SELECT * FROM ProductTable;
rs1 = stmt.executeQuery(query);
while (rs1.next())
{
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);
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
product= itemEvent.getItem().toString();
try {
Statement st = con.createStatement();
}
private void disconnect()
{
try
{
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. Thirdparty 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
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
clients 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.
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 users 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 websites 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 cookies 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>);
}
public void destroy()
{
// This is optional step but if you like you
// can write hitCount value in your database.
}
}
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
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=submitvalue=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
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
PrintWriter pw=res.getWriter();
pw.println(<h1>);
Cookie[] c=req.getCookies();
for(Cookie k:c)
{
pw.println(k.getValue());
}
pw.println(</h1>);
}
}
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
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.
Tag libraries provide a platform independent way of extending the capabilities of a
Web server.
JSPs are compiled into Java Servlets by a JSP compiler. A JSP compiler may generate
a servlet in Java code that is then compiled by the Java compiler, or it may generate byte
code for the servlet directly.
JSP technology enables Web developers and designers to rapidly develop and easily
maintain, information-rich, dynamic Web pages that leverage existing business systems.
As part of the Java technology family, JSP technology enables rapid development of Webbased applications that are platform independent.
JSP technology separates the user interface from content generation, enabling
designers to change the overall page layout without altering the underlying dynamic
content
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
<?xml version=1.0 encoding=utf-8?>
</Server>
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 tomcatuser.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.
4 : Check your username and password(optional)
http://localhost:9999/
ThenClick TomcatManager andgiveusername(admin)andpassword(admin123).
Ifsuccessfullylogin,thenusernameandpasswordperfecltlyset.
Otherwise, check tomcat-users.xml file.
Step 6: Set path, java_home, and classpath variable as required from command line.
For example:
SetJAVA_HOME=C:\ProgramFiles\Java\jdk1.8.0_25\
set PATH=%JAVA_HOME%;%PATH%
setCLASSPATH=.;D:\apache-tomcat-8.0.15\lib\jsp-api.jar;D:\apache-tomcat8.0.15\webapps\JSPDemo; C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\
connector-java-5.1.34-bin %classpath%
Step7 : Run HelloWorld.jsp program in browser using following link:
http://localhost:9999/JSPDemo/HelloWorld.jsp
Step 8: Observe the output:
mysql-
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h1 align=center>
<b>REGISTRATION FORM</b>
</h1>
<form action=welcome.jsp method=post>
<div>
<label for=inputFirstname>First Name
</label>
<div>
<input type=text name=firstname maxlength=12
placeholder=firstname></input>
</div>
</div>
<div>
<label for=inputLastname>Last Name
</label>
<div>
<input type=text name=lastname maxlength=12
placeholder=lastname></input>
</div>
</div>
<div>
<label for=inputMobile>Mobile</label>
<div>
<input type=text name=mobile maxlength=10
placeholder=Ex:95xxxx4104></input>
</div>
</div>
<div>
<label for=inputEmail>E-mail</label>
<div>
<input type=text name=email maxlength=50
placeholder=rakesh@gmail.com></input>
</div>
</div>
<div>
<label for=gender>Gender</label>
<div>
<input type=radio name=optionsRadios id=optionsRadios1
value=Male checked>Male <input type=radio
name=optionsRadios id=optionsRadios2 value=Female>Female
</div>
</div>
<div>
<label for=inputAddress>Address </label>
<div>
<input type=text name=address maxlength=70 id=address
placeholder=Address></input>
</div>
</div>
<div>
<label for=inputCity>City </label>
<div>
<input type=text name=city id=city placeholder=Noida>
</input>
</div>
</div>
<div>
<label for=inputState>State </label>
<div>
<input type=text id=state name=state id=state
placeholder=Delhi></input>
</div>
</div>
<div>
<div>
<input type=reset value=Reset /> <input
type=submit value=Submit />
</div>
</div>
</form>
</body>
</html>
</body>
</html>
welcome.jsp
<%@ page language=java contentType=text/html; charset=UTF-8
pageEncoding=UTF-8%>
<html>
<head>
<title>Details Of User</title>
</head>
<body>
<h3>
<left>
<i>REGISTRATION HAS BEEN COMPLETED SUCCESSFULLY.</i>
</left>
</h3><br>
FirstName:<%=request.getParameter(firstname)%><br>
LastName:<%=request.getParameter(lastname)%><br>
email:<%=request.getParameter(email)%><br>
mobile :<%=request.getParameter(mobile)%><br>
city :<%=request.getParameter(city)%><br>
State:<%=request.getParameter(state)%><br>
Gender:<%=request.getParameter(optionsRadios)%><br>
address:<%=request.getParameter(address)%>
</body>
</html>
O UTPUT
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
<%@page
contentType=text/html
errorPage=Error.jsp%>
pageEncoding=UTF-8
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<br/><br/><br/><br/><br/>
<center>
<h2>
<%
String a=session.getAttribute(username).toString();
out.println(Hello +a);
%>
</h2>
<br/>
<br/>
<br/><br/><br/><br/><br/>
<a href=logout.jsp>Logout</a>
</center>
</body>
</html>
Logout.jsp
<%@page contentType=text/html pageEncoding=UTF-8%>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<%
session.removeAttribute(username);
session.removeAttribute(password);
session.invalidate();
%>
<h1>Logout was done successfully.</h1>
</body>
</html>
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.
last_name
uname
pass
regdate
login.jsp
</tbody>
</table>
</center>
</form>
</body>
</html>
Logincheck.jsp
<%@ page import =java.sql.* %>
<%
String userid = request.getParameter(uname);
String pwd = request.getParameter(pass);
Class.forName(com.mysql.jdbc.Driver);
Connection con =
DriverManager.getConnection(jdbc:mysql://localhost/logindatabase,
root, );
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery(select * from members where uname= +
userid + and pass= + pwd + );
if (rs.next()) {
session.setAttribute(userid, userid);
response.sendRedirect(success.jsp);
} else {
out.println(Invalid password <a href=login.jsp>try again</a>);
}
%>
Newregistration.jsp
<%@page contentType=text/html pageEncoding=UTF-8%>
<html>
<head>
<title>Registration</title>
</head>
<body>
<form method=post action=registrationsubmit.jsp>
<center>
<table border=1 width=30% cellpadding=5>
<thead>
<tr>
<th colspan=2>Enter Information Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Name</td>
<td><input type=text name=fname value= /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type=text name=lname value= /></td>
</tr>
<tr>
<td>Email</td>
<td><input type=text name=email value= /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type=text name=uname value= /></td>
</tr>
<tr>
<td>Password</td>
<td><input type=password name=pass value= />
</td>
</tr>
<tr>
<td><input type=submit value=Submit /></td>
<td><input type=reset value=Reset /></td>
</tr>
<tr>
<td colspan=2>Already registered!! <a
href=login.jsp>Login Here</a></td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
</html>
Registrationsubmit.jsp
<%@ page import =java.sql.* %>
<%
String user = request.getParameter(uname);
String pwd = request.getParameter(pass);
String fname = request.getParameter(fname);
String lname = request.getParameter(lname);
String email = request.getParameter(email);
Class.forName(com.mysql.jdbc.Driver);
Connection con =
DriverManager.getConnection(jdbc:mysql://localhost/logindatabase,
root, );
Statement st = con.createStatement();
int i = st.executeUpdate(insert into members(first_name, last_name,
email, uname, pass, regdate) values ( + fname + , + lname + , +
email + , + user + , + pwd + , CURDATE()));
if (i > 0) {
response.sendRedirect(welcome.jsp);
}
else {
response.sendRedirect(login.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:
</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()))
{
int cmarks = Integer.parseInt(c);
int jmarks = Integer.parseInt(j);
int nmarks = Integer.parseInt(n);
int vmarks = Integer.parseInt(v);
int dmarks = Integer.parseInt(d);
int total = cmarks+jmarks+nmarks+vmarks+dmarks;
int avg = (total)/5;
int percent = avg;
String grade =;
if(percent < 40){
grade = E;
//request.setAttribute(grade, grade);
}
else if(percent >= 40 && percent <=44){
grade = D;
}
else if(percent >=45 && percent <=49){
grade = D+;
}
else if(percent >=50 && percent <=54){
grade = C-;
}
else if(percent >=55 && percent<=59){
grade = C;
}
else if(percent >=60 && percent <=64){
grade = C+;
}
else if(percent >=65 && percent<=69){
grade = B-;
}
else if(percent >=70 && percent <=74){
grade = B;
}
else if(percent >=75 && percent <=79){
grade = B+;
}
else if(percent >=80 && percent <=84){
grade = A;
}
else if (percent >=85 && percent <=100){
grade = A+;
}
request.setAttribute(Grade, grade);
%>
<table>
<tr>
<td><b>Aggregate Marks</b></td><td></td>
<td align=center><%=total %></td>
</tr>
<tr>
<td><b>Grade</b></td><td></td>
<td align=center><%=grade %></td>
</tr>
</table>
<%
}
%>
</body>
</html>
O UTPUT