0% found this document useful (0 votes)
13 views17 pages

Wa0064.

The document provides an overview of applet fundamentals, including applet life cycle, graphics handling, and JDBC architecture. It explains the differences between applets and applications, the process of creating and embedding applets in web pages, and how to pass parameters to applets. Additionally, it covers basic graphics operations in Java, such as drawing shapes and using the JDBC for database connectivity.

Uploaded by

kavyasanthosh107
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views17 pages

Wa0064.

The document provides an overview of applet fundamentals, including applet life cycle, graphics handling, and JDBC architecture. It explains the differences between applets and applications, the process of creating and embedding applets in web pages, and how to pass parameters to applets. Additionally, it covers basic graphics operations in Java, such as drawing shapes and using the JDBC for database connectivity.

Uploaded by

kavyasanthosh107
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Module V

Applet Fundamentals -applet tag, applet life cycle, passing parameters to applets. Working with
graphics - Line, Rectangle, Oval, Arc, color setting. JDBC architecture- JDBC connection,
JDBC statement object, JDBC drivers.
Applet Programming
Applets are small Java programs that are primarily used in Internet computing. They can be
transported over the Internet from one computer to another and run using the Applet Viewer
or any Web browser that supports Applet can perform arithmetic operations, display graphics,
play sounds, accept user input, create animation, and play interactive games.
Local and Remote Applets
We can embed applets into Web pages in two ways
One, we can write our own applets and embed them into Web pages. Second, we can
download an applet from a remote computer system and then embed it into a Web page.
An applet developed locally and stored a local system is known as a local applet. When a
Web page is trying to find a local applet, it does not need to use the internet and therefore the
local system does not require the Internet connection.

A remote applet is that which is developed someone else and stored on remote computer
connected to the Internet. If our system is connected to the Internet, wecan download the
remote applet on to our system and run on it.

In order to locate and load remote applet,we must know the applet's address on the Web. This
address is known as Uniform Reource Locator(URL) and must be specified the applet's
HTML document as the value of the CODEBASE attribute
Eg. CODEBASE = http : // www.netserve.com/applets
Applets Differ from Applications:
Both the applets and the stand alone applications are the java programs, there are significant
differences between them. Applets are not full featured application programs. They are
usually written to accomplish a small task or a component of a task. They are designed for
use on the internet and have certain limitations and restrictions in their design:
• Applets do not use the main( ) method for initiating the execution of the code. when
itloaded, automatically call certain method of applet class to start and execute the
applet code.
• Unlike stand-alone applications, Applets cannot be run independently. They are run
from inside a web page using a special feature known as HTML tag.
• Applets cannot read from or write to the files in the local computer.
• Applets cannot communicate with other serves on the network.
• Applets cannot run any program from the local computer.
• Applets area restricted from using libraries from other languages such as C or C++.

Applet Life Cycle


Every java applet inherits a set of default behaviours from the Applet class, when an applet is
loaded it undergoes a series of changes in its state as shown below:
1. Born on initialization state
2. Running state
• Idle state
• Dead or destroyed state
Applet’s state transition diagram is represented as shown below:
Initialization state:
Applets enters the initialization state when it is first loaded. This is achieved by calling the
init( ) method of applet class. The applet is born, we may do following:
1. Create objects needed by the applet
2. Set up initial values
3. Load images or fonts
4. Set up colors
The initialization occurs only once in the applet life cycle.
public void init( )
{
….
….Action
}
Running state:
Applets enters the running state when the system calls the start( ) method of applet class. This
occurs automatically after the applet is initialized. Starting can also occur if the applet is in
stopped state. The start method may be called more than once. We may override start( )
method to create a thread to control the applet.
public void start( )
{
….
….Action
}
Idle or stopped state :
An applet becomes idle when it is stopped from running. Stopping occurs automatically when
we leave the page containing the currently running applet. We can also do so by calling the
stop ( ) method explicitly. If we use a thread to run the applet, then we must use stop( )
method to terminate the thread.
public void stop( )
{
…..
…..Action
}
Dead state:
An applet is said to be dead when it is removed from memory. This occurs automatically by
invoking the destroy ( ) method when we quit the browser. Destroying stage occurs only once
in the applet’s life cycle.
public void stop( )
{
........Action
.........
}
Display State
Applet moves to the display state whenever it has to perform some output operations on the
screen. This happens immediately after the applet enters into the running state. The paint( )
method is called to accomplish this task.
public void paint( Graphics g)
{
................( Display statements)
................
}

