You are on page 1of 176

Table

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.



ADVANCED JAVA LABORATORY MANUAL


By Gayatri Patel
Advanced JAVA Laboratory Manual

Copyright © Reserved by the Author


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.


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.”

Four definitions of applet:


A small application
A secure program that runs inside a web browser
A subclass of java.applet.Applet
An instance of a subclass of java.applet.Applet

The APPLET HTML Tag


Applets are embedded in web pages using the <APPLET> and </APPLET>
tags. The <APPLET> tag is similar to the <IMG> tag.
The CODE attribute of <APPLET> tag tells the browser where to
look for the compiled .class file. It is relative to the location of the
source document.
The CODEBASE attribute is a URL that points at the directory where
the .class 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>

Executing Applet using Web Browser


TestApplet.java
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.

Executing Applet directly using Appletviewer


TestApplet.java
import java.applet.*;
import java.awt.*;

/*

<APPLET code=“TestApplet.class” width=350 height=200></APPLET>


*/
public class TestApplet extends Applet

public void paint (Graphics g) {


g.drawString(“Welcome to Applet world”,20,40); }

The Basic Applet Life Cycle


1. The browser reads the HTML page and finds any <APPLET> tags.
2. The browser parses the <APPLET> tag to find the CODE and
possibly CODEBASE attribute.
3. The browser downloads the .class file for the applet from the URL
found in the last step.
4. The browser converts the raw bytes downloaded into a Java class, that
is a java.lang.Class object.
5. The browser instantiates the applet class to form an applet object.
This requires the applet to have a noargs constructor.
6. The browser calls the applet’s init() method.
7. The browser calls the applet’s start() method.
8. While the applet is running, the browser passes any events intended
for the applet, e.g. mouse clicks, key presses, etc., to the applet’s
handleEvent() method. Update events are used to tell the applet that it
needs to repaint itself.
9. The browser calls the applet’s stop() method.
10. The browser calls the applet’s destroy() method.
All applets have the following four methods: public void init();
public void start();
public void stop();
public void destroy();

Simple Methods to Design Applet

Method 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 ( To obtain the current settings for


) the background color

Color getForeground ( ) To obtain the current settings for


the foreground color

Applet getApplet ( To obtain the applet specified by


String name ) given name from the current applet
context.
Void showStatus( To display the status message in
String status ) the status bar of applet window

URL To obtain the directory of the


getDocumentBase ( ) current browser page.

URL getCodeBase( ) To obtain the directory from


which the applet’s class file was
loaded

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:









Passing Parameters to Applets


Parameters are passed to applets in NAME=VALUE pairs in <PARAM>
tags between the opening and closing APPLET tags. Inside the applet, you read
the values passed through the PARAM tags with the getParameter() method of
the java.applet.Applet class.

<param name = parameter_name value =


parameter_value> Complete syntax for the APPLET tag
including Param Tag <APPLET
CODEBASE = codebaseURL
CODE = appletFile
ALT = alternateText
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:

The Coordinate System


Java uses the standard, two-dimensional, computer graphics coordinate
system. The first visible pixel in the upper left-hand corner of the applet canvas
is (0, 0). Coordinates increase to the right and down.
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 applet’s 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 you’re drawing.
Commonly used methods of Graphics class are as follows:

drawString ( String s, int x, int y ) To output a string to an applet at


a specified position. It is called from
within update( ) or paint( ).

drawChars ( char c[ ], int start_index, int To output characters of array to


num_of_char, int x, int y ) an applet at specified location.

drawChars ( byte c[ ], int start_index, int To output characters of byte’s


num_of_char, int x, int y ) array to an applet at specified
location.

drawLine (int x1, int y1, int x2, int y2); To draw a line at specific
location.

drawOval ( int x, int y, int width, int To draw an oval at specified


height) location x,y having specific height
and width

setColor ( Color c ) To set the color of the object

fillOval ( int x, int y, int width, int height To fill color in Oval
)

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 To fill color in rectangle
)

drawArc (int x, int y, int width, int To draw an Arc


height, int arcwidth, int archeight )

fillArc (int x, int y, int width, int height, To fill color in Arc.
int arcwidth, int archeight )

setFont ( Font f) To set the 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 you’re 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.
Here’s the code: import java.applet.*; import java.awt.*;

