You are on page 1of 82

GOVERNMENT POLYTECHNIC

FOR GIRLS, AHMEDABAD

TERM WORK

DEPARTMENT OF
COMPUTER ENGINEERING

ADVANCE JAVA PROGRAMMING


(3360701)

VI SEMESTER (TERM – 202)


(10-12-2020 to 01-05-2021)

Submitted by

Enrollment No 186140307110
Name Thakkar Dhara Manishbhai
CERTIFICATE

GOVERNMENT POLYTECHNIC FOR GIRLS

This is to certify that the Thakkar Dhara Manishbhai having

Enrollment No. 186140307110 of Program Computer Engineering has

satisfactorily completed the term work in course Advance Java Programming with Subject

Code 3360701 of semester VI.

Date of Submission 26/04/2021 . Staff in-charge D.S.Baldev .

Head of Department R . M . Shaikh .


Contents
Name:Thakkar Dhara Manishbhai Enrollment No.: 186140307110
Semester: 6th Batch: B2
Course: Advance Java Programming (3360701)
Sr. Page
Aim
No No
1 Develop 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 4
your name centered in a circle.( using drawOval() method)
2 Write a program to draw draw ten red circles in a vertical column in centre of the applet 6
3 Build an applet that displays a horizontal rectangle in its centre. Let the rectangle be filled
8
with colour from left to right.
4 Write a program to pass parameter to applet to set the message on its status bar. 10
5 Develop an applet that displays moving banner. Consider string “Advance Java
12
Programming”.
6 Develop 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 18
current mouse position.
7 Develop an applet that contains one button. Initialize the label on the button to “start”.
When the user presses the button, change the label to “stop”. Toggle the button label 20
between these two values each time the button is pressed.
8 Develop an applet that uses the mouse listener, which overrides only two methods which are
22
mouse Pressed and mouse Released.
9 Develop a program that has only one button in the applet, clicking on the button cycles
through the colors: red->green>blue and so on. One color changes per click.(use get 24
Background() method to get the current color)
10 Develop an program 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
27
determines the color of the canvas. For example, if the user selects both “Red” and “Blue”,
the canvas should be purple.
11 Create an application that displays a frame with a menu bar. When a user selects any menu
30
or menu item, display that selection on a text area in the center of the frame
12 Write a frame that has only one button in it, clicking on the button number is increment by
33
one and display the number in the frame.
13 Write a GUI based application using Jlabel, JTextField and JButton that accept your name
35
and display it.
14 Develop a database application that uses any JDBC driver. 41
15 Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update. 43
Write a program to present a set of choice for user to select a product & display the price of
16 47
product.
Develop a simple servlet program which maintains a counter for the number of times it has
17 54
been accessed since its loading; initialize the counter using deployment descriptor.
Write an HTML code to create login form having one submit button, two textboxes labeled
as Login name and Password as respectively. Write a Servlet class named as ReadParameter
18 57
to read these two parameters and display entered parameters values on the page using
doGet() or doPost() method when the user clicked on the submit button.
19 Create a web form which processes servlet and demonstrates use of cookies and sessions. 60
Develop a simple JSP program for user registration and then control will be transferring it
20 68
into the second page.
21 Develop a simple JSP program for user login form with static database 71
Develop a simple JSP program to create a form having two textboxes and one submit
22 button. Write JSP code to display the addition of these two numbers when the user clicks on 74
the submit button.
Develop a JSP program to display the grade of a student by accepting the marks of five
23 76
subjects.
Department of Computer Engineering Advance Java Programming (3360701)

UNIT 1
JAVA APPLETS

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

JAVA APPLETS
An Applet is a Java program that can be embedded into a web page. It runs inside the web browser and
works at client side. An Applet is embedded in an HTML page using the APPLET tag and hosted on a
web server. Applets are used to make the web site more dynamic and entertaining.
Important points:
 All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
 Applets are not stand-alone programs. Instead, they run within either a web browser or an applet
viewer. JDK provides a standard applet viewer tool called applet viewer.
 In general, execution of an Applet does not begin at main() method.
 Output of an applet window is not performed by System.out.println(). Rather it is handled with
various AWT methods, such as drawString().
Software Required: JDK, Appletviewer Tool, JAVA enabled Web Browser.
Package: java.applet.*, java.awt.*.

Methods of Applet Class


Called by the browser or applet viewer to inform this applet that it has
void init()
been loaded into the system.
Called by the browser or applet viewer to inform this applet that it
void start()
should start its execution.
Called by the browser or applet viewer to inform this applet that it
void stop()
should stop its execution.
Called by the browser or applet viewer to inform this applet that it is
void destroy() being reclaimed and that it should destroy any resources that it has
allocated.
void showStatus(String s) Requests that the argument string be displayed in the "status window".

String getParameter(String attr) Returns the value of the named parameter in the HTML tag.

Methods of Component Class

void paint(Graphics g) Paints this component.

void setBackground(Color c) Sets the background color of this component.

void setForeground(Color c) Sets the foreground color of this component.

Color getBackground() Gets the background color of this component.

Color getForeground() Gets the foreground color of this component.

void repaint() Repaints this component.

void update(Graphics g) Updates this component.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Methods of Graphics Class
void drawLine(int x1, int y1, Draws a line, using the current color, between the points (x1, y1) and
int x2, int y2) (x2, y2) in this graphics context's coordinate system.
void drawOval(int x, int y,
Draws the outline of an oval.
int width, int height)
void drawPolygon(int[] xPoints,
Draws a closed polygon defined by arrays of x and y coordinates.
int[] yPoints, int nPoints)
void drawRect(int x, int y,
Draws the outline of the specified rectangle.
int width, int height)
void drawArc(int x ,int y,
Draws the outline of a circular or elliptical arc covering the specified
int w,int h , int startAngle,
rectangle.
int arcAngle)
void drawString(String str, int x, Draws the text given by the specified string, using this graphics
int y) context's current font and color.
void setColor(Color c) Sets this graphics context's current color to the specified color.

Color getColor() Gets this graphics context's current color.