Preparing an Applet:
Before we try to write applets, we must make sure that java is installed properly and also
ensure that either the java appletviewer or a java-enabled browser is available.
The steps involved are:
1. Building an applet code (.java file)
2. Creating an executable applet (.class file)
3. Designing a web page using HTML tags.
4. Preparing <APPLET> tag .
5. Incorporating <APPLET> tag into the web page.
6. Creating HTML file.
7. Testing the applet code.
Building Applet code:
The applet class from java.applet package provides life and behavior to the applet through its
methods such as init( ), start( ), and paint( ). Java calls the main( ) method directly to initiate
the execution of the program, when an applet is loaded , java automatically calls a series of
applet class methods for starting , running, and stopping the applet code. The applet class
therefore maintains the lifecycle of an applet. The paint( ) method of the applet class displays
the result of the applet code when it is called. The output may be text, graphics, or sound. The
paint( ) method which requires a Graphics
object as an argument is defined as follows:
public void paint (Graphics g)
Syntax:
import java.awt.*;
import java.applet.*;
….
…..
public class appletclassname extends Applet
{
……
……
public void paint (Graphics g)
{
……
……
}
……
……
}
Example:
import java.awt.*;
import java.applet.*;
public class Hellojava extends Applet
{
public void paint (Graphics g)
{
g.drawString(“Hello java”, 10, 100);
}
}
Creating an Executable Applet:
Executable applet is nothing but the .class file of the applet, which is obtained by compiling
the source code of the applet. The steps required for compiling the Hellojava applet.
• Move to the directory containing the source code and type the following commands:
javac Hellojava.java
• The compiled output file called Hellojava.class is placed in the same directory as the
source.
• If any error message is received then we must check for errors, correct them and
compile the applet again.

Designing a web page:


