Notes Advance java -
Notes Advance java -
Unit I
1. AWT Classes:
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java. Java AWT components are platform-dependent i.e.
components are displayed according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS). The
java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc. The AWT tutorial will help the user to understand Java GUI
programming in simple and easy steps.
Why AWT is platform dependent?
Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating
API components like TextField, ChechBox, button, etc.For example, an AWT GUI with components like
TextField, label and button will have different look and feel for the different platforms like Windows,
MAC OS, and Unix. The reason for this is the platforms have different view for their native components
and AWT directly calls the native subroutine that creates those components. In simple words, an AWT
application will look like a windows application in Windows OS whereas it will look like a Mac
application in the MAC OS.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there
are classes for each component as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame,
Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it
contains and controls the layout of components.
Types of containers:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window. We need to create an instance of Window class to create this
container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for
holding the components. It can have other components like button, text field etc. An instance of Panel
class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have other
components like button, text field, scrollbar etc. Frame is most widely used container while developing
an AWT application.
AWT Classes
Class : Description
AWTEvent :
BorderLayout :
The border layout manager. Border layouts use five componentsNorth, South, East, West,
and Center.
Button :
Canvas :
Checkbox :
CheckboxGroup :
Choice :
Color :
Manages colors in a portable, platform-independent fashion.
Component :
Container :
Dialog : kkk
FileDialog :
Font :
Frame :
Creates a standard window that has a title bar, resize corners, and a menu bar.
Graphics :
Encapsulates the graphics context. This context is used by the various output methods to
List : Creates a list from which the user can choose. Similar to the standard Windows list box.
ScrollPane : A container that provides horizontal and/or vertical scroll bars for anothe
component.
SystemColor : Contains the colors of GUI widgets such as windows, scroll bars, text, and others.
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract class
that encapsulates all of the attributes of a visual component. Except for menus, all user
interface elements that are displayed on the screen and that interact with the user are
subclasses of Component. It defines over a hundred public methods that are responsible
for managing events, such as mouse and keyboard input, positioning and sizing the window,
and repainting.A Component object is responsible for remembering the current foreground
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels
etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.
The Container class is a subclass of Component. It has additional methods that allow
other Component objects to be nested within it. Other Container objects can be stored inside
of a Container (since they are themselves instances of Component). This makes for a
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have
recursively nestable, concrete screen component. Panel is the superclass for Applet. When
screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence,
a Panel is a window that does not contain a title bar, menu bar, or border. This is why you
don’t see these items when an applet is run inside a browser. When you run an applet using
an applet viewer, the applet viewer provides the title and border.
Other components can be added to a Panel object by its add( ) method (inherited from
Container). Once these components have been added, you can position and resize them
manually using the setLocation( ), setSize( ), setPreferredSize( ), or setBounds( )
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
The Window class creates a top-level window. A top-level window is not contained within
any other object; it sits directly on the desktop. Generally, you won’t create Window
objects directly. Instead, you will use a subclass of Window called Frame.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have
and has a title bar, menu bar, borders, and resizing corners. The precise look of a Frame will
Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one
other type of window that you will find valuable: Canvas. Derived from
Component, Canvas encapsulates a blank window upon which you can draw.
void fillRect(int startX, int startY, int width, int height) – Used to
draw a solid (colored) rectangle with the given parameters.
void fillRoundRect(int startX, int startY, int width, int height, int
xDiam, int yDiam) – Used to draw a solid (colored) rounded
rectangle whose x-diameter and y-diameter of the corners is
given by xDiam and yDiam respectively.
void drawOval(int startX, int startY, int width, int height) – Used
to draw an ellipse inside an imaginary rectangle whose
dimensions are specified by the given parameters. We can get a
circle by giving the same value for both width and height.
void fillOval(int startX, int startY, int width, int height) – Used
to draw a solid (colored) ellipse inside an imaginary rectangle
whose dimensions are specified by the given parameters. We
can get a circle by giving the same value for both width and
height.
void drawArc(int startX, int startY, int width, int height, int
startAngle, int sweepAngle) – Used to draw an arc inside an
imaginary rectangle. The start angle and the sweep angle are
specified by using startAngle and sweepAngle respectively.
void fillArc(int startX, int startY, int width, int height, int
startAngle, int sweepAngle) – Used to draw a solid (colored) arc
inside an imaginary rectangle. The start angle and the sweep
angle are specified by using startAngle and sweepAngle
respectively.
where r, g, b indicates the red, green and blue colors whose values must
be between 0 and 255.
if r, g or b are outside of the range 0 to 255 it will throw an
IllegalArgumentException.
Example -
Color c1 = new Color(0, 0, 0); // Black color
Color c2 = new Color(255, 255, 255); //White
Color
Color c3 = new Color(100, 0 ,0); // Light red
color
2- public Color(float r, float g, float b) -
where r, g, b indicates the red, green and blue colors whose values must
be between 0.0 and 1.0.
if r, g or b are outside of the range 0.0 to 1.0, it will throw an
IllegalArgumentException .
Example -
Color c1 = new Color(0.0f, 0.0f, 0.0f); // Black
color
Color c2 = new Color(1.0f, 1.0f, 1.0f); // White
color
Color c3 = new Color(0.5f, 0.0f, 0.0f);//Light
red color
It will creates a color with the specified combined RGB value consisting
of the red component in bits 16-23, the green component in bits 8-15,
and the blue component in bits 0-7.
Example -
Color c = new Color(0xff0000); // Red color
Color c = new Color(0x00ff00); //Green color
Color c = new Color(0x0000ff); // Blue color
You can change the color of graphics you are drawing by using Graphics
class setColor() method. It has the following syntax -
public abstract void setColor(Color c)
You can select the font style of your choice by using Font class of
java.awt package.
Font style can have one of the following three values ? Font.BOLD,
Font.PLAIN, Font.ITALIC. We can also combine these styles.
For example if we want bold and italic then we can combine Font.BOLD
+ Font.ITALIC.
size specifies the font size.
Using Fonts -
After creating new font, you can use it by using setFont() method.
import java.awt.*;
class Simple
Simple()
f1.setSize(500,1500);
f1.setTitle("my frame");
f1.setVisible(true);
f1.setLayout(null);
new Simple();
}
AWTExample1.java
// creating a button
Button b = new Button("Click Me!!");
// no layout manager
setLayout(null);
// main method
public static void main(String args[]) {
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
creating a TextField, Label and Button component on the Frame.
AWTExample2.java
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// no layout
f.setLayout(null);
// main method
public static void main(String args[]) {
}
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and Listener
interfaces for event handling.
Steps to perform Event Handling
Following steps are required to perform event handling:
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For
example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
1. Within class
2. Other class
3. Anonymous class
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
2. Windows Fundamentals:
Window Fundamentals
The AWT defines windows according to a class hierarchy that adds functionality
and specificity with each level. The two most common windows are those derived
from Panel, which is used by applets, and those derived from Frame, which creates
a standard application window. Much of the functionality of these windows is
derived from their parent classes. Thus, a description of the class hierarchies
relating to these two classes is fundamental to their understanding. Figure shows the
Container
Panel
The Panel class is a concrete subclass of Container. A Panel may be thought of as
a recursively nestable, concrete screen component. Panel is the superclass for
Applet. When screen output is directed to an applet, it is drawn on the surface of a
Panel object. In essence, a Panel is a window that does not contain a title bar, menu
bar, or border. This is why you don’t see these items when an applet is run inside a
browser. When you run an applet using an applet viewer, the applet viewer provides
the title and border.
Other components can be added to a Panel object by its add( ) method (inherited
from Container). Once these components have been added, you can position and
resize themmanually using the setLocation( ), setSize( ), setPreferredSize( ), or
setBounds( ) methods defined by Component.
Window
The Window class creates a top-level window. A top-level window is not contained
within any other object; it sits directly on the desktop. Generally, you won’t create
Window objects directly. Instead, you will use a subclass of Window called
Frame, described next.
Frame
Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one
other type of window that you will find valuable: Canvas. Derived from
Component, Canvas encapsulates a blank window upon which you can draw.
I) Frame()
II) Frame(String title)
- The first form creates a standard window that does not contain a title.
- The second form creates a window with the title specified by title.
There are several methods you will use when working with
Framewindows.Following are the useful methods of Component Class.
1. setSize( ) method:
The setSize( ) method is used to set the dimensions of the window.Its syntax
as follows.
2.DimensiongetSize( ) method:
This method returns the current size of the window contained within the
width and height fields of a Dimension object.
2. setVisible( ):
- After a frame window has been created, it will not be visible until you call
setVisible( ).
- By default frame is not visible,The Frame is visible if the argument to this
method is true. Otherwise, it is hidden.
setTitle( ):
Swing in java is part of Java foundation class which is lightweight and platform
independent. It is used for creating window based applications. It includes components
like button, scroll bar, text field etc. Putting together all these components makes a
graphical user interface. In this article, we will go through the concepts involved in the
process of building applications using swing in Java.
It becomes easier to build applications since we already have GUI components like
button, checkbox etc. This is helpful because we do not have to start from the scratch.
Container Class
Any class which has other components in it is called as a container class. For building
GUI applications at least one container class is necessary.
3. Dialog – It is like a pop up window but not fully functional like the frame
Explanation: All the components in swing like JButton, JComboBox, JList, JLabel are
inherited from the JComponent class which can be added to the container classes.
Containers are the windows like frame and dialog boxes. Basic swing components are
the building blocks of any gui application. Methods like setLayout override the default
layout in each container. Containers like JFrame and JDialog can only add a component
to itself. Following are a few components with examples to understand how we can use
them.
MVC(Model-View-Controller )Architecture
The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program
or application shall consist of data model, presentation information and
control information. The MVC pattern needs all these components to be
separated as different objects.
The model designs based on the MVC architecture follow MVC design
pattern. The application logic is separated from the user interface while
designing the software using model designs.
In Java Programming, the Model contains the simple Java classes, the View
used to display the data and the Controller contains the servlets. Due to this
separation the user requests are processed as follows:
1. A client (browser) sends a request to the controller on the server side,
for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
We can write the code of swing inside the main(), constructor or any other
method.
import javax.swing.*;
JFrame f;
Simple2()
{
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
Java Swing is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Icons
Swing introduces the concept of an icon for use in a variety of components.
The Icon interface and ImageIcon class make dealing with simple images
extremely easy.
Method
public abstract void paintIcon(Component c, Graphics g, int x, int y)
import javax.swing.*;
import java.awt.*;
The class JButton is an implementation of a push button. This component has a label
and generates an event when pressed.
JLabel is of the many Java classes from the Java Swing package. The JLabel
class from the swing package is able to display a text or a picture or both. Similar to
other classes in the Swing package, the label and label’s contents displayed by JLabel
are aligned using horizontal and vertical alignments. The programmer can specify
where the label’s contents will be displayed on the label’s display area by setting the
alignments.
By default, the text or more specifically, label text is aligned vertically and is displayed at
the center of their display area whereas an image or picture displayed is horizontally
centered by default.
JLabel is a class of java Swing . JLabel is used to display a short string or an
image icon. JLabel can display text, image or both . JLabel is only a display of
text or image and it cannot get focus . JLabel is inactive to input events such a
mouse focus or keyboard focus. By default labels are vertically centered but the
user can change the alignment of label.
JCheckBoxes:
The class JCheckBox is an implementation of a check box - an item that can be
selected or deselected, and which displays its state to the user.The JCheckBox class
in JAVA can be used as a toggle to switch off or on any functionality. This class
basically created a checkbox that provides two options which are: on and off.
Here on and off are denoted as true or false internally by the system. Then on
“on” state is arrived at by clicking on the checkbox. Clicking on it again changes
the state of the checkbox from “on” to “off”. This class inherits its characteristics
from the JToggleButton class.
JRadioButton:
We use the JRadioButton class to create a radio button. Radio button is use to
select one option from multiple options. It is used in filling forms, online
objective papers and quiz.
We add radio buttons in a ButtonGroup so that we can select only one radio
button at a time. We use “ButtonGroup” class to create a ButtonGroup and add
radio button in a group.
The JRadioButton class is used to create a radio button. It is used to choose
one option from multiple options. It is widely used in exam systems or quiz.
Combo Box:
The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits JComponent class.
Scroll panes:
Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen
size is limited, we use a scroll pane to display a large component or a
component whose size can change dynamically.
JMenuBar
The JTable class is used to display data in tabular form. It is composed of rows
and columns.The JMenuBar class is used to display menubar on the window
or frame. It may have several menus.The object of JMenu class is a pull down
menu component which is displayed from the menu bar. It inherits the
JMenuItem class.The object of JMenuItem class adds a simple labeled menu
item. The items used in a menu must belong to the JMenuItem or any of its
subclass.
1)URL class.
2)URLConnection class.
3)Socket class.
4)ServerSocket classes.
5)DatagramSocket.
6)MulticastSocket etc.
A datagram socket is the sending or receiving point for a packet delivery service. Each
packet sent or received on a datagram socket is individually addressed and routed. Multiple
packets sent from one machine to another may be routed differently, and may arrive in any
order.
and
MulticastSocket classes, on the other hand, all provide support for
communication over a connectionless protocol. The MulticastSocket class is
new in Java.
The URL and URLConnection classes define methods for working with
uniform resource locators (URLs). The URL class supports basic access to
data stored at a URL, while URLConnection offers complete control over all
aspects of working with a URL.
The InetAddress class represents network addresses,
so InetAddress objects are used by a number of the methods in other
classes in java.net.
The java.net package provides two basic mechanisms for accessing data and
other resources over a network. The fundamental mechanism is called a socket. A
socket allows programs to exchange groups of bytes called packets. There are a
number of classes in java.net that support sockets,
including Socket, ServerSocket, DatagramSocket, DatagramPacket,
and MulticastSocket. The java.net package also includes a URL class that provides
a higher-level mechanism for accessing and processing data over a network.
A socket is a mechanism that allows programs to send packets of bytes to each other.
The programs do not need to be running on the same machine, but if they are running
on different machines, they do need to be connected to a network that allows the
machines to exchange data. Java's socket implementation is based on the socket
library that was originally part of BSD UNIX. Programmers who are familiar with
UNIX sockets or the Microsoft WinSock library should be able to see the similarities
in the Java implementation.
A network address that specifies the system that should receive the packet.
A port number that tells the receiving system to which socket to deliver the
data.
Working of java.net Package
The java.net package is helpful in Java networking. It supports two protocols
such as:
Java Networking:
In Java Networking, many terminologies are used frequently. These widely used
Java Networking Terminologies are given as follows:
1. IP Address – An IP address is a unique address that distinguishes a
device on the internet or a local network. IP stands for “Internet Protocol.” It
comprises a set of rules governing the format of data sent via the internet or
local network. IP Address is referred to as a logical address that can be
modified. It is composed of octets. The range of each octet varies from 0 to
255.
Range of the IP Address – 0.0.0.0 to 255.255.255.255
For Example – 192.168.0.1
4. MAC Address – MAC address stands for Media Access Control address.
It is a bizarre identifier that is allocated to a NIC (Network Interface
Controller/ Card). It contains a 48 bit or 64-bit address, which is combined
with the network adapter. MAC address can be in hexadecimal
composition. In simple words, a MAC address is a unique number that is
used to track a device in a network.
7. Socket – The Socket class is used to create socket objects that help the
users in implementing all fundamental socket operations. The users can
implement various networking actions such as sending, reading data, and
closing connections. Each Socket object built
using java.net.Socket class has been connected exactly with 1 remote
host; for connecting to another host, a user must create a new socket
object.
10. URL – The URL class in Java is the entry point to any available sources
on the internet. A Class URL describes a Uniform Resource Locator, which
is a signal to a “resource” on the World Wide Web. A source can denote a
simple file or directory, or it can indicate a more difficult object, such as a
query to a database or a search engine.
Socket Programming:
S
Method Description
No.
ServerSocket Class
S
no. Method Description
public void This method is used to set the time-out value for the
setSoTimeout(int time in which the server socket pauses for a client
2 timeout) during the accept() method.
3 public Socket accept() This method waits for an incoming client. This method is
blocked till either a client combines to the server on the
specified port or the socket times out, considering that
the time-out value has been set using the
S
no. Method Description
import java.io.*;
import java.net.*;
// establish a connection
try {
System.out.println("Connected");
socket.getOutputStream());
catch (UnknownHostException u) {
System.out.println(u);
catch (IOException i) {
System.out.println(i);
while (!line.equals("End")) {
try {
line = input.readLine();
out.writeUTF(line);
catch (IOException i) {
System.out.println(i);
try {
input.close();
out.close();
socket.close();
catch (IOException i) {
System.out.println(i);
clientSide client
}
}
import java.io.*;
import java.net.*;
{
// starts server and waits for a connection
try {
System.out.println("Server started");
socket = server.accept();
System.out.println("Client accepted");
in = new DataInputStream(
new BufferedInputStream(
socket.getInputStream()));
while (!line.equals("End")) {
try {
line = in.readUTF();
System.out.println(line);
catch (IOException i) {
System.out.println(i);
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
catch (IOException i) {
System.out.println(i);
For the connection oriented service, the user has to follow the sequence operations
given below −
Connection is established
Information is sent
Connection is released
We have to establish a connection before starting the communication in connection
oriented service. Whenever the connection is established we can send the message
and after that we can release the connection.
Connection oriented service is more reliable than connectionless service. In connection
oriented service we can also send the message if there is an error at the receiver’s end.
For example: connection oriented is TCP protocol.
In connection-oriented services, the devices at both the endpoints use a protocol to
establish an end-to-end connection before sending any data.
Stream Socket Class:
Unicode (UTF) − Stands for Unicode Translation Format. It is developed by The Unicode
Consortium. If you want to create documents that use characters from multiple character sets,
you will be able to do so using the single Unicode character encodings. It provides 3 types of
encodings.
Java application generally uses the data output stream to write data that can
later be read by a data input stream (Basically it is use by client side).
Java application generally uses the data output stream to write data that can
later be read by a data input stream. (Basically it is use by client side).
Buffered readers are preferable for more demanding tasks, such as file and streamed readers.
Buffering the reads allows large volumes to be read from disk and copied to much faster RAM to
increase performance over the multiple network communications or disk reads done with each
read command otherwise. Java BufferedReader is preferable anywhere costly reads are likely to
be an issue, such as FileReaders and InputStreamReaders,
The Java System class comes in the module of "java.base" & in the package
of "java.lang".
4. JDBC
Design of JDBC
Java Database Connectivity (JDBC) is an Application Programming
Interface (API), from Sun microsystem that is used by the Java application to
communicate with the relational databases from different vendors. JDBC and
database drivers work in tandem to access spreadsheets and
databases. Design of JDBC defines the components of JDBC, which is used
for connecting to the database.
Performing Database Operations in Java using the JDBC API (SQL CREATE,
INSERT, UPDATE, DELETE, and SELECT).
JDBC or Java Database Connectivity is a Java API to connect and execute the
query with the database. It is used to write programs required to access
databases. JDBC, along with the database driver, can access databases and
spreadsheets. The enterprise data stored in a relational database(RDB) can be
accessed with the help of JDBC APIs.
JDBC has four major components that are used for the interaction with the
database.
1. JDBC API
2. JDBC Test Suite
3. JDBC Driver Manger
4. JDBC ODBC Bridge Driver
2) JDBC Test suite: JDBC Test suite facilitates the programmer to test the
various operations such as deletion, updation, insertion that are being
executed by the JDBC Drivers.
3) 3) JDBC Driver manager: JDBC Driver manager loads the database-
specific driver into an application in order to establish the connection
with the database. The JDBC Driver manager is also used to make the
database-specific call to the database in order to do the processing of
a user request.
Architecture of JDBC
1) Application: It is the Java servlet or an applet that communicates with
the data source.
2) The JDBC API: It allows the Java programs to perform the execution of
the SQL statements and then get the results.
A few of the crucial interfaces and classes defined in the JDBC API are the
following:
o Drivers
o DriverManager
o Statement
o Connection
o CallableStatement
o PreparedStatement
o ResultSet
o SQL data
4) JDBC drivers: To interact with a data source with the help of the JDBC,
one needs a JDBC driver which conveniently interacts with the respective
data source.
Metadata:
Metadata in Java defined as the data about the data is called “Metadata”.
Metadata is also said to be documentation about the information which is
required by the users. This is one of the essential aspects in the case of data
warehousing.
For Example: Suppose we say that a data item about a person is 80. This
must be defined by noting that it is the person's weight and the unit is
kilograms. Therefore, (weight, kilograms) is the metadata about the data is
80.
Reasons to use:
o First, it acts as the glue (Paste) that links all parts of the data
warehouses.
o Next, it provides information about the contents and structures to the
developers.
o Finally, it opens the doors to the end-users and makes the contents
recognizable in their terms.
Types of Metadata
o Operational Metadata
o Extraction and Transformation Metadata
o End-User Metadata
Operational Metadata
As we know, data for the data warehouse comes from various operational
systems of the enterprise. These source systems include different data
structures. The data elements selected for the data warehouse have various
fields lengths and data types.
In selecting information from the source systems for the data warehouses,
we divide records, combine factor of documents from different source files,
and deal with multiple coding schemes and field lengths. When we deliver
information to the end-users, we must be able to tie that back to the source
data sets. Operational metadata contains all of this information about the
operational data sources.
End-User Metadata
The end-user metadata is the navigational map of the data warehouses. It
enables the end-users to find data from the data warehouses. The end-user
metadata allows the end-users to use their business terminology and look for
the information in those ways in which they usually think of the business.
Transactions:
Transactions enable you to control if, and when, changes are applied to the database. It
treats a single SQL statement or a group of SQL statements as one logical unit, and if
any statement fails, the whole transaction fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC
driver uses by default, use the Connection object's setAutoCommit() method. If you
pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a
boolean true to turn it back on again.
5. Servlet:
Introduction of Servlet:
Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the
webserver, process the request, produce the response, then send a response
back to the webserver.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
The entire life cycle of a Servlet is managed by the Servlet container which
uses the javax.servlet.Servlet interface to understand the Servlet object and
manage it. So, before creating a Servlet object, let’s first understand the life
cycle of the Servlet object which is actually understanding how the Servlet
container manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through
four stages,
Loading a Servlet.
Initializing the Servlet.
Request handling.
Destroying the Servlet.
1.Loading a Servlet: The first stage of the Servlet lifecycle involves loading
and initializing the Servlet by the Servlet container. The Web container or
Servlet Container can load the Servlet at either of the following two stages :
Initializing the context, on configuring the Servlet with a zero or positive
integer value.
If the Servlet is not preceding stage, it may delay the loading process until
the Web container determines that this Servlet is needed to service a
request.
A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
POS Asks the server to accept the body info attached. It is like GET request with extra
T info sent with the request.
6. Introduction to JSP:
Java Server Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based applications.
JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases.
Features of JSP
Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
Reduction in the length of Code :- In JSP we use action tags, custom
tags etc.
Connection to Database is easier :-It is easier to connect website to
database and allows to read or write data easily to the database.
Make Interactive websites :- In this we can create dynamic web pages
which helps user to interact in real time environment.
Portable, Powerful, flexible and easy to maintain :- as these are
browser and server independent.
No Redeployment and No Re-Compilation :- It is dynamic, secure and
platform independent so no need to re-compilation.
Extension to Servlet :- as it has all features of servlets, implicit objects
and custom tags
First JSP:
Let's begin with a simple JSP example. We shall use the webapp called "hello" that we
have created in our earlier exercise. Use a programming text editor to enter the
following HTML/JSP codes and save as "first.jsp" (the file type of ".jsp" is
mandatory) in your webapp (web context) home directory (i.e., "webapps\hello".
<html>
<head><title>First JSP</title></head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
</body>
</html>
To execute the JSP script: Simply start your Tomcat server and use a browser to issue
an URL to browse the JSP page (i.e., http://localhost:8080/hello/first.jsp).
From your browser, choose the "View Source" option to check the response message. It
should be either of the followings depending on the random number generated.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
You can access a variety of objects, including enterprise beans and JavaBeans
components, within a JSP page. JSP technology automatically makes some objects
available, and you can also create and access application-specific objects.
Implicit Objects
Implicit objects are created by the Web container and contain information related to a
particular request, page, or application. Many of the objects are defined by the Java
Servlet technology underlying JSP technology.
Scriptlets:
Scripting elements in JSP must be written within the <% %> tags. The JSP
engine will process any code you write within the pair of the <% and
%> tags, and any other texts within the JSP page will be treated as HTML
code or plain text while translating the JSP page.
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Mixing Scriptlets and HTML
You can mix scriptlets with HTML to make part of the HTML conditional, or
looping.
All you have to do is keep the Java within the <% %> tags, and the HTML out.
The compiler will take care of the rest.
The following example illustrates mixing HTML with JSP code. For
starters, typically some of the JSP programs look weird and confusing
because both the HTML and JSP code is mixed. But if you can carefully
understand what tag is what, you can write even more complex JSP
programs than you see.
One key point you need to know that, you can end a scriptlet tag
anywhere you want. For example
<%
if(true){
%>
<p>This is in the if-block. </p>
<%
out.println("This is that's it.");
}
%>
As you can see the first tag <% %> was ended unexpectedly to write the
message This is in the if-block. This is a html line executed only if the if-
condition is met. Isn’t this simple?
Now let us write a program.
Directives:
The jsp directives are messages that tells the web container how to
translate a JSP page into the corresponding servlet.
<html>
<body>
</body>
</html>
A JSP declaration is used to declare variables and methods in a page’s scripting language
Tags
JSP Tags
JSP scripting language include several tags or scripting elements that performs various tasks such
as declaring variables and methods, writing expressions, and calling other JSP pages. These are
known as JSP scripting elements. The different types of scripting elements are summarized in
the Table 1:
Table 1. JSP Tags
JSP Tag Brief Description Tag Syntax
Expression Used as a shortcut to print values in the output <%= an Expression %>
HTML of a JSP page.
Session:
In simple terms, JavaBeans are classes which encapsulate several objects into a single
object. It helps in accessing these object from multiple places. JavaBeans contains
several elements like Constructors, Getter/Setter Methods and much more.
A JavaBean is a specially constructed Java class written in the Java and coded
according to the JavaBeans API specifications.
JavaBeans are classes that encapsulate many objects into a single object (the
bean).Serialization is a mechanism of converting the state of an object into a
byte stream. Deserialization is the reverse process where the byte stream is
used to recreate the actual Java object in memory. This mechanism is used to
persist the object.
JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the
object. The attribute can be of any Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties
are accessed through two methods in the JavaBean's implementation class −
getPropertyName()
1 For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.
setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.
The byte stream created is platform independent. So, the object serialized on
one platform can be deserialized on a different platform. To make a Java object
serializable we implement the java.io.Serializable interface.
Reusability is the main concept in any programming language. A JavaBean is a
software component that has been designed to be reusable in a variety of
environments.
Following are the unique characteristics that distinguish a JavaBean from other Java
classes −
It provides a default, no-argument constructor.
It should be serializable and that which can implement the Serializable interface.
It may have a number of properties which can be read or written.
It may have a number of "getter" and "setter" methods for the properties.
Syntax for setter methods:
Advantages of javaBean:
6. A Bean may register to receive events from other objects and can
generate events that are sent to other objects.
bean-writing process:
A Java bean is a Java class that has private member variables, public
getter and setter methods, and a zero-argument, public constructor
(supplied automatically by the compiler). To create a Java bean, follow
these seven steps.
Open your text editor and create a new file that will contain the Java bean
source. Type in the following Java statements:
Open your text editor and create a new file that will contain the Java bean
source. Type in the following Java statements:
The Java bean has two properties, firstName and lastName. A property is a
private variable exposed to external programs by means of getter and setter
methods.
The program will instantiate the Java bean and then call the setter and getter
methods of the newly created Java bean.
1. Save your file as CreateAJavaBean.java.
2. Open a command prompt and navigate to the directory containing your new Java
programs. Then type in the command to compile the Java bean source and
hit Enter.