void fillOval(int x, int y,
Fills an oval bounded by the specified rectangle with the current color.
int width, int height)
void fillPolygon(int[] xPoints,
Fills a closed polygon defined by arrays of x and y coordinates.
int[] yPoints, int nPoints)
void fillRect(int x, int y,
Fills the specified rectangle.
int width, int height)
void fillArc(int x ,int y, int w,int
Fills a circular or elliptical arc covering the specified rectangle.
h , int startAngle, int arcAngle)

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 1
Develop 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).

Prac1Circle.java
import java.applet.Applet;
import java.awt.*;

public class Prac1Circle extends Applet


{
public void paint(Graphics g)
{
g.drawOval(150,50,200,200);
g.drawString("ABC",245,150);
}
}

Circle.html
<HTML>
<BODY>
<APPLET CODE="Prac1Circle.class" WIDTH="500" HEIGHT="300">
</APPLET>
</BODY>
</HTML>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
This Program is to draw the circle in the center of the Applet. Created an Applet of width 500 and height
300 by setting the attributes of applet tag in html code. Circle is of 100 pixels radius created using
drawOval() Method of graphics Class and “ABC ” written in the center of the circle using drawString()
Method of the Graphics class.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 2
Write a program to draw ten red circles in a vertical column in the centre of the applet.

Prac2FillCircle.java
import java.applet.Applet;
import java.awt.*;

public class Prac2FillCircle extends Applet


{
public void paint(Graphics g)
{
int h=2;
for(int i=1;i<=10;i++)
{
g.setColor(Color.RED);
g.fillOval(230,h,50,50);
h=h+50;
}

}
}

Circle2.html
<HTML>
<BODY>
<APPLET CODE="Prac2FillCircle.class" WIDTH="500" HEIGHT="500">
</APPLET>
</BODY>
</HTML>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
This program is to draw ten red circles in a vertical column in the centre of the applet.Created an Applet
of width 500 and height 500 by setting the attributes of applet tag in html code. Circle is created using the
drawOval() method. To draw ten circles in a vertical column I have to write the drawOval() method in the
for loop. Firstly, in the for loop i had set color as red by using setColor method() of the graphics class. In
every iteration of the for loop the height of the circle will increase by 50, if we will not do so then every
circle will overlap each other.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 3
Build an applet that displays a horizontal rectangle in its centre. Let the rectangle be filled with colour
from left to right.

Prac3FillRect.java
import java.applet.Applet;
import java.awt.*;
public class Prac3FillRect extends Applet
{
public void paint(Graphics g)
{
String r = getParameter("R");
String gr = getParameter("G");
String b = getParameter("B");

int ri = Integer.parseInt(r);
int gi = Integer.parseInt(gr);
int bi = Integer.parseInt(b);

int w=150;
for(int i=1;i<=5;i++)
{
Color c = new Color(ri,gi,bi);
g.setColor(c);
g.fillRect(w,200,40,70);
w=w+40;
bi = bi-50;
}

}
}

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

FillRect.html
<HTML>
<BODY>
<APPLET CODE="Prac3FillRect.class" WIDTH="500" HEIGHT="500">
<PARAM NAME="R" VALUE="255">
<PARAM NAME="G" VALUE="0">
<PARAM NAME="B" VALUE="255">
</APPLET>
</BODY>
</HTML>
Output:

Conclusion/Observation:
This Program is to display a horizontal rectangle in its centre and filled with colour from left to
right.Firstly I had to use the getParameter Method to get the value of parameters from the HTML
code.After that converted that value to Integer from string because color class accepts the parameter in
the Integer form.I had user fillRect from displaying rectangle and filling color in it.Every time i am
decrementing the value of bi for changing the color.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 4
Write a program to pass parameters to applet to set the message on its status bar.

Prac4ShowStatus .java
import java.applet.Applet;
import java.awt.*;
public class Prac4ShowStatus extends Applet
{
String s;
public void init()
{
s = getParameter("status");
}
public void paint(Graphics g)
{
showStatus(s);
g.drawString("Hello",250,250);
}
}

ShowStatus.html
<HTML>
<BODY>
<APPLET CODE="Prac4ShowStatus.class" WIDTH="500" HEIGHT="500">
<PARAM NAME="status" VALUE="Practical 4 of Applet ">
</APPLET>
</BODY>
</HTML>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
This​ ​ program passes parameters to applet to set the message on its status bar. I had to use getParameter
for getting the value that is to be set in status bar and After that , passess that value to the ShowStatus()
method of the component class for displaying the value in the status bar of an applet.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 5
Develop an applet that displays moving banner. Consider string “Advance Java Programming”.

Prac5MovingBanner.java
import java.applet.Applet;
import java.awt.*;
public class Prac5MovingBanner extends Applet implements Runnable
{
String msg=" Advance Java Programming ";
Thread t= null;
int state;
volatile boolean stopflag;

public void init()


{
setBackground(Color.cyan);
setBackground(Color.magenta);
}
public void start()
{
t = new Thread(this);
stopflag=false;
t.start();
}
public void run()
{
for(;;)
{
try
{
repaint();
Thread.sleep(250);

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
if(stopflag)
break;
}
catch(InterruptedException e) {}
}
}
public void stop()
{
stopflag= true;
t=null;
}
public void paint(Graphics g)
{
char ch;
ch=msg.charAt(0);
msg = msg.substring(1,msg.length());
msg+=ch;
g.drawString(msg,200,250);
}
}

MovingBanner.html
<HTML>
<BODY>
<APPLET CODE="Prac5MovingBanner.class" WIDTH="500" HEIGHT="500">
</APPLET>
</BODY>
</HTML>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
This program is about to display a moving banner. For displaying the moving banner we have to use
threads concept . In this program there are a total 5 methods init(), start(),stop() methods of Applet class ,
run() method of thread and paint() method of graphics class.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

UNIT 2
ABSTRACT WINDOW
TOOLKIT

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

ABSTRACT WINDOW TOOLKIT


The Abstract Window Toolkit (AWT) is Java's original platform-dependent windowing, graphics, and
user-interface widget toolkit, preceding Swing. Java AWT components are platform-dependent i.e.
components are displayed according to the view of operating system. AWT is heavyweight i.e. its
components are using the resources of OS.

