You are on page 1of 40

BHAGVAN MAHAVIR POLYTECHNIC

BHARTHANA, SURAT.
I.T. DEPARTMENT
PRACTICAL

COURSE TITLE: ADVANCE JAVA PROGRAMMING


(COURSE CODE: 3360701)
NO. TOPICS

Write an applet that draws a circle. The dimension of the applet should be 500 x 300 pixels. The circle
1 should be centered in the applet and have a radius of 100 pixels. Display your name centered in a circle.
( using drawOval() method)
2 Draw ten red circles in a vertical column in the center of the applet.
Built an applet that displays a horizontal rectangle in its center. Let the rectangle fill with color from left to
3 right.
Write an applet that display the position of the mouse at the upper left corner of the applet when it is dragged
4 or moved. draw a 10x10 pixel rectangle filed with black at the current mouse position.
Write an applet that contains one button. Initialize the label on the button to “start”, when the user presses the
5 button change the label between these two values each time the button is pressed.
Write an applet that uses the mouse listener, which overrides only two methods which are mousePressed and
6 mouseReleased.
Write a program that has only one button in the frame, clicking on the button cycles through the colors: red-
7 >green->blue-> and so on.one color change per click.(use getBackGround() method to get the current color)
Write an applet that contains three check boxes and 30 x 30 pixel canvas. The three checkboxes should be
8 labeled “Red”, ”Green”, ”Blue”. The selection of the check boxes determine the color of the canvas. For
example, if the user selects both “Red” and “Blue”, the canvas should be purple.
Create an application that displays a frame with a menubar. When a user selects any menu or menu item,
9 display that selection on a text area in the center of the frame
Write an applet that draws two sets of ever-decreasing rectangles one in outline form and one filled
10 alternately in black and white.
11 Write a database application that use any JDBC driver
12 Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update.
13 Write a program to present a set of choice for user to select a product & display the price of product.
Write a simple servlet program which maintains a counter for the number of times it has been accessed since
14 its loading, initialize the counter using deployment descriptor.
15 Create a form processing servlet which demonstrates use of cookies and sessions.
16 Write a simple JSP program for user Registration & then control will be transfer it into second page.
17 Write a simple JSP program for user login form with static & dynamic database
18 Write a JSP program to display the grade of a student by accepting the marks of five subjects.

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

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/*
<applet code="oval" width=500 height=500>
</applet>
*/
public class oval extends Applet
{
public void paint(Graphics g)
{
//set color to red
setForeground(Color.red);
g.drawOval(180,200,100,100);
g.drawString("arhanti",210,250);

}
}

2
2 Draw ten red circles in a vertical column in the center of the applet

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/*
<applet code="oval1" width=500 height=500>
</applet>
*/
public class oval1 extends Applet
{
public void paint(Graphics g)
{
g.drawOval(180,40,50,50);
g.drawOval(180,90,50,50);
g.drawOval(180,140,50,50);
g.drawOval(180,190,50,50);
g.drawOval(180,240,50,50);
g.drawOval(180,290,50,50);
g.drawOval(180,340,50,50);
g.drawOval(180,390,50,50);
g.drawOval(180,440,50,50);
g.drawOval(180,500,50,50);
}
}

3
3 Built an applet that displays a horizontal rectangle in its center. Let the rectangle fill with
color from left to right.

import java.applet.*;
import java.awt.*;
/*
<applet code="rect" width=500 height=500>
</applet>
*/
public class rect extends Applet
{
public void paint(Graphics g)
{
g.drawRect(180,180,60,50);
g.fillRect(180,180,60,50);
g.setColor(Color.red);
}
}

4
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.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="MouseMotionExample" width=500 height=500>
</applet>
*/
public class MouseMotionExample extends Applet implements MouseMotionListener
{
int xpos;
int ypos;
int rect1xco,rect1yco,rect1width,rect1height;
public void init()
{
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
g.drawRect(xpos, ypos,10,10);
g.drawString("("+xpos+","+ypos+")",20,10);
}
public void mouseMoved(MouseEvent me)
{
xpos = me.getX();
ypos = me.getY();
repaint();
}
public void mouseDragged(MouseEvent me)
{
}
}

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