public class FillAndCenter extends Applet {

public void paint(Graphics g) {


int appletHeight = this.getSize().height; int appletWidth =
this.getSize().width; int rectHeight = appletHeight/3; int rectWidth =
appletWidth/3; int rectTop = (appletHeight - rectHeight)/2; int rectLeft =
(appletWidth - rectWidth)/2;
g.fillRect(rectLeft, rectTop, rectWidth-1, rectHeight-1); }

Output

Ovals and Circles


Java has methods to draw outlined and filled ovals. As you’d probably guess
these methods are called drawOval() and fillOval() respectively. As you might
not guess they take identical arguments to drawRect() and fillRect(), i.e.
public void drawOval(int left, int top, int width, int height) public void
fillOval(int left, int top, int width, int height) Instead of the dimensions of the
oval itself, the dimensions of the smallest rectangle which can enclose the oval
are specified. The oval is drawn as large as it can be to touch the rectangle’s
edges at their centers. This picture may help:
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

Using Colors with Applets


The syntax of the constructor to create custom colors: Color ( int red, int
green, int blue);
Example:
new Color (255, 100, 100); // light red Calling a constructor to set the
color
Color c=new Color (255, 175, 175)
Color c=new Color (255, 175, 175)
g.setColor (c)

Color Red Green Blue


Obtained Value Value Value

White 255 255 255

Black 0 0 0

Light Gray 192 192 192

Dark Gray 128 128 128

Red 255 0 0

Green 0 255 0

Blue 0 0 255

Yellow 255 255 0

Purple 255 0 255

Table of RGB values of common colors


You create new colors using the same RGB triples that you use to set
background colors on web pages. However you use decimal numbers instead of
the hex values used by the bgcolor tag. For example medium gray is Color(127,
127, 127). Pure white is Color(255, 255, 255). Pure red is (255, 0, 0) and so on.
As with any variable you should give your colors descriptive names. For
instance Color medGray = new Color(127, 127, 127);
Color cream = new Color(255, 231, 187);
Color lightGreen = new Color(0, 55, 0);
A few of the most common colors are available by name. These are

Color.black 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 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.*;

/*

<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);
Color c2=new Color(128,128,128); g.setColor(c1); int r=c1.getRed( );
int gr=c1.getGreen( ); int b=c1.getBlue( );
g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,20);

c1=c1.darker( );

g.setColor(c1);
g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE =
“+b,10,40);

g.setColor(c2);

g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,60);


c2=c2.brighter( );

g.setColor(c2); g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE


= “+b,10,80);

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 {

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 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:







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)
S PECIFIC 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 Circle.
L EARNING O UTCOMES
Explain & Practice Graphic Drawing method drawOval() to draw
circle.
A SSUMPTIONS
Oracle JDK installed
Editor Like notepad, Jcreator available for program development

E NVIRONMENT VARIABLES LIKE JAVA_H OME , P ATH , C LASSPATH ARE


CONFIGURED .C ODE
CONFIGURED .C ODE

import java.awt.*;
import java.applet.*;

/*

<applet code=CenterCircle height=500 width=300> </applet>

*/

public class CenterCircle extends Applet

int w,h;
public void init()

w=getWidth();
h=getHeight();

public void paint(Graphics g) {


g.setColor (Color.blue); g.drawOval ((w/2)-50,(h/2)-50,100,100);
g.drawString(“J.B.Patel”, w/2,h/2); g.setColor (Color.green); showStatus
(“This applet draws circle in the center of the applet”); }

O UTPUT

PRACTICAL 2: DRAW TEN RED CIRCLES IN A VERTICAL


COLUMN IN THE CENTER OF THE APPLET.

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.*;

/*

<applet code=TenRed height=500 width=300> </applet>

*/

public class TenRed extends Applet

int w,h;
public void init()

{
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;

Output

PRACTICAL 3: BUILT AN APPLET THAT DISPLAYS A


HORIZONTAL RECTANGLE IN ITS CENTER. LET THE
RECTANGLE FILL WITH COLOR FROM LEFT TO RIGHT.

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.*;

/*

<applet code=FillRectGrad height=500 width=300> </applet>

*/

public class FillRectGrad extends Applet

int w,h, x1=100,x2,y1=50,y2=150, flag=0;


Thread t;
Graphics g1;
public void init()

w=getWidth();
h=getHeight();

public void paint(Graphics g)

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



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.

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.*;

/*

<applet code=MousePosition height=300 width=400> </applet>

*/

public class MousePosition extends Applet implements MouseListener,


MouseMotionListener {
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)


{
}
public void mouseReleased(MouseEvent m)

public void mouseDragged(MouseEvent m)

mx=m.getX( );
my=m.getY( );
s=“Dragging:”;
repaint( );

public void mouseMoved(MouseEvent m)

mx=m.getX( );
my=m.getY( );
s=“Moving:”;
repaint( );

}
}