Every user interface considers the following three main aspects:

 UI elements: These are the core visual elements the user eventually sees and interacts with.
 Layouts: They define how UI elements should be organized on the screen and provide a final
look and feel to the GUI (Graphical User Interface).
 Behavior: These are events which occur when the user interacts with UI elements.

Software Required: JAVA Editors, JDK, Appletviewer Tool, JAVA enabled Web Browser.

Package: java.applet.*, java.awt.*, java.awt.event.*.

Java AWT Hierarchy:

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

AWT UI Elements
SrNo Elements and Description.
Component
Component class is at the top of AWT hierarchy. All the elements like buttons, text fields,
1. scrollbars etc are known as components. Component is an abstract class that encapsulates all the
attributes of visual component. A component object is responsible for remembering the current
foreground and background colors and the currently selected text font.
Container
Container is a component in AWT that contains another component like button, text field, tables
2.
etc. Container is a subclass of component class. Container class keeps track of components that
are added to another component.
Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or
3.
border. It is container that is used for holding components.
Window
4.
Window class creates a top level window. Window does not have borders and MenuBar.
Frame
5. Frame is a subclass of Window and has resizing canvas. The Frame is the container that contain
title bar and can have menu bars.
Label
6. A Label object is a component for placing text in a container. It is a passive control because it
does not create any event when accessed by the user. It displays a single line of read-only text.
Button
7.
Button is a control component that has a label and generates an event when pressed.
Checkbox
Checkbox control is used to turn an option on(true) or off(false). There is label for each
8.
checkbox representing what the checkbox does.The state of a checkbox can be changed by
clicking on it.
List
9. The List represents a list of text items. The list can be configured that user can choose either one
item or multiple items.
TextField
10.
The TextField component allows the user to edit single line of text.
TextArea
The TextArea control in AWT provide us multiline editor area. When the text in the text area
11.
become larger than the viewable area the scroll bar is automatically appears which help us to
scroll the text up & down and right & left.
Choice
12. Choice control is used to show pop up menu of choices. Selected choice is shown on the top of
the menu.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 6
Develop 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 filled with black at the current mouse position.

Prac6.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE="Prac6.class" WIDTH="500" HEIGHT="500"></APPLET>*/
public class Prac6 extends Applet implements MouseMotionListener
{
String str="";
int x,y;
public void init()
{
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent me)
{
x= me.getX();
y= me.getY();
str= "Mouse Moved at location X : "+x+ " Y: "+y;
repaint();
}
public void mouseDragged(MouseEvent me)
{
x= me.getX();
y= me.getY();
str= "Mouse Dragged at location X : "+x+ " Y: "+y;
repaint();
}
public void paint(Graphics g)
{
g.drawString(str,20,20);
g.fillRect(x,y,10,10);
}

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
}

Output:

Conclusion/Observation:
This Program is to develop an applet that displays the position of the mouse at the upper left corner of the
applet when it is dragged or moveda and draw a 10x10 pixel rectangle filled with black at the current
mouse position. For that first we have to import java.awt.event.* package to perform to do programs
related to events . As we saw here our source is mouse so i had implement MouseMotionListner interface
and implemented all the method of MouseMotionListner interface and i had get the coordinates through
getX() and getY() methods of recorder and draw the rectangle according to that coordinates.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 7
Develop an applet that contains one button. Initialize the label on the button to “start”. When the user
presses the button, change the label to “stop”. Toggle the button label between these two values each time
the button is pressed.

Prac7.java
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*
<APPLET CODE="Prac7.class" WIDTH="250" HEIGHT="250"></APPLET>
*/
public class Prac7 extends Applet implements ActionListener
{
Button btn1;
public void init()
{
btn1 = new Button("Start");

add(btn1);

btn1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = btn1.getActionCommand();

if(str.equals("Start"))
{
btn1.setLabel("Stop");
}
else
{
btn1.setLabel("Start");

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
}
}
}
Output:

Conclusion/Observation:
This Program is to develop an applet that contains a toggle button , that contains two values Start and
Stop ,if the value is start and we click on the button the value should change to stop and vice versa .For
that first i had created a button , added it in applet container and register it via addActionListener()
method of Action listener interface. Then i get the value to button through getActionCommand() and
compare the value with the start , if the value is start then set label again using setLabel() method.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 8
Develop an applet that uses the mouse listener, which overrides only two methods which are mouse
Pressed and mouse Released.

Practical8.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Practical8.class" width=500 height=500>
</applet>*/
public class Practical8 extends Applet
{
public void init()
{
MyAdapter ma = new MyAdapter(this);
addMouseListener(ma);
setBackground(Color.black);
}
}
class MyAdapter extends MouseAdapter
{
Practical8 p8;
MyAdapter(Practical8 p8)
{
this.p8=p8;
}
public void mouseReleased(MouseEvent m)
{
p8.setBackground(Color.red);
p8.showStatus("mouse released");
}
public void mousePressed(MouseEvent m)
{
p8.setBackground(Color.blue);

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

p8.showStatus("mouse pressed");
}
}
Output:

Conclusion/Observation:
In this program , the MouseAdapter concept is used . This program is about to create an applet that uses
the mouse listener, which overrides only two methods which are mouse Pressed and mouse Released ,
and on mouse Pressed and mouse released Background color of an applet changes.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 9
Develop 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 changes per click.(use get Background() method to get the
current color)