import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/*
<applet code="Example5" width=200 height=200>
</applet>
*/
public class Example5 extends Applet implements ActionListener
{

Button Button1 = new Button("Start");


String actionMessage=" Hello...........";
public void init()
{

//add Buttons
add(Button1);
//set action listeners for buttons
Button1.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString(actionMessage,10,50);
}
public void actionPerformed(ActionEvent ae)
{
String action = ae.getActionCommand();
if(action.equals("Start"))
{

Button1.setLabel("STOP");

}
else if(action.equals("STOP"))
{
Button1.setLabel("Start");
}
}
}

6
7
6 Write an applet that uses the mouse listener, which overrides only two methods which are
mousePressed and mouseReleased.

import java.applet.Applet;
import java.awt.*;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/*
<applet code="Example6" width=200 height=200>
</applet>
*/
public class Example6 extends Applet implements MouseListener
{
String msg1=" ";
public void init()
{
addMouseListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg1,10,50);
}
public void mousePressed(MouseEvent ae)
{
msg1="Mouse Pressed...";
repaint();
}
public void mouseReleased(MouseEvent ae)
{
msg1="Mouse Released...";
repaint();
}
public void mouseEntered(MouseEvent ae)
{
}
public void mouseExited(MouseEvent ae)
{
}
public void mouseClicked(MouseEvent ae)
{
}
}

8
9
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)

import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
/*
<applet code="Example7" width=200 height=200>
</applet>
*/
public class Example7 extends Applet implements ActionListener
{
Button Button1 = new Button("RED");
Color c;
int c1= 0;
public void init()
{
//add Buttons
add(Button1);
//set action listeners for buttons
Button1.addActionListener(this);
}
public void paint(Graphics g)
{
if( c1 == 0)
{
setBackground(Color.red);
Button1.setLabel(" RED ");
}
else if(c1== 1)
{
setBackground(Color.green);
Button1.setLabel(" GREEN ");
}
else if(c1== 2)
{
setBackground(Color.blue);
Button1.setLabel(" Blue ");
}
}
public void actionPerformed(ActionEvent ae)
{
c = getBackground();
if( c == Color.red)
{
10
c1= 1;
repaint();
}
c = getBackground();
if( c == Color.green)
{
c1= 2;
repaint();
}
c = getBackground();
if( c == Color.blue)
{
c1= 0;
repaint();
}
}
}

11
8 Write an applet that contains three check boxes. The three checkboxes should be labeled
“Red”, ”Green”, ”Blue”. The selection of the check boxes determines the color of the
applet. For example, if the user selects both “Red” and “Blue”, the canvas should be
purple.

import java.applet.Applet;
import java.awt.Checkbox;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.Color;
/*
<applet code="Example8" width=200 height=200>
</applet>
*/
public class Example8 extends Applet implements ItemListener{
Checkbox RED = new Checkbox("RED");
Checkbox GREEN = new Checkbox("GREEN");
Checkbox BLUE = new Checkbox("BLUE");
public void init()
{
add(RED);
add(GREEN);
add(BLUE);
//add item listeners
RED.addItemListener(this);
GREEN.addItemListener(this);
BLUE.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
int r,g,b;
r=0;
g=0;
b=0;
if(RED.getState()== true)
{
r=1;

}
if(GREEN.getState()== true)
{
g=1;

}
if(BLUE.getState()== true)
{
b=1;

12
}
setBackground(new Color(r*255,g*255,b*255));
}
}

13
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

import java.awt.*;
import java.util.Vector;
import java.awt.event.*;
public class Example9 extends Frame
{
TextField t1 = new TextField(20);
public Example9()
{
add(t1);
MenuItem mi;
MenuBar mb1= new MenuBar();
setMenuBar(mb1);
Menu file1 = new Menu("File");
mb1.add(file1);
Menu edit1 = new Menu("Edit");
mb1.add(edit1);
mi= new MenuItem("Open");
file1.add(mi);
mi.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
t1.setText("You Clicked Open");
}
});
mi= new MenuItem("Close");
file1.add(mi);
mi.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
t1.setText("You Clicked close");
}
});
mi= new MenuItem("Undo");
edit1.add(mi);
mi.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
t1.setText("You Clicked Undo");
}
});
setSize(250,300);
setLayout(new FlowLayout());
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
14
System.exit(0);
}
});
}
public static void main (String args[])
{
Example9 e = new Example9();
}
}