Java applets are programs that reside on Web pages. Inorder to run a java applet it is first
necessary to have a web page that references that applet. Web page is basically made up of
text and HTML tags that can be interpreted by a web browser or an applet viewer. Java
source code can be prepared using any ASCII text editor (e.g. Notepad). A web page is also
known as HTML page or HTML documents. Web pages are stored using a file extension
.html such as MyApplet.html.Web pages include both text that we want to display and
HTML tags (commands) to Web browsers.
A Web page is marked by an opening HTML tag < HTML> and a closing HTML tag and is
divided into the following three sections
1. Comment section (Optional)
2. Head section (Optional)
3. Body section
Comment Section: This section contains comments about the Web page. A comment line
begins with <! And ends with >. Web browsers will ignore the text enclosed between them.
Comments are optional and can be included anywhere in the Web page.
Head Section: The head section is defined with a starting <HEAD> tag and a closing
</HEAD> tag. This section usually contains a title for the Web page. The text enclosed in the
tags will appear in the title bar of the Web browser when it displays the page. The head
section is also optional.
Body Section: After the head section, comes the body section. We call this as body section
because this section contains the entire information about the Web page and its behaviour.
We can set up many options to indicate how our page must appear on the screen (like colour,
location, sound, etc.). Shown below is a simple body section:
Preparing <APPLET> tag: The <APPLET…> tag supplies the name of the applet to be
loaded and tells the browser how much space the applet requires. The ellipsis in the tag
<APPLET….> indicates that it contains certain attribute that must specified.
<APPLET
CODE = hellojava.class
WIDTH = 400
HEIGHT = 200 >
</APPLET>
The HTML code tells the browser to load the compiled java applet hellojava.class which is in
the same directory as the html file. Also specifies area for the applet output as 400 pixels
width and 200 pixels height.
Incorporating <APPLET> tag into the web page: Now we can put together the various
components of the web page and create a file known as HTML file. Insert the <APPLET> tag
in the page at the place where the output of the applet must appear.
Creating HTML file:
<HTML>
<HEAD>
<TITLE>
Welcome to java applet
</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1> welcome to the world of applet </H1>
</CENTER>
<BR>
<CENTER>
<APPLET
CODE = hellojava.class
WIDTH = 400
HEIGHT = 200>
</APPLET>
</CENTER>
</BODY>
</HTML>
Testing (Running) the applet code: To run the applet we require one of the following
Tools
1. Java-enabled web browser (such as HotJava, Netscape, Internet Explorer)
2. Java appletViewer
If we use java-enabled web browser we will see entire web page containing the applet. If we
use the appletviewer tool we will only see applet output. The appletviewer is available as a
part of the Java Development Kit. We can use it to run or applet as follows :
appletviewer hellojava.html
Passing parameters to applets
We can supply user-defined parameters to an applet using <PARAM…> tags. Each
<PARAM…> tag has a name attribute such as color, and a value attribute such as red. Inside
the applet code, the applet can refer to that parameter by name to find its value. We can
change the color of the text displayed to red by an applet by using a <PARAM…> tag as
follows:
<APPLET>
<PARAM= color value = “red”>
<APPLET>
Similarly, we can change the text to be displayed by an applet by supplying new text to the
applet through a <PARAM…> tag as shown below:
<PARAM NAME=text VALUE=“JAVA”>
Passing parameters to an applet code using <PARAM> tag is something similar to passing
parameters to the main() method using command line arguments. To set up and handle
parameters, we need to do two things.
1. Include appropriate <PARAM..> tags in the HTML Document.
2. Provide Code in the applet to parse these parameters.
Parameters are passed on an applet when it is loaded. We can define the init() method in the
applet to get hold of the parameters defined in the <PARAM> tags.
import java.awt.*;
import java.applet.*;
public class HelloJavaParam extends Applet
{ String str;
public void init()
{
str= getParameter (“string”); //Receiving parameter value
if( str==null)
str=“Java”;
str=“hello”+str; //Using the value
}
public void paint(Graphics g)
{
g.drawString(“str",10, 100);
}
}
WORKING WITH GRAPHICS

One of the most important features of Java is its ability to draw graphics. We can write Java
applets that draw lines, figures of different shapes, Images, and text in different fonts and
styles. We can also incorporate different colors in display.
THE GRAPHICS CLASS

Java's Graphics class includes methods for drawing many different types of shapes, from
simple line to polygons to text in a variety of fonts. The most commonly used drawing
methods in the Graphics class.
Method Description

clearRect( ) Erases a rectangular area Copies a rectangular area

copyArea ( ) Copies a rectangular area of the canvas to another area

drawArc ( ) Draws a hollow arc.

drawLine() Draws a straight line.

drawoOval ( ) Draws a hollow oval.

drawPolygon () Draws a hollow polygon.

drawRect ( ) Draws a hollow rectangle.

drawRoundRect ( ) Draws a hollow rectangle with rounded corners


drawString () Displays a text string.

fillArc ( ) Draws a filled arc.

fillPolygon () Draws a filled oval.

fillRect ( ) Draws a filled polygon.

fillRoundRect ( ) Draws a filled rectangle

getColor ( ) Draws a filled rectangle with rounded corners

getFont () Retrieves the current drawing color Retrieves the currently


used font.

getfontMetrics () Retrieves information about the current font

setColor ( ) Sets the drawing color.

setFont( ) Sets the font.

LINES AND RECTANGLES

The simplest shape we can draw with the Graphics class is a line. The drawLine () method
takese pair of coordinates, (xl, yl) and (x2, y2) as arguments and draws a line between them.
we can draw a rectangle using the drawRect() method. This method takes four be remaining
two represent the width and the height of the rectangle.
Program- Drawing a line
import java.awt.*;
import java.applet.*;
public class Line extends Applet
{
public void paint(Graphics g)
{
g.drawLine(100,10,250, 150);
g.drawLine(100,150,150,10);
}
}
<html>
<head>
</head>
<body>
<applet code = "Line.class" width = "420" height = "320"></applet>
</body>
</html>

Program- Drawing a rectangle


import java.awt.*;
import java.applet.*;
public class Rectangle extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawRect(120, 50, 100, 100);
}
}
<applet code = "Rectangle.class" width = "480" height = "360"></applet>

CIRCLES AND OVALS

The Graphics class does not have any method for circles or ellipses. The drawOval() method
can be used to draw a circle or an ellipse. Ovals are just like rectangles with overly rounded
corners. The drawOval() method takes four arguments: the first two represent the top-left
comer of the imaginary rectangle and the other two represent the width and height of the oval
itself
import java.awt.*;
import java.applet.*;
public class circle extends Applet
{
public void paint(Graphics g)
{
g.drawOval(20,20,200,120);
g.setColor(Color.green);
g.fillOval(70,30,100,100);
}
}
<html>
<head>
</head>
<body>
<applet code = "circle.class" width = "480" height = "360"></applet>
</body>
</html>
DRAWING ARCS