Practical9.java
import java.awt.*;
import java.awt.event.*;
public class Practical9 extends Frame implements ActionListener
{
Button b;
public Practical9()
{
MyAdapter ma =new MyAdapter(this);
addWindowListener(ma);
FlowLayout fl = new FlowLayout();
setLayout(fl);
b = new Button("Change");
add(b);
b.addActionListener(this);
}
public static void main(String args[])
{
Practical9 f = new Practical9();
f.setVisible(true);
f.setSize(500,500);
f.setTitle("Window");
f.setBackground(Color.RED);
}
public void actionPerformed(ActionEvent ae)
{
Color cur_c=getBackground();
Color r_c= new Color(255,0,0);
Color g_c= new Color(0,255,0);

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Color b_c= new Color(0,0,255);


if(cur_c.equals(r_c))
{
setBackground(g_c);
}
else if(cur_c.equals(g_c))
{
setBackground(b_c);
}
else
{
setBackground(r_c);
}
}
}
class MyAdapter extends WindowAdapter
{
Practical9 fd;
MyAdapter(Practical9 obj)
{
fd=obj;
}
public void windowClosing(WindowEvent we)
{
//System.exit(0);
fd.setVisible(false);
}
}

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
In this program the concept of Frame and WindowAdapter is used . Frame is a container that contains one
button . On a single click of the button the background color changes from red to green ,green to blue ,
blue to red and so on.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 10
Develop a program 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.
Practical10.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*
<APPLET CODE="Practical10.java" WIDTH="400" HEIGHT="400">
</APPLET>
*/
public class Practical10 extends Applet implements ItemListener
{
Checkbox ch_r,ch_g,ch_b;
Canvas c;
public void init()
{
ch_r = new Checkbox("Red");
ch_g = new Checkbox("Green");
ch_b = new Checkbox("Blue");

c = new Canvas();
c.setSize(30,30);
c.setBackground(Color.BLACK);

add(ch_r);
add(ch_g);
add(ch_b);
add(c);

ch_r.addItemListener(this);
ch_g.addItemListener(this);

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

ch_b.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
int r =0 ,g=0 , b=0;
if(ch_r.getState())
{
r=255;
}
if(ch_g.getState())
{
g=255;
}
if(ch_b.getState())
{
b=255;
}
Color co = new Color(r,g,b);
c.setBackground(co);
}
}
Output:

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Conclusion/Observation:
In this Program , Applet is a container that contains 3 Checkbox named “Red”,”Green”,”Blue” and on
canvas or size 30 x 30 pixels . On selecting the checkbox the canvas background color changes
accordingly, for that getState() method is used to see that which checkbox is checked accordingly that
created a color using Color class and set that created color.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 11
Create an application that displays a frame with a menu bar. When a user selects any menu or menu item,
display that selection on a text area in the center of the frame

Practical11.java
import java.awt.*;
import java.awt.event.*;
class Frame1 extends Frame implements ActionListener
{
TextArea ta;
Frame1()
{
FlowLayout fl = new FlowLayout();
setLayout(fl);
MenuBar mb = new MenuBar();
setMenuBar(mb);
Menu m1 = new Menu("File");
Menu m2 = new Menu("Edit");
mb.add(m1);
mb.add(m2);
MenuItem mi1 = new MenuItem("New");
MenuItem mi2 = new MenuItem("Open");
MenuItem mi3 = new MenuItem("Save");
MenuItem mi4 = new MenuItem("Cut");
MenuItem mi5 = new MenuItem("Copy");
MenuItem mi6 = new MenuItem("Paste");
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m2.add(mi4);
m2.add(mi5);
m2.add(mi6);
ta = new TextArea("Selected Menuitems are......\n");

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

add(ta);
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi4.addActionListener(this);
mi5.addActionListener(this);
mi6.addActionListener(this);
MyAdapter ma = new MyAdapter();
addWindowListener(ma);
}
public void actionPerformed(ActionEvent ae)
{
String s = ae.getActionCommand();
ta.append("You Select: "+s+"\n");
}
}
class MyAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
public class Practical11
{
public static void main(String arg[])
{
Frame1 f1 = new Frame1();
f1.setVisible(true);
f1.setSize(500,500);
f1.setTitle("Practical11");
}
}
Government Polytechnic For Girls-Ahmedabad Page No.
Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
In this program , a frame container that contains a menu bar and a text area .When a user selects any
menu or menu item, display that selection on a text area . Default layer of frame is border layout so firstly
we will set the layout as Flowlayout , then we will create a menu bar in that we will add a menu-like file
and edit.After that we will add menu item in each menu , all this coding is done in the constructor. As we
are implementing the ActionListener interface we need to override actionPerformed() method . In that
method we are getting all the action commands and appending in textarea.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 12
Write a frame that has only one button in it, clicking on the button number is incremented by one and
display the number in the frame.

Practical12.java
import java.awt.*;
import java.awt.event.*;
public class Practical12 extends Frame implements ActionListener
{
Button b;
Label l;
public Practical12()
{
MyAdapter ma =new MyAdapter(this);
addWindowListener(ma);
FlowLayout fl = new FlowLayout();
setLayout(fl);
b = new Button("Increment");
l = new Label("1");
add(b);
add(l);
b.addActionListener(this);
}
public static void main(String args[])
{
Practical12 f = new Practical12();
f.setVisible(true);
f.setSize(200,200);
f.setTitle("Window");
}
public void actionPerformed(ActionEvent ae)
{
int i = Integer.parseInt(l.getText());
i =i+1;

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

l.setText(String.valueOf(i));
}
}
class MyAdapter extends WindowAdapter
{
Practical12 fd;
MyAdapter(Practical12 obj)
{
fd=obj;
}
public void windowClosing(WindowEvent we)
{
//System.exit(0);
fd.setVisible(false);
}
}

Output:

Conclusion/Observation:
In this program , Frame is a container that contains a single button and a label with text ‘1’ . On every
click of button label text increment by 1 . There is also a concept of WindowAdapter.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 13
Write a GUI based application using Jlabel, JTextField and JButton that accept your name and display it.