15
10 Write an applet that draws two sets of ever-decreasing rectangles one in outline form and
one filled alternately in black and white.
/* <applet code="rect1" height=400 width=300>
</applet> */
import java.awt.*;
import java.applet.*;
public class rect1 extends Applet
{
public void paint(Graphics g)
{
Dimension d = getSize();
int rh = 100;
int rw = 50;
int dec=5;
int x=150;
int y=300;
for(int i=0;i<5;i++)
{
rh-=dec;
rw-=dec;
y-=50;
g.drawRect(x,y,rh,rw);
}
for(int i=0;i<5;i++)
{
rh-=dec;
rw-=dec;
y+=30;
if(i%2==0)
{
g.drawRect(40,y,rh,rw);
}
else
{
g.fillRect(40,y,rh,rw);
}
}
}
}

16
11 Write a database application that use any JDBC driver

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

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable
access to an underlying database. Java can be used to write different types of executables, such as:

Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs)
 JDBC uses a simple class hierarchy for database objects. The classes are contained in the java.sql.*
package, which will be included in JDK 1.1. The java.sql.* classes are descriptions of classes and
methods that must be written in order to produce a J DBC driver, as mentioned earlier.
 Three classes relate to opening a connection to the DBMC: java.sql.DriverManager,
java.sql.Connection, and java.sql.DatabaseMetaData. For accessing a database, a java.sql.Connection
object has to be obtained directly from the JDBC management layer and the java.sql.DriverManager.
The following is an example of the code to obtain a connection:
 Connection con = DriverManager.getConnection ("jdbc:odbc:wombat", "login", "password");
 The DriverManager uses the URL string as an argument, and the JDBC management layer locates and
loads the appropriate driver for the target database to which the applet is attempting to link. The
DriverManager does this by querying each driver, locatin g the one that can connect to the URL. The
drivers look at the URL to determine if it requires a sub-protocol that the driver supports. Then, the
driver connects to the remote database, returning the correct java.sql connection object that is the way
by w hich the applet accesses services on the database. The JDBC management layer must know the
location of each and every database driver available to it. Each driver must register with the
DriverManager using the DriverManager.RegisterDrive method so that th e DriverManager knows that
the driver exists and where to find it.
 The DatabaseMetaData returns information about the client�s connection and interesting information
about the database to which the client has connected.
 The java.sql.Statement class is used to compose and execute SQL queries on the DBMS. A query of
some sort, either a select statement, or an insert, update or delete statement could be performed after
connecting. The results of a query are used to creat e a java.sql.ResultSet. Using the connection obtained
in the example above, an example of the code for a Select statement could be:
 Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while ( rs.next() ) { int x = getInt("a");
String s = getString("b");
float f = getFloat("c"); }
 Stored procedures on a database can also be executed with two subclasses of java.sql.Statement:
java.sql.PreparedStatement, and java.sql.CallableStatement.
17
 Finally other JDBC classes are supplied for utility purposes. For example java.sql.Types encapsulates
Java types for database use; java.sql.Date, java.sql.Time, and java.sql.TimeStamp; java.sql.Exception,
and java.sql.Warning provide for exception hand ling.
 JDBC Driver Types
 JDBC drivers fit into one of the following four categories:
 The JDBC-ODBC Bridge plus ODBC driver

 Because many PC-based networks already use ODBC for their C and C++ clients, JavaSoft and
Intersolv (a major ODBC driver vendor) worked together to produce a JDBC-ODBC bridge, to make
the transition from C/C++ clients to Java clients more appropriate. It was developed in mid-1996. They
are preparing for the release of a reference implementation of JDBC that uses the ODBC interface. This
is the technology that lets Java Applets use existing ODBC drivers.

 In this case, ODBC acts as a mediating layer between the JDBC driver and the vendor client libraries.
The bridge driver translates JDBC method calls into ODBC function calls. ODBC binary code, and in
many cases database client code, must be loaded on e ach client machine that uses this driver. This kind
of driver is most appropriate on a corporate network where client installations are not a major problem.
 Native-API partly-Java driver