public void paint(Graphics g)

g.drawString(“Mouse”+s+mx+”,”+my, 10, 10); g.setColor (Color.red);


g.drawRect ( mx,my, 10, 10); }

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 :

When You Press Stop When You Press Start


Button Button

PRACTICAL 6: WRITE AN APPLET THAT USES THE MOUSE
LISTENER, WHICH OVERRIDES ONLY TWO METHODS WHICH
ARE MOUSE PRESSED AND MOUSERELEASED.

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>

*/

public class MouseState extends Applet implements MouseListener,


MouseMotionListener {
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)

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 When You Release 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


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 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.

Working with Frame Windows


After the applet, the type of window we will most often create is derived
from Frame. We will use it to create child windows within applets, and top-level
or child windows for applications. It creates a standard-style window. Following
are two of Frame’s constructors:
Frame( );
Frame(String title);
The first form creates a standard window that does not contain a title. The
second form creates a window with the title specified by title. Note that we
cannot specify the dimensions of the window. Instead, we must set the size of
the window after it has been created.

Creating a Frame Window in an Applet


This example overrides the applet window’s start( ) and stop( ) method s so
that they show and hide the child window, respectively. It also causes the child
window to be shown when the browser returns to the applet.
SampleFrame.java

/*

<applet code=“AppletFrame” width=300 height=50>


</applet>

*/

class SampleFrame extends Frame

SampleFrame(String title)

{
super(title);

public void paint(Graphics g)

g.drawString(“This is in frame window”, 10, 40);

public class AppletFrame extends Applet

Frame f;
public void init()

f = new SampleFrame(“A Frame Window”);


f.setSize(250, 250);
f.setVisible(true);

public void start()

f.setVisible(true);

public void stop()

{
{

f.setVisible(false);

public void paint(Graphics g)

g.drawString(“This is in applet window”, 10, 20);

Output:






Using AWT Controls, Layout Managers and Menus


Controls are components that allow a user to interact with his application in
various ways—for example; a commonly used control is the push button.
Control Fundamentals
The AWT supports the following types of controls:
Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text Area
Text Field
These controls are subclasses of Component.
Adding and Removing Controls
In order to include a control in a window, we must add it to the window. So,
we must first create an instance of the desired control and then add it to a
window by calling add( ), which is defined by Container. The add( ) method has
several forms. The following form is the one that is used for the first part of this
chapter:
Component add(Component compObj)
Here, compObj is an instance of the control that we want to add. A reference
to 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>

*/

public class LabelDemo extends Applet

public void init()

Label one = new Label(“One”); Label two = new Label(“Two”); Label


three = new Label(“Three”);
// add labels to applet window add(one);
add(two);
add(three);


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>

*/

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 = ””;


Checkbox Win98, winNT, solaris, mac;
public void init()

Win98 = new Checkbox(“Windows 98/XP”, null, true);


winNT = new Checkbox(“Windows NT/2000”);
solaris = new Checkbox(“Solaris”);
mac = new Checkbox(“MacOS”);
add(Win98);
add(winNT);
add(solaris);
add(mac);

public void paint(Graphics g)

Output:








Checkbox Group/Option Button


Only one check box in the group can be checked at any one time. These
check boxes are often called radio buttons. For creating a set of mutually
exclusive check boxes, we must first define the group to which they will belong
and then specify that group when we construct the check boxes. Check
box groups are objects of type CheckboxGroup. Only the default constructor is
defined, which creates an empty group.
We can determine which check box in a group is currently selected by
calling getSelectedCheckbox( ). We can set a check box by calling
setSelectedCheckbox( ). These methods are as follows:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox wh)
Example: Here is a program that uses check boxes that are part of a group.
//CBGroup.java
import java.awt.*;import java.applet.*;

/*

<applet code=“CBGroup” width=250 height=200>


</applet>

*/

public class CBGroup extends Applet

String msg = ””;


Checkbox Win98, winNT, solaris, mac;
CheckboxGroup cbg;
public void init()

cbg = new CheckboxGroup();


Win98 = new Checkbox(“Windows 98/XP”, cbg, true);
winNT = new Checkbox(“Windows NT/2000”, cbg, false);
solaris = new Checkbox(“Solaris”, cbg, false);
mac = new Checkbox(“MacOS”, cbg, false);
add(Win98);
add(winNT); add(solaris); add(mac);

public void paint(Graphics g)

msg = “Current selection: “;


msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);


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.*;

/*

<applet code=“ChoiceDemo” width=300 height=180>


</applet>

*/

public class ChoiceDemo extends 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);