An arc is a part of an oval. The drawArc( ) designed to draw arcs takes six arguments. The
first four are the same as the arguments for drawOval() method and the last two represent the
starting angle of the arc and the number of degrees (sweep angle) around the arc.

import java.awt.*;
import java.applet.*;
public class Mouth extends Applet
{
public void paint (Graphics g)
{
g.drawArc(60, 125, 80, 40, 180, 180); // Draw an Arc Shape
g.fillArc(60, 125, 80, 40, 180, 180); // Fill an Arc Shape
}
}
<html>
<head>
</head>
<body>
<applet code = "Mouth.class" width = "480" height = "360"></applet>
</body>
</html>

JDBC ARCHITECTURE

JDBC is a phrase that is used to specify Java Database Connectivity. It is an interface with the
J Application Program known as Application Programming Interface (API) on one end and the
data set defined as a database on another end. It is used to link an application written in Java
language in any platform with database as backend. JDBC helps to connect to a database, send
queries and updates to the database, and retrieve and process the results obtained from the
database for queries.
JDBC link with java application and database can be represented as

Java application JDBC Backend database

The JDBC library includes


• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.
JDBC makes it possible to do establish a connection with a data source, send queries and
update statements to the data source, and process the results.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
JDBC Components
The JDBC API provides the following interfaces and classes –
Driver Manager: This class manages a list of database drivers. Matches connection requests
from the java application with the proper database driver using communication sub protocol.
The first driver that recognizes a certain sub protocol under JDBC will be used to establish a
database Connection.
Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use Driver Manager Objects, which
manages objects of this type. It also abstracts the details associated with working with Driver
objects.
Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection
object only.
Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.
Result Set: These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.
SQLException: This class handles any errors that occur in a database application.
There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection

Register the driver class


The forName() method of Class class is used to register the driver class. This method is used
to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Here, Java program is loading oracle driver to establish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
Create the connection object
The getConnection() method of DriverManager class is used to establish connection with
the database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Eg: Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe",
"system","password");

Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Eg: Statement stmt=con.createStatement();

Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Eg: ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Eg:
con.close();
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database.
There are 4 types of JDBC drivers:
• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)
JDBC-ODBC bridge driver

Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. Type-
1 driver is also called Universal driver because it can be used to connect to any of the databases.
As a common driver, it is used in order to interact with different databases, the data transferred
through this driver is not so secured.The ODBC bridge driver is needed to be installed in
individual client machines.Type-1 driver is not written in java, that’s why it isnot a portable
driver. This driver software is built-in with JDK so it doesnot need to install separately. It is a
database independent driver.
Native-API driver
The Native API driver uses the client -side libraries of the database.This driver converts JDBC
method calls into native calls of the database API. In order to interact with different database,
this driver needs their local API, that’s why data transfer is much more secure as compared to
type-1 driver.
This driver needs to be installed separately in individual client machines. The Vendor client
library needs to be installed on client machine. Type-2 driver isn’t written in java, that’s why
it isn’t a portable driver. It is a database dependent driver.
Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. Here all the database
connectivity drivers are present in a single server, hence no need of individual client-side
installation. Type-3 drivers are fully written in Java, hence they are portable drivers. No client
side library is required because of application server that can perform many tasks like auditing,
load balancing, logging etc.Network support is required on client machine. Maintenance of
Network Protocol driver becomes costly because it requires database-specific coding to be
done in the middle tier. Switch facility to switch over from one database to another database.
Thin driver
Type-4 driver is also called native protocol driver. This driver interact directly with database.
It does not require any native database library, that is why it is also known as Thin Driver. If
you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is type-4. If your Java application is accessing multiple types of databases at the same
time, type 3 is the preferred driver. Type 2 drivers are useful in situations, where a type 3 or
type 4 driver is not available yet for your database. The type 1 driver is not considered a
deployment-level driver, and is typically used for development and testing purposes only.

JDBC Statement objects


Statement are used for executing SQL statements.There are 3 types of JDBCstatements:
• Statement
It can be used for general purpose access to database.It is useful when you are using static
SQLstatements at run time.
• PreparedStatement
A PreparedStatement object is used when an application plans to reuse a statement multiple
times. The application prepares the SQL it plans to use. Once prepared, the application can
specify values for parameters in the prepared SQL statement. The statement can be executed
multiple times with different parameter values specified for each execution.
• CallableStatement objects.
A CallableStatement is used to call stored procedures that return values. The
CallableStatement has methods for retrieving the return values of the stored procedure.

You might also like