This kind of driver is a two-tier driver that converts JDBC calls into calls on the client API for
Oracle, Sybase, Informix, or other DBMS. As well as with the bridge driver, some binary code must be
loaded on each client machine. There is a wide range of variation between vendors in how much of the
driver is Java, and how much is C/C++. This driver connects the client to the DBMS by way of the
vendor-supplied libraries for the DBMS. By this fact, the need for ODBC and the ODBC-JDBC bridge
is not there anymore.

 The advantage of using this kind of JDBC driver is that it reduces the complexity of a client application,
including development, debugging, and maintenance time. It also provides direct access to the full
functionality of the database. The client libr aries are usually written in C or C++, therefore, the JDBC
implementation must use a layer of C or C++ in order to make calls to the vendor libraries; their layer of
non-Java code requires the use of "native methods" in Java. JDBC drivers that use native methods
can�t currently be used in applets for security reasons.

JDBC-Net pure Java driver

 This driver translates JDBC calls into a DBMS-independent net protocol which is then translated to a
18
DBMS protocol by a server. This driver designed for a three-tier environment, work with an
intermediate application server, the DBMS-independent net pr otocol, that sits between the client and
the DBMS. This net server middleware is able to connect its pure Java clients to many different
databases. In general, this is the most flexible JDBC alternative.
 Native-protocol pure Java driver

This kind of driver converts JDBC calls into the network protocol used by DBMSs directly. This pure-
Java drivers make no calls to the client libraries of the DBMS, but rather communicate with the DBMS
directly, using its proprietary protocol. This allo ws a direct call from the client machine to the DBMS
server and is a practical solution for Intranet access.

 Other Features

In addition to retrieving text data, JDBC provides facilities to access binary large objects
(BLOBs). This facility is convenient for moving image, video, and audio information from relational
databases into Java applets or applications. JDBC will supp ort advanced database features as well, such
as using scalar functions and invoking stored procedures and triggers.

 JDBC provides threading, which is important for increasing performance because it allows multiple
transactions on database data. Using a three-tier JDBC driver with a robust, pure-Java intermediate
server will bring the added advantages of Java'� thread support. The client can operate as a
multithreaded application and let the intermediate server handle the synchronization and waiting that
results from communicating with a single-threaded client library.
 JDBC is a low-level API and a base for higher-level APIs. Two higher-level APIs under development
are:
 1. an embedded SQL for Java. JDBC requires that the SQL statements be passed as Strings to Java
methods. An embedded SQL preprocessor allows a programmer to instead mix SQL statements directly
with Java: for example, a Java variable can be used in a SQ L statement to receive or provide SQL
values. The embedded SQL preprocessor then translates this Java/SQL mix into Java with JDBC calls.
 2. a direct mapping of relational database tables to Java classes. This is an object/relational mapping, in
which each row of the table becomes an instance of that class, and each column value corresponds to an
attribute of that instance. Programmer’s c an then operate directly on Java objects; the required SQL
calls to fetch and store data are automatically generated "beneath the covers". More sophisticated
mappings are also provided, for example, where rows of multiple tables are combined in a Java class.
 In addition to retrieving text data, JDBC provides facilities to access binary large objects (BLOBs). This
facility is convenient for moving image, video, and audio information from relational databases into
Java applets or applications. JDBC will supp ort advanced database features as well, such as using scalar
functions and invoking stored procedures and triggers.
 JDBC provides threading, which is important for increasing performance because it allows multiple
transactions on database data. Using a three-tier JDBC driver with a robust, pure-Java intermediate
server will bring the added advantages of Java'� thread support. The client can operate as a
multithreaded application and let the intermediate server handle the synchronization and waiting that
results from communicating with a single-threaded client library.
 JDBC is a low-level API and a base for higher-level APIs. Two higher-level APIs under development
are:
 1. an embedded SQL for Java. JDBC requires that the SQL statements be passed as Strings to Java
methods. An embedded SQL preprocessor allows a programmer to instead mix SQL statements directly
with Java: for example, a Java variable can be used in a SQ L statement to receive or provide SQL
19
values. The embedded SQL preprocessor then translates this Java/SQL mix into Java with JDBC calls.
 2. a direct mapping of relational database tables to Java classes. This is an object/relational mapping, in