public void paint(Graphics g)


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.*;

/*

<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

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.*;

/*

<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 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.*;

/*

<applet code=“TextAreaDemo” width=300 height=250>


</applet>

*/

public class TextAreaDemo extends Applet

public void init()


{

String val = “There are two ways of constructing ” + “a software design.\n”


+
“One way is to make it so simple\n” +
“that there are obviously no deficiencies.\n” +
“And the other way is to make it so complicated\n” + “that there are no
obvious deficiencies.\n\n” +
” -C.A.R. Hoare\n\n” +
“There’s an old story about the person who wished\n” +
“his computer were as easy to use as his telephone.\n” + “That wish has
come true,\n” +
“since I no longer know how to use my telephone.\n\n” + ” -Bjarne
Stroustrup, AT&T, (inventor of C++)”;
TextArea text = new TextArea(val, 10, 30);
add(text);



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.

Fig. Layout Managers at work


The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj);
Here, layoutObj is a reference to the desired layout manager. If we wish to
disable the layout manager and position components manually, pass null for
layoutObj. If we do this, we will need to determine the shape and position of
each component manually, using the setBounds( ) method defined by
Component.
Each layout manager keeps track of a list of components that are stored by
their names. The layout manager is notified each time we add a component to a
container. 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;
public void init()

Win98 = new Checkbox(“Windows 98/XP”, null, true);


winNT = new Checkbox(“Windows NT/2000”);
solaris = new Checkbox(“Solaris”);
mac = new Checkbox(“MacOS”);
setLayout(new FlowLayout(FlowLayout.CENTER));
add(Win98); add(winNT); add(solaris); add(mac);

public void paint(Graphics g)

}
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.*;