Practical13.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Practical13.class" height="200" width="250"></applet>
*/
public class Practical13 extends JApplet implements ActionListener
{
JTextField tf1;
JLabel jl1,jl2;
JButton jb1;
public void init()
{
jl1 = new JLabel("Enter Name : ");
jl2 = new JLabel("");
tf1 = new JTextField(20);
jb1 = new JButton("Enter");

add(jl1);
add(tf1);
add(jb1);
add(jl2);

jb1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String s = tf1.getText();
jl2.setText("Hello " +s);

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
This program is all about the swing controls like JButton ,JLabel and JTextField . For that firstly we have
to import a new statement import javax.swing.*; for accessing all the swing controls . Then we have to
declare the controls ,add the control and lastly register the button . As we are implementing the
ActionListener interface we need to override the actionPerformed() method , in that i had just get the text
from textfield and simply set that text in label2.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

UNIT 3
JAVA DATABASE
CONNECTIVITY
(JDBC)

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

JAVA DATABASE CONNECTIVITY

Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to connect


Java application with Database. JDBC is used to interact with various type of Database such as Oracle,
MS Access, My SQL and SQL Server. JDBC can also be defined as the platform-independent interface
between a relational database and Java programming. It allows java program to execute SQL statement
and retrieve result from database.

Software Required: JAVA Editors, JDK, Appletviewer Tool, JAVA enabled Web Browser, Eclipse,
JDBC Driver (mysql-connector-java-5.1.18-bin)

Package: java.applet.*, java.awt.*, java.awt.event.*,java.sql.*


JDBC Architecture

JDBC Driver

JDBC Driver is required to process SQL requests and generate result. The following are the different
types of driver available in JDBC.

 Type-1 Driver or JDBC-ODBC bridge


 Type-2 Driver or Native API Partly Java Driver
 Type-3 Driver or Network Protocol Driver
 Type-4 Driver or Thin Driver

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Steps to connect a Java Application to Database

The following 5 steps are the basic steps involve in connecting a Java application with Database using
JDBC.

1. Register the Driver


2. Create a Connection
3. Create SQL Statement
4. Execute SQL Statement
5. Closing the connection

1. Register the Driver

Class.forName() is used to load the driver class explicitly.

Example:

Class.forName("com.mysql.jdbc.Driver");

2. Create a Connection

getConnection() method of DriverManager class is used to create a connection

Syntax

getConnection(String url)

getConnection(String url, String username, String password)

getConnection(String url, Properties info)

Example:

Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/dbname ", "username",


"password");

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
3. Create SQL Statement

createStatement() method is invoked on current Connection object to create a SQL Statement.

Syntax

public Statement createStatement() throws SQLException

Example:

Statement s=con.createStatement();

4. Execute SQL Statement

executeQuery() method of Statement interface is used to execute SQL statements.

Syntax

public ResultSet executeQuery(String query) throws SQLException

Example

ResultSet rs=s.executeQuery("select * from user");


while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}

5. Closing the connection

After executing SQL statement you need to close the connection and release the session. The close()
method of Connection interface is used to close the connection.

Syntax

public void close() throws SQLException

Example

con.close();

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 14
Develop a database application that uses any JDBC driver.
Practical14.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Practical14
{
public static void main(String args[])
{
Connection con;
Statement stmt;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ppd","root","");
System.out.println("Connection Successful");
stmt = con.createStatement();
String sql = "SELECT * FROM stu_info";
rs = stmt.executeQuery(sql);
while(rs.next())
{
System.out.println("Id : "+rs.getInt(1)+ " Name : " +rs.getString(2)+ " Sem
: "+rs.getInt(3));
}
rs.close();
stmt.close();
con.close();
}
catch(ClassNotFoundException e)
Government Polytechnic For Girls-Ahmedabad Page No.
Department of Computer Engineering Advance Java Programming (3360701)

{
System.out.println(e);
}
catch(SQLException e)
{
System.out.println(e);
}
}
}
Output:

Conclusion/Observation:
This program is about to develop a database application using jdbc Driver. For that firstly , load a jdbc
Driver using static method forName() of class Class.Then create a connection with server and database
using getConnection() method of DriverManager . After connection create Statement object and execute
query and parse result at last close connection.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 15
Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update.