which each row of the table becomes an instance of that class, and each column value corresponds to an
attribute of that instance. Programmer’s c an then operate directly on Java objects; the required SQL
calls to fetch and store data are automatically generated "beneath the covers". More sophisticated
mappings are also provided, for example, where rows of multiple tables are combined in a Java cla ss.

20
12 Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update.
JDBC - Insert Records Example
//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/STUDENTS";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

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 a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

//STEP 4: Execute a query


System.out.println("Inserting records into the table...");
stmt = conn.createStatement();

String sql = "INSERT INTO Registration " +


"VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");

}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
21
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample

Now let us compile above example as follows:

C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces following result:
C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Inserting records into the table...
Inserted records into the table...
Goodbye!
C:\>
JDBC - Delete Records Example
//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/STUDENTS";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

22
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 a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "DELETE FROM Registration " +
"WHERE id = 101";
stmt.executeUpdate(sql);

// Now you can extract all the records


// to see the remaining records
sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);

while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}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

23
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample

Now let us compile above example as follows:

C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces following result:
C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Creating statement...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Goodbye!
C:\>
JDBC - Update Records Example
//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/STUDENTS";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;

24
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 a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE Registration " +
"SET age = 30 WHERE id in (100, 101)";
stmt.executeUpdate(sql);

// Now you can extract all the records


// to see the updated records
sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);

while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}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)
conn.close();

25
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample

Now let us compile above example as follows:

C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces following result:
C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Creating statement...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 101, Age: 30, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Goodbye!
C:\>

26
13 Write a program to present a set of choice for user to select a product & display the price
of product
import java.awt.*;
import java.awt.event.*;
public class SuperBazarBilling extends Frame implements ActionListener
{
List bazar;
double rates[] = { 80.50, 75.60, 150.25, 39.99, 120.25, 90.80, 50.00 };
public SuperBazarBilling()
{ // create List object
bazar = new List(5, true);
// populate list
bazar.add("Gloves");
bazar.add("Socks");
bazar.add("Waist Belt");
bazar.add("Cap"); bazar.add("Wallet");
bazar.add("Pen Set");
bazar.add("Napkins");
// register with listener
bazar.addActionListener(this);
// window closing using adapter
PleaseClose pc = new PleaseClose();
addWindowListener(pc);
// add to frame
add(bazar, "North");
// frame creation trio
setTitle("Scrollable List");
setSize(300, 350);
setVisible(true);
} // override the abstract method of AL
public void actionPerformed(ActionEvent e)
{
repaint();
}
public void paint(Graphics g)
{
String itemNames[] = bazar.getSelectedItems();
int itemIndexes[] = bazar.getSelectedIndexes();

  int y = 170;
double totalAmount = 0.0;
g.drawString("Sl.No. Item Name Item code Rate", 50, 150);
for(int i = 0; i < itemNames.length; i++, y += 25)
{
g.drawString((i + 1) + " " + itemNames[i] + " " + itemIndexes[i] + " " + rates[itemIndexes[i]],
50, y);
totalAmount += rates[ itemIndexes[i]];
}
g.setColor(Color.blue);

27
g.drawString("Total Bill Rs." + totalAmount, 50, y += 25);
g.setColor(Color.magenta); g.drawString("Thnaks Visit Again.", 50, y += 25);
g.setColor(Color.red);
g.drawString("Comments Book Available", 50, y += 25);
}
public static void main(String args[])
{
new SuperBazarBilling();
}
}
class PleaseClose extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

28
14 Write a simple servlet program which maintains a counter for the number of times it has
been accessed since its loading, initialize the counter using deployment descriptor.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HitCounter extends HttpServlet
{
private static final long serialVersionUID = 1L;
private int hitCount;
public void init()
{
// Reset hit counter.
hitCount = 0;
}
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.
}
}

29
30
15 Create a form processing servlet which demonstrates use of cookies and sessions
Html File

<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Servlet

// Import required java libraries


import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
/** * */
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));

// Set expiry date after 24 Hrs for both the cookies.


firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

31
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Setting Cookies Example";
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime =
new Date(session.getLastAccessedTime());

//String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = request.getParameter("first_name");
String userID = request.getParameter("first_name");

// Check if this is new comer on your web page.


if (session.isNew()){
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = request.getParameter("first_name");
//(String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
// Set response content type
response.setContentType("text/html");
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" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
32
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}

33
16 Write a simple JSP program for user Registration & then control will be transfer it into
second page
Html File

<html>
<body>

<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="text" name="surname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>

JSP FILE

<%@ 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>
<body>
<form>
<%= "Welcome "+request.getParameter("uname") %> <%=request.getParameter("surname") %>
</form>
</body>
</html>

17 Write a simple JSP program for user login form with static & dynamic database

34
Login Jsp

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


<%@ page import ="javax.sql.*" %>
<%
String userid=request.getParameter("user");
session.putValue("userid",userid);
String pwd=request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/
test","root","root");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from users where user_id='"+userid+"'");
if(rs.next())
{
if(rs.getString(2).equals(pwd))
{
out.println("welcome"+userid);

}
else
{
out.println("Invalid password try again");
}
}
else
%>
Reg Jsp

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


<%@ page import ="javax.sql.*" %>
<%
String user=request.getParameter("userid");
session.putValue("userid",user);
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root","root");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into users values ('"+user+"','"+pwd+"','"+fname+"',
'"+lname+"','"+email+"')");
%>

welcome.jsp
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
35
<%
String user=session.getValue("userid").toString();
%>
Registration is Successfull. Welcome to <%=user %>
Mysql Create Database Test:

Create Table Users:

Login.html

<html>
<body>
<form action="login.jsp" method="post">

User name :<input type="text" name="usr" />


password :<input type="password" name="pwd" />
<input type="submit" />
</form>
</body>
</html>
OUTPUT:

36
Reg.html
<form action="reg.jsp" method="post">
Email :<input type="text" name="email" />
First name :<input type="text" name="fname" />
Last name :<input type="text" name="lname" />
User name :<input type="text" name="userid" />
password :<input type="password" name="pwd" />
<input type="submit" />
</form>
OUTPUT:

37
18 Write a JSP program to display the grade of a student by accepting the marks of five
subjects.
Grade.html

<html>
<body>
<form action="main.jsp" method="GET">
Sub1: <input type="number" name="sub1">
<br />
Sub2:<input type="number" name="sub2" />
<br/>
Sub3: <input type="number" name="sub3">
<br/>
Sub4: <input type="number" name="sub4">
<br/>
Sub5: <input type="number" name="sub5">
<br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>

Main.jsp

<html>
<head>
<title>Display Grade</title>
</head>
<body>
<h1>Grade of Student</h1>
<ul>
<li><p><b>Sub1:</b>
<%=
request.getParameter("sub1")
%>
</p></li>
<li><p><b>Sub2:</b>
<%=
request.getParameter("sub2")
%>
</p></li>
<li><p><b>Sub3:</b>
<%=
request.getParameter("sub3")
%>
</p></li>
<li><p><b>Sub4:</b>
<%=
request.getParameter("sub4")
%>
38
</p></li>
<li><p><b>Sub5:</b>
<%=
request.getParameter("sub5")
%>
</p></li>
<li><p><b>Percentage</b>
<%
float x,y,w,z,v,a;
x=Float.parseFloat(request.getParameter("sub1"));
y=Float.parseFloat(request.getParameter("sub2"));
w=Float.parseFloat(request.getParameter("sub3"));
z=Float.parseFloat(request.getParameter("sub4"));
v=Float.parseFloat(request.getParameter("sub5"));
a=(((x+y+z+w+v)/500)*100);
out.println(a);
%>
</p></li>
<li><p><b>Grade</b>
<%

if((a>=80) & (a<=100))


out.println("Grade is A");
else if((a>=70) & (a<=80))
out.println("grade is B");
else if((a>=60) & (a<=70))
out.println("grade ic C");
else if((a>=50) & (a<=60))
out.println("grade ic D");
else
out.println("FAIL");

%>
</p></li>
</ul>
</body>
</html>

39
40

You might also like