/*

<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:









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)

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()

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 :



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.

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);

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 :






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

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;

public void init()

myFrame = new Frame();


myFrame.addWindowListener(new Terminator());
myTextField = new TextField(20);
add(myTextField);
myFrame.setBounds(200,200,300,300);

// place myMenuBar at top of myFrame
MenuBar myMenuBar = new MenuBar();
myFrame.setMenuBar(myMenuBar);

Menu fileMenu = new Menu(“File”);


myMenuBar.add(fileMenu);

Menu editMenu = new Menu(“Edit”);


myMenuBar.add(editMenu);
MenuItem myMenuItem;

myMenuItem = new MenuItem(“Open”);


myMenuItem.addActionListener(this);
fileMenu.add(myMenuItem);

myMenuItem = new MenuItem(“Close”);
myMenuItem.addActionListener(this);
fileMenu.add(myMenuItem);

myMenuItem = new MenuItem(“Undo”);


myMenuItem.addActionListener(this);
editMenu.add(myMenuItem);

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


EVER-DECREASING 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;
g.drawRect(x1, y1, x 2, x 2);


public static void main(String args[])

Applet applet = new RectApplet();


Frame frame = new Frame();
frame.addWindowListener(new WindowAdapter()

public void windowClosing(WindowEvent e)

{
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:




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); 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”);

PRACTICAL 11: WRITE A DATABASE APPLICATION THAT USES


ANY JDBC DRIVER.

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.

PRACTICAL 12: DEVELOP A UI THAT PERFORMS THE


FOLLOWING SQL OPERATIONS:1) INSERT 2)DELETE
3)UPDATE.
S PECIFIC O BJECTIVES
After performing this practical student will be able to:
Learn how to use JDBC to perform CRUD Operation (Create/ Read/
Update/ Delete)
Learn how to use JDBC API and JDBC Drivers for databae
functions.

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 ;

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 from StudentData where FName =


’”+txtFname.getText()+”’”; Statement statement = con.createStatement();
//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_UPDAT
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_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)
{

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

Message when u press


Insert Button

JDBC Update Operation

Change Thakkar to Patel Message when u press


Update Button

JDBC Delete Operation

Navigate to Sanjay Dhami Message when u press


Record Update Button


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;

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();
rs2 = st.executeQuery(“SELECT Price FROM ProductTable WHERE
ProductName = ’”+ product +”’”); if (rs2!=null) {
rs2.next();
lblSelectedItem.setText(product.toString());
lblItemPrice.setText(String.valueOf(rs2.getInt(1)));
rs2.close(); }
}
catch (SQLException ex) {}
catch(Exception e) {}

};
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”);
}

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. 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.

Inserting Data in Database table using Statement To


accomplish our goal we first have to make a class named
as ServletInsertingData, which must extends the abstract
HttpServlet class, the name of the class should be such
that other person can understand what this program is
going to perform. The logic of the program will be
written inside the doGet() method that takes two
arguments, first is HttpServletRequest interface and the
second one is the HttpServletResponse interface and this
method can throw ServletException.
Inside this method call the getWriter() method of the PrintWriter class. We
can insert the data in the database only and only if there is a connectivity
between our database and the java program. To establish the connection between
our database and the java program we first need to call the method forName(),
which is static in nature of the class Class. It takes one argument which tells
about the database driver we are going to use. Now use the static method
getConnection() of the DriverManager class. This method takes three arguments
and returns the Connection object. SQL statements are executed and results are
returned within the context of a connection. Now your connection has been
established. Now use the method createStatement() of the Connection object
which will return the Statement object. This object is used for executing a static
SQL statement and obtaining the results produced by it. We have to insert a
values into the table so we need to write a query for inserting the values into the
table. This query we will write inside the executeUpdate() method of the
Statement object. This method returns int value.
If the record will get inserted in the table then output will show “record has
been inserted” otherwise “sorry! Failure”.

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)

PRACTICAL 14: WRITE A SIMPLE SERVLET PROGRAM WHICH


MAINTAINS A COUNTER FOR THE NUMBER OF TIMES IT HAS
MAINTAINS A COUNTER FOR THE NUMBER OF TIMES IT HAS
BEEN ACCESSED SINCE IT’S LOADING; INITIALIZE THE
COUNTER USING DEPLOYMENT DESCRIPTOR.

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

PRACTICAL 15: CREATE A FORM PROCESSING SERVLET WHICH


DEMONSTRATES USE OF COOKIES.

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

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

PRACTICAL 16: CREATE A FORM PROCESSING SERVLET WHICH


DEMONSTRATES USE OF SESSIONS.

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.

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
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 Web-based 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 Create and Run a simple JSP program using tomcat
Here I am going to explain for write create a simple jsp program and run that
program in apache tomcat. This process has some steps. The following steps are
based on windows operating system Java Server Pages are saved with .jsp
extension.
Installation and execution of JSP
Follow these steps to run JSP Page:
Step 1: Download and install latest Apache Tomcat and JAVA.
Step 2: Create directory “JSPDemo” and apache D:\apache-tomcat-
8.0.15\webapps\JSPDemo directories under the webapps as shown here: Step
3: Create simple HelloWorld.jsp program using any editor like notepad:
<%@page contentType=“text/html” pageEncoding=“UTF-8”%> <html>
<head>

<title>First JSP Page</title> </head>


<body>

<p> Hi, <h3><%=“Hello!” %></h3></p>


</body>
</html>

Step 4: Save this file as HelloWorld.jsp in D:\apache-tomcat-
8.0.15\webapps\JSPDemo\JSPApp directory:

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 port=“8005” shutdown=“SHUTDOWN”>



<Connector port=“9999” protocol=“HTTP/1.1”
connectionTimeout=“20000”
redirectPort=“8443” />


</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 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.

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-
tomcat-8.0.15\webapps\JSPDemo; C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\
;
mysql-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:


PRACTICAL 17: WRITE A SIMPLE JSP PROGRAM FOR USER


REGISTRATION & THEN CONTROL WILL BE TRANSFER IT INTO
SECOND PAGE.

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

<%@ page language=“java” contentType=“text/html; charset=UTF-8”


pageEncoding=“UTF-8”%>
<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

PRACTICAL 18 :WRITE A SIMPLE JSP PROGRAM FOR USER


LOGIN FORM WITH STATIC & DYNAMIC DATABASE.
LOGIN FORM WITH STATIC & DYNAMIC DATABASE.

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

<%@page contentType=“text/html” pageEncoding=“UTF-8”


errorPage=“Error.jsp”%> <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.
->Create logindatabase Database in MySQL.
->Create members Table under logindatabase Database.
Members:

first_name last_name email uname pass regdate

login.jsp

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


<head>
<title>JSP Example</title> </head>
<body>
<form method=“post” action=“logincheck.jsp”> <center>
<table border=“1” width=“30%” cellpadding=“3”> <thead> <tr> <th
colspan=“2”>Login Here</th> </tr> </thead>
<tbody> <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=“Login” ><td> <td><input type=“reset” value=“Reset” ><td> </tr>
<tr> <td colspan=“2”>Not Yet Registered!! <a
href=“Newregistration.jsp”>Register Here</a></td> </tr> </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:

PRACTICAL 19 :WRITE A JSP PROGRAM TO DISPLAY THE


GRADE OF A STUDENT BY ACCEPTING THE MARKS OF FIVE
SUBJECTS.

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()))

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

You might also like