Advanced Java Programming Notes
Advanced Java Programming Notes
1
Programming: Subject Code:22517
Teaching
Scheme #Examination
Scheme
Theory Practical
Credit
L T P (L+T+P) Paper
Hrs.
ESE PA Total ESE PA Total
Max Min M
Min Max Min Max Min Max M in Max Min
a
x
02 Swings 10 02 02 06
03 Event Handling 12 02 02 08
04 Networking Basics 10 02 04 04
06 Servlets
Welcome To VCLIENT WORLD 14 04 04 06
Introduction to 12
Abstract Windowing Toolkit (AWT) 4
Marks
scroll
bars
• AWT contains numerous classes and methods that allow you to create
and manage window.
• import java.awt.*;
• Java AWT is an API to develop GUI or windowbased application in
java.
• Java AWT components are platform-dependent
• i.e. components are displayed according to the view of operating
system.
• AWT is heavyweight i.e. its components uses the resources of system.
Welcome To VCLIENT WORLD
AWT Class Hierarchy 9
• java.lang.Object
• java.awt. Component
• java.awt.Container
• The methods of the class Container are:
• java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
+----java.awt.Panel
|
+----java.applet.Applet
…so you
Welcome can WORLD
To VCLIENT display things in an Applet
Applets 18
• import java.applet.*;
• Import java.awt.*;
• Applet code in comment
• Extends Applet class
• Life cycle method
• Class must be public
• Container (Applet)
• Containers (Panels)
• Component (Canvas)
• Components (Buttons)
• Components (TextFields)
• Components (Labels)
Welcome To VCLIENT WORLD
Window 21
Choice Scrollbar
Button
Checkbox
Layout Manager 27
• int getAlignment( )
AWT Control: Button 30
• AdjustmentEvent is generated.
• Implement the AdjustmentListener interface.
• adjustmentValueChanged() method we have to override
• getAdjustmentType( ) method can be used to determine the type
of the adjustment.
• BLOCK_DECREMENT: A page-down event has been generated.
• BLOCK_INCREMENT: A page-up event has been generated.
• TRACK: An absolute tracking event has been generated.
• UNIT_DECREMENT: user clicks in the right arrow of a horizontal scroll bar,
or the bottom arrow of a vertical scroll bar
• UNIT_INCREMENT: User clicks in the left arrow of a horizontal scroll bar, or
Welcome To VCLIENT WORLD
the top arrow of a vertical scroll bar.
AWT Control: TextField 43
• import java.awt.*;
• import java.applet.*;
• public class FlowLayoutExample extends Applet {
• public void init () {
• setLayout (new FlowLayout ()); // default
• add (new Button ("One"));
• add (new Button ("Two"));
• add (new Button ("Three"));
• add (new Button ("Four"));
• add (new Button ("Five"));
•Welcome
addTo(new Button ("Six"));
VCLIENT WORLD
• }}
BorderLayout 53
• import java.awt.*;
• import java.applet.*;
• public class GridLayoutExample extends Applet {
• public void init () {
• setLayout(new GridLayout(2, 3));
• add(new Button("One"));
• add(new Button("Two"));
• add(new Button("Three"));
• add(new Button("Four"));
• add(new Button("Five"));
•Welcome
} To VCLIENT WORLD
•}
CardLayout 59
• GridBagLayout()
GridBagLayout 63
• Constructors:.
• Dialog(Frame parentWindow, boolean mode)
• Dialog(Frame parentWindow, String title, boolean mode)
• To create Dialog Box:
• Create Frame or Applet
• Create another class which extends Dialog class.
• Call this new class from Frame/Applet class.
• In constructor of Extended Dialog class, use super method and pass
vales to constructor of Dialog
Welcome To VCLIENT WORLD
FileDialog 73
• Java provides a built-in dialog box that lets the user specify a file.
• To create a file dialog box, instantiate an object of type
FileDialog.
• Constructor:
• FileDialog(Frame parent, String boxName)
• FileDialog(Frame parent, String boxName, int how)
• FileDialog(Frame parent)
• Int how: FileDialog.LOAD, FileDialog.SAVE
• Methods:
• String getDirectory( )
Welcome To VCLIENT WORLD
• String getFile( )
UNIT –II SWINGS 10
2.1 Introduction to Swing 74
Marks
• Package : javax.swing.*
• Swing is set of classes which provides more powerful and flexible
components as compare to AWT.
• Swing supplies several exciting additions, including tabbed panes, scroll
panes, trees, and tables.
• Build on top of AWT API and acts as replacement of AWT API.
• Swing component follows a Model-View-Controller
• Swing Components are implemented using Java and so their LOOK & FEEL
is platform independent.
• Called
Welcome To VCLIENT lightweight
WORLD components
Introduction to Swing 75
• AWT uses Applet and Frame while Swing uses JApplet and JFrame
for GUI.
• AWT is platform dependent code while Swing code is platform
independent.
• Swing has bigger collection of classes and interfaces as compare to
AWT.
• In Swing extra feature to Button: Provide Image.
• Swing provides: Tree, Table, Scrollpanes, Tabbedpanes etc new
feature which not available in AWT.
Welcome To VCLIENT WORLD
Difference Between AWT & Swing 78
Awt Swing
Native component. Pure Java component.
Components are heavy weight. Components are light weight.
Native look and feel. Pure java component.
Does not have complex component. It has additional components like JTree, JTable, JProgressBar, and
JSlider ect.
Applet can not have menu. JApplet can contain menu.
Components like Button can not have images. Components like JButton can have images.
List has scrollbar. JList doesn’t support scrolling but this can be done using ScrollPane.
Components can be added directly on the Window While adding component to window or Frame, they have to be added
or Frame. on its ContentPane.
Does not have SplitPane or TabbedPane. Has SplitPane or TabbedPane.
Do not have MDI window. MDI can be achieved using JInternalFrame Object.
MenuWelcome To VCLIENT WORLD
item can not have images or radio button Menu item can have images or radio button or check boxes.
2.2 Swing Components : JApplet 79
• java.lang.Object
+--- java.awt.Component
+----java.awt.Container
+--------java.awt.Panel
+--------java.applet.Applet
+-------javax.swing.JApplet
Applet JApplet
• java.lang.Object
• java.awt.Component
• java.awt.Container
• java.awt.Window
• java.swing.JWindow
• import javax.swing.*;
• public class JFrameDemo {
• public static void main(String[] args) {
• JFrame f = new JFrame("The Frame");
• f.setSize(300, 300);
• f.setLocation(100, 100);
• f.setVisible(true);
• }
• }
Welcome To VCLIENT WORLD
•
JApplet and JFrame 87
• int getIconWidth( )
JLabel and ImageIcon 92
• The ImageIcon class implements the Icon interface that declares the
methods
• int getIconHeight( )
• int getIconWidth( )
• Other methods:
• Icon getIcon( )
• String getText( )
• void setIcon(Icon i)
• void setText(String s)
Welcome To VCLIENT WORLD
JTextField 94
• java.lang.Object
• java.awt.Component
• java.awt.Container
• javax.swing.JComponent
Welcome To VCLIENT WORLD
• javax.swing.text.JTextComponent
JTextField 95
• Constructors:
• JTextField ()
Constructs a new TextField.
• JTextField (int columns)
Constructs a new empty TextField with the specified number of columns.
• JTextField (String text)
Constructs a new TextField initialized with the specified text.
• JTextField (String text, int columns)
Constructs a new TextField initialized with the specified text and columns.
• Method:
• String getText ()
• Void setText (String s)
Welcome To VCLIENT WORLD
• int getColumns()
AbstractButton 96
• Constructors:
• JButton(Icon i)
• JButton(String s)
• JButton(String s, Icon i)
• JCheckBox(Icon i)
• JCheckBox(Icon i, boolean state)
• JCheckBox(String s)
• JCheckBox(String s, boolean state)
• JCheckBox(String s, Icon i)
• JCheckBox(String s, Icon i, boolean state)
• JRadioButton(Icon i)
• JRadioButton(Icon i, boolean state)
• JRadioButton(String s)
• JRadioButton(String s, boolean state)
• JRadioButton(String s, Icon i)
• JRadioButton(String s, Icon i, boolean state)
• ItemEvent is generated.
• Implements ItemListener interface
• Override: itemStateChnaged(ItemEvent ie) method defined by
ItemListener
• TreePath object that encapsulates information about the tree node that
was selected by the user.
• The TreeNode interface declares methods that obtain information about
a tree node.
• The MutableTreeNode interface extends TreeNode. It declares methods
that can insert and remove child nodes or change the parent node.
• The DefaultMutableTreeNode class implements the MutableTreeNode
interface. It represents a node in a tree.
• Constructor: DefaultMutableTreeNode(Object obj)
• AWT – The Abstract Window Toolkit provides basic graphics tools (tools for
putting information on the screen)
• Swing – A much better set of graphics tools
• Container – a graphic element that can hold other graphic elements (and is itself
a Component)
• Component – a graphic element (such as a Button or a TextArea) provided by a
graphics toolkit
• listener – A piece of code that is activated when a particular kind of event occurs
• layout manager – An object whose job it is to arrange
• Components in a Container
• Two requirements:
• It must have been registered with one or more sources to
receive notifications.
• It must implement methods to receive and process these
notifications.
Welcome To VCLIENT WORLD
Event Classes 121
• Event Classes are core of Java’s event handling
mechanism.
• EventObject is the root of the Java event class hierarchy
which is present in java.util.
• It is the superclass for all events.
• Constructor:
• EventObject(Object src).
• EventObject class has defines two methods:
• Object getSource( ) : method returns the source of the event.
Welcome To VCLIENT WORLD
• String toString( ) : returns string equivalent of the event.
Event Classes : AWTEvent 122
• ActionEvent
• ComponentEvent
• ContainerEvent
• FocusEvent
• ItemEvent
• KeyEvent
• MouseEvent
• TextEvent
• WindowEvent
Welcome To VCLIENT WORLD
ActionEvent 125
• There are many other integer constants that are defined by KeyEvent.
•
• VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents
of the numbers and letters.
•
• VK_ENTER VK_ESCAPE VK_CANCEL
• VK_UP VK_DOWN VK_LEFT VK_RIGHT
• VK_PAGE_DOWN VK_PAGE_UP VK_SHIFT
• VK_ALT VK_CONTROL
Welcome To VCLIENT WORLD
MouseEvent Class 133
• Eight types of mouse events.
• The MouseEvent class defines the following integer constants
• MOUSE_CLICKED The user clicked the mouse.
• MOUSE_DRAGGED The user dragged the mouse.
• MOUSE_ENTERED The mouse entered a component.
• MOUSE_EXITED The mouse exited from a component.
• MOUSE_MOVED The mouse moved.
• MOUSE_PRESSED The mouse was pressed.
• MOUSE_RELEASED The mouse was released.
• MOUSE_WHEEL The mouse wheel was moved
• These are generated by text fields and text areas when characters
are entered by a user or program.
• TextEvent defines the integer constant
• TEXT_VALUE_CHANGED.
• Constructor:
• TextEvent(Object src, int type)
}
Illustration (contd..) 140
}
3.3 Adapter Class 142
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter
Welcome To VCLIENT WORLD
WindowListener
3.4 Inner Class 144
• Change Listener
• Container Listener
• Document Listener
• Focus Listener
• Internal Frame Listener
• ListSelectionListener
• Property Change Listener
• Table Model Listener
• TreeSelectionListener
• TreeWillExpandListener
• TreeExpansionListener
Welcome To VCLIENT WORLD
Common Event-Handling Issues 161
1. You are trying to handle certain events from a component, but it doesn’t generate
the events it should.
Make sure you have registered the right kind of listener to detect the events.
Make sure you have registered the listener on the right object.
Make sure you have implemented the event handler correctly, especially, the
method signatures.
2. Your combo box isn’t generating low level events like focus events.
Since combo boxes are compound components, i.e., components implemented
using multiple components, combo-boxes do not fire the low-level events that
simple components fire.
3. The document for an editor pane is not triggering document events.
The document instance for an editor pane might change when loading text from
a URL. Thus your listeners might be listening for events on an unused document.
Welcome To VCLIENT WORLD
Hence, make sure that the code adjusts for possible changes to the document if
your program dynamically loads text into an editor pane.
Networking and Security 162
• Chapter 04
java.net
• Packet oriented
• Packets routed between computers
• Unreliable
java.net
• Packet oriented
• Message split into datagrams
• Send datagrams as packets on network layer
• Unreliable but fast
• Application must deal with lost packets
• Examples
• Ping
• Streaming multimedia
• Online games
Welcome To VCLIENT WORLD
Transmission Control Protocol (TCP) 174
• Connection oriented
• Message split into datagrams
• Send datagrams as packets on network layer
• Provides illusion of reliable connection
• Extra messages between sender / recipient
• Resend packets if necessary
• Ensure all packets eventually arrive
• Store packets and process in order
Welcome To VCLIENT
Transmission Control Protocol (TCP) 175
TCP UDP
Reliable Unreliable
Retransmit No retransmission
• Socket I/O is based on the Java I/O support (in the package
java.io).
• getInputStream()
• getOutputStream()
• close()
• getInetAddress()
• getPort()
• getLocalPort()
• accept()
• close()
• getInetAddress()
• getLocalPort()
• Basic steps
1. Determine server location – IP address & port
2. Open network connection to server
3. Write data to server (request)
4. Read data from server (response)
5. Close network connection
6. Stop client
• Basic steps
1. Determine server location - port (& IP address)
2. Create server to listen for connections
3. Open network connection to client
4. Read data from client (request)
5. Write data to client (response)
6. Close network connection to client
7. Stop server
• TCP Protocol
write reply to
connectionSocket read reply from
connectionSocket
close
Welcome To VCLIENT WORLD connectionSocket close
clientSocket
Socket programming with TCP
195
Client must contact server • When client creates socket:
• server process must first client TCP establishes
connection to server TCP
be running
• When contacted by client,
• server must have created server TCP creates new socket
socket (door) that for server process to
welcomes client’s contact communicate with client
Client contacts server by: • allows server to talk with
multiple clients
• creating client-local TCP
socket application viewpoint
• specifying IP address, port TCP provides reliable, in-order
number of server process transfer of bytes (“pipe”)
Welcome To VCLIENT WORLD between client and server
TCP server 196
public static void main(String[] argv) throws IOException {
ServerSocket sock;
Socket clientSock;
try {
sock = new ServerSocket(PORT);
while ((clientSock = sock.accept( )) != null) {.
process(clientSock);
}
} catch (IOException e) {
System.err.println(e);
}
}
static void process(Socket s) throws IOException {
DataOutputStream os = new DataOutputStream(s.getOutputStream( ));
long time = System.currentTimeMillis( );
os.writeInt((int)time)
Welcome To VCLIENT WORLD
s.close( );
}
TCP server – multithreaded case 197
public class ServerThreaded {
public static final int PORT = 7;
public static void main(String[] av){
new ServerThreaded().runServer( );
}
public void runServer( ){
ServerSocket sock;
Socket clientSocket;
try {
sock = new ServerSocket(PORT);
System.out.println("ServerThreaded ready for connections.");
/* Wait for a connection */
while(true){
clientSocket = sock.accept( );
/* Create a thread to do the communication, and start it */
new Handler(clientSocket).start( );
Welcome To VCLIENT WORLD
}
} catch(IOException e) { System.exit(1); }
}
TCP server – multithreaded case 198
class Handler extends Thread {
Socket sock;
Handler(Socket s) {
sock = s;
}
public void run( ){
System.out.println("Socket starting: " + sock);
try { DataInputStream is = new DataInputStream(sock.getInputStream( ));
PrintStream os = new PrintStream(sock.getOutputStream( ), true);
String line;
while ((line = is.readLine( )) != null) {
os.print(line + "\r\n");
os.flush( );
}
sock.close( );
} catch (IOException e) {return;}
System.out.println("Socket
Welcome To VCLIENT WORLD ENDED: " + sock);
}
}
Classes 199
•InetAddress
•Socket
•URL
•URLConnection
•ServerSocket
•DatagramSocket
•DatagramPacket
Welcome To VCLIENT WORLD
Packet Oriented 200
• UDP Protocol
• close()
• getLocalAddress()
• getLocalPort()
• receive(DatagramPacket p)
• send(DatagramPacket p)
• setSoTimeout(int t)
• getSoTimeout()
• getAddress()
• getData()
• getLength()
• getPort()
• setAddress()
• setData()
• setLength()
• setPort()
Welcome To VCLIENT WORLD
Client/server socket interaction: UDP 206
Server (running on hostid) Client
create socket, create socket,
port=x, for clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x),
send datagram request
using clientSocket
read request from
serverSocket
write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port number close
clientSocket
java.net
• Internet
• Underlying medium is unreliable (IP), packet oriented
• Provides two views
• Reliable, connection oriented (TCP)
• Unreliable, packet oriented (UDP)
• Java
• Object-oriented classes & API
• IP – InetAddress
• TCP – Socket, ServerSocket
• UDP – DatagramSocket, DatagramPacket
Welcome To VCLIENT WORLD
Summary 216
Questions?
• JDBC drivers implement the defined interfaces in the JDBC API for
interacting with your database server.
• Package: java.sql
• JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then
receiving results with Java.
• JDBC is a Java API that is used to connect and execute query for
the database.
• JDBC API uses jdbc drivers to connects to the database.
Java
Application
JDBC API
• • Advantages:
• easy to use.
• can be easily connected to any database.
• Disadvantages:
• Performance degraded because JDBC method call is converted into the
ODBC function calls.
• The ODBC driver needs to be installed on the client machine.
• Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
• Disadvantage:
• The Native driver needs to be installed on the each client
machine.
• The Vendor client library needs to be installed on client machine.
• Advantage:
• No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
• Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
•
Welcome To VCLIENT WORLD
Type 4 Drivers 235
• The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver.
• It is fully written in Java language.
• Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
• Disadvantage:
• Drivers depends on the Database.
• Insert Record:
• Statement st = con.createStatement();
• St.executeUpdate(“insert into dept values (‘comp’,101,’BVP’)”);
• Delete Record:
• Statement st = con.createStatement();
• St.executeUpdate(“delete from dept where deptno=101”);
• beforeFirst()
• afterLast()
• first()
• last()
• previous()
• next()
• getRow()
• Specific Objectives:
• To write web based applications using servlets
• To write servlet for cookies and session tracking.
Data is sent in header to the server Data is sent in the request body
Get request can send only limited Large amount of data can be sent.
amount of data
Get request is not secured because Post request is secured because data is
data is exposed in URL not exposed in URL.
• Get request contains path to server and the parameters added to it.
• Post requests are used to make more complex requests on the server. For
instance, if a user has filled a form with multiple fields and the application
wants to save all the form data to the database. Then the form data will be
sent to the server in POST request body, which is also known as Message
body.
Process Thread
Takes more time to create Takes less time to create
More secure Offers multiple threads of execution
More fault tolerant Share information with other threads
Less secure
More vulnerable to crashes
• HTTP:
Http is the protocol that allows web servers and browsers to
exchange data over the web.
It is a request response protocol.
Http uses reliable TCP connections by default on TCP port 80.
It is stateless means each request is considered as the new
request. In other words, server doesn't recognize the user by
default.
• The browser sends an HTTP request to the Java web server. The
web server checks if the request is for a servlet. If it is, the
servlet container is passed the request.
• The servlet container will then find out which servlet the request
is for, and activate that servlet.
• The servlet is activated by calling the Servlet.service()method.
• Once the servlet has been activated via the service() method the
servlet processes the request, and generates a response. The
response is then sent back to the browser.
Welcome To VCLIENT WORLD
Servlet Containers 283
• Server:
• It is a running program or software that provides services.
• Two types
• Web Server:
• Web server contains only web or servlet container. It can be used for servlet, jsp,
struts, jsf etc. It can't be used for EJB.
• Example of Web Servers are: Apache Tomcat and Resin.
• Application Server:
• Application server contains Web and EJB containers. It can be used for servlet, jsp,
struts, jsf, ejb etc.
• Ex: Jboss, Glassfish, Weblogic, Websphere
Welcome To VCLIENT WORLD
Content Type 285
• Content Type:
• Content Type is also known as MIME (Multipurpose internet Mail Extension) Type.
• It is a HTTP header that provides the description about what are you sending to the
browser.
• text/html
• text/plain
• application/msword
• application/vnd.ms-excel
• application/jar
• application/pdf
• application/octet-stream
• application/x-zip
• images/jpeg
• video/quicktime
Welcome To VCLIENT WORLD
Types of Servlet 286
• Generic Servlet:
• It is in javax.servlet.GenericServlet package
• It is protocol independent.
• HTTP Servlet
• It is in javax.servlet.HTTPServlet package
• Built-in HTTP protocol support.
• Managed by :____________.
• Each servlet instance is loaded once.
• Each execution happens in a separate thread
• Three methods:
• init() : call only once to initialize servlet.
• service() : Call for every request.
• destroy() : call only once
• Method service() is invoked every time a request comes it. It spawns
off threads to perform doGet or doPost based on the method invoked.
Welcome To VCLIENT WORLD
Servlet life cycle 289
Interfaces Description
Servlet Declare life cycle methods for servlet. To implement
this interface we have to extends GenericServlet or
HttpServlet classes.
Classes Description
GenericServlet Used to create servlet (Protocol independent)
Classes Description
HttpServlet Used to create http servlet (Protocol
dependent)
HttpServletRequest It enables servlets to read data from
an HTTP request
HttpServletResponse It enables servlets to write data to an
HTTP response
HttpSession It allows to read and write session
data.
•<context-param>
• <param-name>dname</param-name>
• <param-value> sun.jdbc.odbc.JdbcOdbcDriver</param-value>
• </context-param>
•
Config Context
One object per servlet Object is global to entire web application
Object is created when servlet class is Object is created when web application
loaded deployed
It destroy when servlet is destroyed or It will destroyed when web application is
upload the class. un-deployed or removed.
• Also we can use same (following) code if request parameters is send through body part
of the Http request.
• If the browser sends an HTTP GET request, the parameters are included in the query
string in the URL.
• If the browser sends an HTTP POST request, the parameters are included in the body
part of the HTTP request.h body part of the Http request.
Welcome To VCLIENT WORLD
HttpRequest: Header 312
• The request headers are name, value pairs sent by the browser along
with the HTTP request.
• The request headers contain information about e.g. what browser
software is being used, what file types the browser is capable of
receiving etc. In short, at lot of meta data around the HTTP request