Practical15.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
//<APPLET code="Practical15" width="500" height="500"></APPLET>
public class Practical15 extends Applet implements ActionListener{
Label l1,l2,l3;
TextField id,name,sem;
Button ins,up,del;
Connection con;
Statement stmt;
public void init()
{
l1=new Label("Id:");
l2=new Label("Name:");
l3=new Label("Sem:");
id=new TextField();
name=new TextField();
sem=new TextField();
ins=new Button("Insert");
up=new Button("Update");
del=new Button("Delete");
add(l1);
add(id);
add(l2);
add(name);
add(l3);
add(sem);

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

add(ins);
add(up);
add(del);
ins.addActionListener(this);
up.addActionListener(this);
del.addActionListener(this);
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ppd", "root","");
stmt=con.createStatement();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException se)
{
se.printStackTrace();
}
}
public void actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
String query=null;
String sid=id.getText();
int a=Integer.parseInt(sid);
String sname=name.getText();
String ssem=sem.getText();
if(s.equals("Insert"))
{
query="INSERT INTO stu_info VALUES("+sid+",'"+sname+"',"+ssem+")";

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

System.out.println("Inserted successfully");
}
else if(s.equals("Update"))
{
query="UPDATE stu_info SET name='"+sname+"'WHERE id="+a;
System.out.println("updated successfully");
}
else if(s.equals("Delete"))
{
query="DELETE FROM stu_info WHERE id="+a;
System.out.println("deleted successfully");
}
try
{
stmt.executeUpdate(query);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void destroy() {
try {
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
}
Output:

Conclusion/Observation:
This program is all about to develop GUI for Insert ,Update and Delete . For that firstly we have to create
3 Labels , 3 TextField and 3 Buttons for insert ,update and delete after that do the registration of the
button. Then Create a connection with the database using the getConnection() method. Lastly implement
actionPerformed() method and check which button is clicked using getText() method accordingly that
fires the query and finally closes the connection .

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 16
Write a program to present a set of choices for users to select a product & display the price of product.

Practical16.java

import java.applet.Applet;
import java.awt.Choice;
import java.awt.Label;
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;

public class Practical16 extends Applet implements ItemListener{


Choice c;
Label ans;
Statement stmt;
Connection con;
ResultSet rs;

public void init() {


c=new Choice();
add(c);
ans=new Label();
add(ans);
c.addItemListener(this);
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ppd", "root", "");
stmt=con.createStatement();
rs=stmt.executeQuery("SELECT name FROM product_details");
while(rs.next())
{

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
c.add(rs.getString(1));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void itemStateChanged(ItemEvent e) {
try {
rs=stmt.executeQuery("SELECT price,name FROM product_details WHERE
name='"+c.getSelectedItem()+"'");
while(rs.next())
{
ans.setText("The price of "+rs.getString(2)+" is:"+rs.getString(1));
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public void destroy()
{
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
This program is about ​presenting a set of choices for users to select a product & display the price of
product.For that firstly created a choice , Create a connection and get all the data from the product_details
table and print all the product names in the choice . Then implement ​itemStateChanged() method and check
that which item is selected according to that display price and lastly close all the connetions.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

UNIT 4
SERVLETS

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
SERVLETS

Servlet Technology is used to create web applications. Servlet technology uses Java language to create
web applications.

Web applications are helper applications that reside at web server and build dynamic web pages. A
dynamic page could be anything like a page that randomly chooses picture to display or even a page that
displays the current time.

Software Required: JAVA Editors, JDK, Web Browser, Eclipse IDK for J2EE, JDBC Driver (mysql-
connector-java-5.1.18-bin), Apache Tomcat Server

Package: java.io.*,java.util.*,javax.servlet.*,javax.servlet.http.*;
Servlet Architecture

Execution of Servlets involves six basic steps:

1. The clients send the request to the web server.


2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of output.
5. The servlet sends the response back to the web server.
6. The web server sends the response back to the client and the client browser displays it on the
screen.

Advantages of using Servlets

7. Better performance: because it creates a thread for each request, not process.
8. Portability: because it uses Java language.
9. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
10. Secure: because it uses java language.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Servlet API
Servlet API consists of two important packages that encapsulates all the important classes and interface,
namely :
javax.servlet
javax.servlet.http
Some Important Classes and Interfaces of javax.servlet
Interfaces : Servlet, ServletContext, ServletConfig, ServletRequest, ServletResponse
Classes : ServletException, UnavailableException, GenericServlet, ServletInputStream,
ServletOutputStream

Parameters and Attributes


Parameters may come into our application from the client request, or may be configured through
deployment descriptor (web.xml) elements or their corresponding annotations. When you submit a form,
form values are sent as request parameters to a web application. In case of a GET request, these
parameters are exposed in the URL as name value pairs and in case of POST, parameters are sent within
the body of the request. Servlet init parameters and context init parameters are set through the
deployment descriptor (web.xml) or their corresponding annotations. All parameters are read-only from
the application code. We have methods in the Servlet API to retrieve various parameters.

Attributes are objects that are attached to various scopes and can be modified, retrieved or removed.
Attributes can be read, created, updated and deleted by the web container as well as our application code.
We have methods in the Servlet API to add, modify, retrieve and remove attributes. When an object is
added to an attribute in any scope, it is called binding as the object is bound into a scoped attribute with a
given name.

Servlet API methods to manipulate parameters


The API methods to retrieve the request parameters are:
 ServletRequest.getParameterValues(String parmName)
o returns a String array with all values present, or null if no value exists for the parameter
name.
 ServletRequest.getParameter(String parmName)
o returns the first value for the given parameter.
 ServletRequest.getParameterNames()
o returns an Enumeration of String objects representing the names of all the parameters in
the request. If there are no parameters Enumeration will be empty.

The API methods to retrieve the ServletContext initialization parameters from a ServletContext object
are:
 ServletContext.getInitParameterNames()
o will always return an enumeration of names.
 ServletContext.getInitParameter(String paramName)
o will return a String or null.

The API methods to retrieve the ServletConfig initialization parameters from a ServletConfig object are:
 ServletConfig.getInitParameterNames()
o returns an enumeration of all the parameter names available to the servlet.
 ServletConfig.getInitParameter(String paramName)
o return a parameter value.
Both the methods are implemented in the GenericServlet abstract class.

Servlet API methods to manipulate attributes

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
The attribute manipulation methods for request, session and application scopes are identical and differ
only on the interfaces they are defined. They are:
• public void setAttribute(String name, Object value)
• public Object getAttribut(String name)
• public Enumeration getAttributeNames()
• public void removeAttribute(String name)

Managing Session in Servlets


Session Management is a mechanism used by the Web container to store session information for a
particular user. Session is used to store everything that we can get from the client from all the requests the
client makes.
HttpSession object is used to store entire session with a specific client. We can store, retrieve and remove
attribute from HttpSession object. Any servlet can have access to HttpSession object throughout the
getSession() method of the HttpServletRequest object.

Cookies are created using Cookie class present in Servlet API. Cookies are added to response object
using the addCookie() method. This method sends cookie information over the HTTP response stream.
getCookies() method is used to access the cookies that are added to response object.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 17
Develop a simple servlet program which maintains a counter for the number of times it has been accessed
since its loading; initialize the counter using deployment descriptor.

Practical17.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Practical17 extends HttpServlet {
int i;
public void init() throws ServletException
{
ServletConfig config = getServletConfig();
String s = config.getInitParameter("page_count");
i = Integer.parseInt(s);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
i++;
out.println("<HTML>");
out.println("<BODY>");
out.println("<H1>Page Count is :::"+i+"</H1>");
out.println("</BODY>");
out.println("</HTML>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request,response);
Government Polytechnic For Girls-Ahmedabad Page No.
Department of Computer Engineering Advance Java Programming (3360701)

}
}
web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Servlets</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Practical17</servlet-name>
<servlet-class>Practical17</servlet-class>
<init-param>
<param-name>page_count</param-name>
<param-value>0</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Practical17</servlet-name>
<url-pattern>/Practical17</url-pattern>
</servlet-mapping>
</web-app>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
This Practical is about to develop a servlet program which maintains a counter for the number of times it
has been accessed since its loading; initialize the counter using deployment descriptor. For that firstly
creates an Servlet override init(),doGet(),doPost() methods and add the servlet in web.xml file

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 18
Write an HTML code to create login form having one submit button, two textboxes labeled as Login
name and Password as respectively. Write a Servlet class named as ReadParameter to read these two
parameters and display entered parameters values on the page using doGet() or doPost() method when the
user clicked on the submit button.
Login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Practical18" method="POST">
Username <input type ="text" name="uname"><br/>
Password<input type="password" name="pass"><br/>
<input type ="submit" value="Submit" name="submit">
</form>
</body>
</html>

Practical18.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Practical18 extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,
ServletException
{

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String unm = request.getParameter("uname");
String pwd = request.getParameter("pass");
out.println("<html>");
out.println("<body>");
out.println("<h1>Welcome "+unm+" </h1>");
out.println("<h1>Password is "+pwd+" </h1>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,
ServletException
{
doGet(request,response);
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Servlets</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

<servlet-name>Practical18</servlet-name>
<servlet-class>Practical18</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Practical18</servlet-name>
<url-pattern>/Practical18</url-pattern>
</servlet-mapping>
</web-app>

Output:

Conclusion/Observation:
This Practical is about reading the parameters and displaying entered parameters values on the page
using doGet() or doPost() method when the user clicked on the submit button. For that firstly created a
form in HTML file , when we click on button in form it should redirect to the servlet(Practical18.java).
In servlet override the doGet() and doPost() methods , in doGet() method get the value that is inserted in
the form using getParameter() and display it.Lastly add this servlet in web.xml file.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Practical No. 19
Create a web form which processes servlet and demonstrates use of cookies and sessions.
index.html
<!DOCTYPE >
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="Praactical19" method="POST">
Name <input type="text" name="userName"><br/>
<input type="submit" name="submit">
</form>
</body>
</html>

Practical19.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Praactical19 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY>");
String n=request.getParameter("userName");
out.print("Welcome "+n);
//Cookie ck=new Cookie("uname",n);//creating cookie object
// response.addCookie(ck);//adding cookie in the response

HttpSession session=request.getSession();
session.setAttribute("uname",n);

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

//creating submit button


out.print("<form action='Servlet2' method='post'>");
out.print("<input type='submit' value='go' >");
out.print("</form>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

Servlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet2 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY>");
//Cookie ck[]=request.getCookies();
//out.print("Hello "+ck[0].getValue());
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.println("</BODY>");
out.println("</HTML>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Servlets</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet-name>Praactical19</servlet-name>
<servlet-class>Praactical19</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Praactical19</servlet-name>
<url-pattern>/Praactical19</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/Servlet2</url-pattern>
</servlet-mapping>
</web-app>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
This Practical is about creating a web form which processes servlet and demonstrates use of cookies and
sessions.For that we had created 3 files Index.html ,Practical19.java ,Servlet2.java .In index.html simply
created an html form and redirected to the Practical19.java(first servlet) , in Practical19.java firstly get
the value from html form ,set cookie or session, print it and ask user to click on button , When the user
will click on it will redirect to the Servlet2.java(Second Servlet) , in Servelet2.java get the value from set
cookie or session and simply display it .Lastly added both the servlet to the web.xml file.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

UNIT 5
JAVA SERVER PAGES
(JSP)

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
JAVA SERVER PAGES (JSP)

JSP technology is used to create dynamic web applications. JSP pages are easier to maintain then a
Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while JSP
adds Java code inside HTML using JSP tags. Everything a Servlet can do, a JSP page can also do it.

JSP enables us to write HTML pages containing tags, inside which we can include powerful Java
programs. Using JSP, one can easily separate Presentation and Business logic as a web designer can
design and update JSP pages creating the presentation layer and java developer can write server side
complex computational code without concerning the web design. And both the layers can easily interact
over HTTP requests.

Software Required: JAVA Editors, JDK, Web Browser, Eclipse IDK for J2EE, JDBC Driver (mysql-
connector-java-5.1.18-bin), Apache Tomcat Server

Package: javax. servlet. jsp


JSP Architecture

Following steps includes the JSP Architecture as shown in the above figure.

1. Web client sends request to Web server for a JSP page (extension .jsp).
2. As per the request, the Web server (here after called as JSP container) loads the page.
3. JSP container converts (or translates) the JSP file into Servlet source code file (with extension
.java). This is known as translation.
4. The translated .java file of Servlet is compiled that results to Servlet .class file. This is known as
compilation.
5. The .class file of Servlet is executed and output of execution is sent to the client as response.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

JSP Scripting Element


JSP Scripting elements are written inside <% %> tags. These code inside <% %> tags are processed by
the JSP engine during translation of the JSP page. Any other text in the JSP page is considered as HTML
code or plain text.
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>

There are five different types of scripting elements


Scripting Element Example
Comment <%-- comment --%>
Directive <%@ directive %>
Declaration <%! declarations %>
Scriptlet <% scriplets %>
Expression <%= expression %>

JSP Scriptlet Tag

Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements the _jspService
method functionality by writing script/java code. Syntax of Scriptlet Tag is as follows :

<% JAVA CODE %>

JSP: Example of Scriptlet

In this example, we will show number of page visit.

<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
JSP Declaration Tag

We know that at the end a JSP page is translated into Servlet class. So when we declare a variable or
method in JSP inside Declaration Tag, it means the declaration is made inside the Servlet class but
outside the service(or any other) method. You can declare static member, instance variable and methods
inside Declaration Tag. Syntax of Declaration Tag :

<%! declaration %>

Example of Declaration Tag


<html>
<head>
<title>My First JSP Page</title>
</head>
<%!
int count = 0;
%>
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>

JSP Expression Tag

Expression Tag is used to print out java language expression that is put between the tags. An expression
tag can hold any java language expression that can be used as an argument to the out.print() method.
Syntax of Expression Tag

<%= Java Expression %>

When the Container sees this

<%= (2*5) %>

It turns it into this:

out.print((2*5));

Note: Never end an expression with semicolon inside Expression Tag. Like this:

<%= (2*5); %>

Example of Expression Tag


<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <%= ++count %>
</body>
</html>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 20
Develop a simple JSP program for user registration and then control will be transferring it into the second
page.
Userreg.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<FORM action = "Welcome.jsp" method = "GET">
<TABLE>
<TR>
<TD>
First Name :
<INPUT type= "text" name="fname">
</TD>
</TR>
<TR>
<TD>
Last Name :
<INPUT type= "text" name="lname">
</TD>
</TR>
<TR>
<TD>
Semester:
<INPUT type= "text" name="sem">
</TD>
</TR>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
<TR>
<TD>
<INPUT type="submit" value="SUBMIT">
</TD>
</TR>
</TABLE>
</FORM>
</body>
</html>

Welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%! int usercount = 0; %>
<H1>
<%
String nm = request.getParameter("fname");
usercount++;
%>
Welcome <%= nm %><br>
You are <%= usercount %> customer...!!!
</H1>
</body>
</html>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

Output:

Conclusion/Observation:
This Practical is about developing a simple JSP program for user registration and then control will be
transferring it into the second page.For that first created a simple form in userreg.jsp file and in second
file welcome.jsp firstly in declaration tag usercount initialize by 0 . Secondly get the inserted name from
tha form in scriptlet tag increment usercount and display using expression tag.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 21
Develop a simple JSP program for user login form with a static database.
Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<FORM action = "Pract21.jsp" method = "POST">
<TABLE>
<TR>
<TD>
UserName :
<INPUT type= "text" name="uname">
</TD>
</TR>
<TR>
<TD>
Password :
<INPUT type= "text" name="pswd">
</TD>
</TR>
<TR>
<TD>
<INPUT type="submit" value="SUBMIT">
</TD>
</TR>
</TABLE>
</FORM>
Government Polytechnic For Girls-Ahmedabad Page No.
Department of Computer Engineering Advance Java Programming (3360701)

<%@ page import="java.sql.*" %>


<%
if(request.getParameter("uname") != null)
{
Connection con = null;
Statement s=null;
ResultSet rs=null;
String url= "jdbc:mysql://localhost:3306/login";
String id= "root";
String pass = "";
String count = "0";
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, id, pass);
String sql = "select count(*) from login_details where username =
'"+request.getParameter("uname")+"' and password ='"+request.getParameter("pswd") + "'";
s = con.createStatement();
rs = s.executeQuery(sql);
while( rs.next() ){
count = rs.getString(1);
}
if(count.equals("1"))
{
%>
<H1>Dear <%= request.getParameter("uname")%> , Login successfully done </H1>
<%
}
else
{
%>
<H1> Incorrect credentials...</H1>
<%
Government Polytechnic For Girls-Ahmedabad Page No.
Department of Computer Engineering Advance Java Programming (3360701)
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(rs!=null) rs.close();
if(s!=null) s.close();
if(con!=null) con.close();
}
}
%>
</body>
</html>
Output:

Conclusion/Observation:
This Practical is about developing a simple JSP program for user login form with a static database.For
that first of all create a login form . secondly create a connection with the database and check whether
inputted data is already in table or not . if yes then display Login successfully done otherwise Incorrect
credentials.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 22
Develop a simple JSP program to create a form having two textboxes and one submit button. Write JSP
code to display the addition of these two numbers when the user clicks on the submit button.
Add.jsp
<HTML>
<BODY>
<FORM method = "GET">
<TABLE>
<TR>
<TD>
Enter number 1 :
<INPUT type= "text" name="no1">
</TD>
</TR>
<TR>
<TD>
Enter number2 :
<INPUT type= "text" name="no2">
</TD>
</TR>
<TR>
<TD>
<INPUT type="submit" value="SUBMIT">
</TD>
</TR>
</TABLE>
</FORM>
<%
int sum = 0;
if(request.getParameter("no1") != null)
{
int n1 = Integer.parseInt(request.getParameter("no1"));
int n2 = Integer.parseInt(request.getParameter("no2"));

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
sum = n1 + n2;
%>
<H1>Total is <%= sum %></H1>
<%
}
%>
</BODY>
</HTML>

Output:

Conclusion/Observation:
This Practical is to develop a form to add two values in jsp. Firstly create a form with 2 textboxes and a
submit button . onclick get the value , parse into integer . Add it , and display using the expression tag.

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Practical No. 23
Develop a JSP program to display the grade of a student by accepting the marks of five subjects.
SubjectMarks.jsp
<HTML>
<BODY>
<FORM action = "SubjectMarks.jsp" method = "GET">
<TABLE>
<TR>
<TD>
Enter Marks of Sub1 :
<INPUT type= "text" name="sub1">
</TD>
</TR>
<TR>
<TD>
Enter Marks of Sub2 :
<INPUT type= "text" name="sub2">
</TD>
</TR>
<TR>
<TD>
Enter Marks of Sub3 :
<INPUT type= "text" name="sub3">
</TD>
</TR>
<TR>
<TD>
Enter Marks of Sub4 :
<INPUT type= "text" name="sub4">
</TD>
</TR>
<TR>
<TD>

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)
Enter Marks of Sub5 :
<INPUT type= "text" name="sub5">
</TD>
</TR>
<TR>
<TD>
<INPUT type="submit" value="CALCULATE">
</TD>
</TR>
</TABLE>
</FORM>
<%
int sum = 0;
String Grade="";
if(request.getParameter("sub1") != null)
{
int mark1 = Integer.parseInt(request.getParameter("sub1"));
int mark2 = Integer.parseInt(request.getParameter("sub2"));
int mark3 = Integer.parseInt(request.getParameter("sub3"));
int mark4 = Integer.parseInt(request.getParameter("sub4"));
int mark5 = Integer.parseInt(request.getParameter("sub5"));
sum = mark1 + mark2 + mark3 + mark4 +mark5;
if(sum>=200)
{
Grade = "A";
}
else if(sum<200 && sum>=150)
{
Grade = "B";
}
else if(sum<150 && sum>=0)
{
Grade = "D";

Government Polytechnic For Girls-Ahmedabad Page No.


Department of Computer Engineering Advance Java Programming (3360701)

}
%>
<H1>GRADE for total marks <%= sum %> is <%= Grade %></H1>
<%
}
%>
</BODY>
</HTML>
Output:

Conclusion/Observation:
This Practical is about to display the grade of a student by accepting the marks of five subjects. Firstly
create a form with 5 textboxes and one submit button. onclick get the value , parse into integer . Add it ,
and check the total marks accordingly to display the Grade.

Government Polytechnic For Girls-Ahmedabad Page No.

You might also like