Professional Documents
Culture Documents
Prepared by:
Mr Gizatie D.
DTU
Modified in January, 2015
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 1
For 2nd Year Regular CS & 3rd Year Extension Cs students
Learning outcomes
At the end of the course students will be able to:-
A. Define GUI in java K, L1
B. create a program of GUI and other K,L5
C. Differentiate AWT and SWING .A,L2
D. Design advance programming S,l3
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 2
For 2nd Year Regular CS & 3rd Year Extension Cs students
UNIT ONE:
AWT And SWING
Unit description
This unit deals with AWT &SWING components with in event handling ,sources and lisneres. To address these
contents Brainstorming, peer & group discussion and gap lecture will be used more. Question & answer, group works
are among the methods to be used.
I. Objectives: At the end of this unit, students will be able to:
Define AWT&SWING L1(K)
Compare AWT&SWING L5(K)
Differentiate the components of awt and swing L3 (A )
II. Contents:
Definition of AWT& SWING
Components of the AWT & SWING
Event handling, sources and listeners
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 4
For 2nd Year Regular CS & 3rd Year Extension Cs students
1.2.1 Menus
Menu
Menu Bar – JMenu( String )
– JMenuBar() – add( JMenuItem )
– add( JMenu
JMenuBar mb = new JMenuBar(); //create a menu bar
JMenu fileMenu = new JMenu (“ File” ); //create a menu
mb.add( fileMenu ); //add menu to menu bar
setMenuBar( mb ); // add a menu bar to frame
fileMenu.setMnemonic( KeyEvent.VK_F ); // add a hotkey to menu
JMenuItem miOpen = new JMenuItem( “ Open...” , KeyEvent.VK_O );
JMenuItem miExit = new JMenuItem( “ Exit” );
fileMenu.add( miOpen ); // add a menu item
fileMenu.addSeparator(); // add a menu separator
fileMenu.add( miExit );
1.2.2 Frame
Frame is a window that is not contained inside another window. Frame is the basis to
contain other user interface components in Java GUI applications.
The JFrame class can be used to create windows.
For Swing GUI programs, use JFrame class to create widows.
1.2.3 Labels
This class is a Component which displays a single line of text.
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 5
For 2nd Year Regular CS & 3rd Year Extension Cs students
Labels are read-only. That is, the user cannot click on a label to edit the text it
displays.
Text can be aligned within the label
To create Label :-
Label la=new Label(“ Enter password);
La.setAlinment(Label.Right);
Panel.add(la);
1.2.4 Buttons
This class represents a push-button which displays some specified text.
When a button is pressed, it notifies its Listeners. (More about Listeners in the
next chapter).
To be a Listener for a button, an object must implement the ActionListener
Interface.
Panel aPanel = new Panel();
Button okButton = new Button("Ok");
Button cancelButton = new Button("Cancel");
aPanel.add(okButton));
aPanel.add(cancelButton));
okButton.addActionListener(controller2);
cancelButton.addActionListener(controller1);
1.2.5 TextField
This class displays a single line of optionally editable text.
This class inherits several methods from TextComponent.
This is one of the most commonly used Components in the AWT
TextField emailTextField = new TextField();
TextField passwordTextField = new TextField();
passwordTextField.setEchoChar("*");
String userEmail = emailTextField.getText();
String userpassword = passwordTextField.getText();
1.2.6 Checkbox
This class represents a GUI checkbox with a textual label.
The Checkbox maintains a boolean state indicating whether it is checked or not.
If a Checkbox is added to a CheckBoxGroup, it will behave like a radio button.
Checkbox creamCheckbox = new CheckBox("Cream");
Checkbox sugarCheckbox = new CheckBox("Sugar");
if (creamCheckbox.getState())
{
coffee.addCream();
}
JLabel
Labels
Provide text instructions on a GUI
Read-only text
Programs rarely change a label's contents
Class JLabel (subclass of JComponent)
Methods
Can declare label text in constructor
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 6
For 2nd Year Regular CS & 3rd Year Extension Cs students
myLabel.setToolTipText( "Text" )
• Displays "Text" in a tool tip when mouse over label
myLabel.setText( "Text" )
myLabel.getText()
JFrame Class
ja v a x .s w in g .J F ra m e
+ JF ra m e() C r e a t e s a d e f a u lt f r a m e w i t h n o ti t le .
+ J F r a m e ( t i t le : S t r i n g ) C r e a t e s a f r a m e w i th th e s p e c i f i e d t it le .
+ s e t S i z e ( w i d t h : i n t , h e i g h t : in t ) : v o i d S p e c i f i e s th e s i z e o f t h e f r a m e .
+ s e t L o c a t i o n ( x : in t, y : i n t ) : v o i d S p e c i f i e s th e u p p e r - le f t c o r n e r lo c a t i o n o f th e f r a m e .
+ s e t V i s ib le ( v i s i b le : b o o l e a n ) : v o i d S e t s t r u e t o d is p la y t h e f r a m e .
+ s e t D e f a u lt C lo s e O p e r a t i o n ( m o d e : in t) : v o i d S p e c i f i e s th e o p e r a ti o n w h e n t h e f r a m e i s c lo s e d .
+ s e t L o c a t i o n R e la t i v e T o ( c : C o m p o n e n t ) : S e t s t h e lo c a t i o n o f th e f r a m e r e la t i v e t o th e s p e c i f i e d c o m p o n e n t .
v o id I f t h e c o m p o n e n t i s n u ll, th e f r a m e i s c e n t e r e d o n t h e s c r e e n .
+ p a c k (): v o id A u t o m a t ic a lly s e t s t h e f r a m e s i z e t o h o ld t h e c o m p o n e n t s i n th e
fra m e.
JCheckBox
• When JCheckBox changes
– ItemEvent generated
• Handled by an ItemListener, which must define
itemStateChanged
– Register handlers with with addItemListener
• Class ItemEvent
– getStateChange
• Returns ItemEvent.SELECTED or ItemEvent.DESELECTED
JRadioButton
• Radio buttons
– Have two states: selected and deselected
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 7
For 2nd Year Regular CS & 3rd Year Extension Cs students
JTextField
A text field is an input area where the user can type in characters. Text fields
are useful in that they enable the user to enter in variable data (such as a
name or a description).
The get and set m ethods for these data fields are provided in
the class, but om itted in the UM L diagram for brevity.
javax.sw ing.text.JTextC om ponent
-text: String The text contained in this text com ponent.
-editable: boolean Indicates whether this text com ponent is editable (default: true).
Reading assignment
Please read the all about components of SWING its properties and methods?
SwingorAWT?That’ stheQuestion.
• Why JButton, not Button?
Initially, the GUI classes were bundled in a library known as the Abstract
WindowsToolkit (AWT).
AWT components are mapped to platform-specific components.
AWT, however, is not good for developing comprehensive GUIs, and is
prone to platform-specific bugs.
In Java 2, the AWT components were replaced with Swing.
Swing is more flexible and robust.
Swing components are directly painted on canvases using Java code.
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 8
For 2nd Year Regular CS & 3rd Year Extension Cs students
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 9
For 2nd Year Regular CS & 3rd Year Extension Cs students
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 10
For 2nd Year Regular CS & 3rd Year Extension Cs students
txuser.requestFocus();
}
}
});
}
UNIT TWO
Streams and File I/O
Unit description:
In this unit Streams, various stream classes and object streams, File management
contents to be covered. To deliver these contents brain storming and interactive lecture,
Peer teaching, group discussion, presentation and class work methods are used. And the
way of assessment will takes place in the form of questioning and answer, group work,
peer assessment.
2.1 Introduction:
Brian storming: what is the term stream, various stream classes and object streams?
Gap lecture:
Stream, various stream classes and File management:
Stream: an object that either delivers data to its destination (screen, file, etc.) or that
takes data from a source (keyboard, file, etc.)
– it acts as a buffer between the data source and destination
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 11
For 2nd Year Regular CS & 3rd Year Extension Cs students
Streams in JAVA are Objects, of course ! Having - 2 types of streams (text / binary) and
-2 directions (input / output)
results in 4 base-classes dealing with I/O:
1. Reader: text-input
2. Writer: text-output
3. InputStream: byte-input
4. OutputStream: byte-output
Input stream: a stream that provides input to a program-System.in is an input stream
Output stream: a stream that accepts output from a program-System.out is an output stream
A stream connects a program to an I/O object
– System.out connects a program to the screen
– System.in connects a program to the keyboard
I/O: General Scheme
In JAVA:
– Create a stream object and associate it with a disk-file
– Give the stream object the desired functionality
– while there is more information
read(write) next data from(to) the stream
– close the stream.
Binary Versus Text Files
All data and programs are ultimately just zeros and ones
– each digit can have one of two values, hence binary
– bit is one binary digit
– byte is a group of eight bits
Text files: the bits represent printable characters
– one byte per character for ASCII, the most common code
– for example, Java source files are text files
– so is any file created with a "text editor"
Binary files: the bits represent other types of encoded information, such as executable
instructions or numeric data
these files are easily read by the computer but not humans
they are not "printable" files
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 12
For 2nd Year Regular CS & 3rd Year Extension Cs students
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 13
For 2nd Year Regular CS & 3rd Year Extension Cs students
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 14
For 2nd Year Regular CS & 3rd Year Extension Cs students
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 15
For 2nd Year Regular CS & 3rd Year Extension Cs students
UNIT THREE
Multithreading Concept
Unit description
In this unit Multithreading concept, process, thread priorities& schedules, thread synchronization and un
synchronized .To deliver these contents brain Storming and gap lecture, group discussion, demonstration
methods will be used. And the way of assessment will takes place in the form of questioning and answer,
group work, individual assignment, lab assignment, test.
I. Objectives: At the end of this, unit students will be able to:
Define Multithreading
Differentiate multithreading and process
Differentiate thread priorities& schedules
Differentiate thread synchronization and un synchronized.
II. Contents:
Multithreading
Multithreading and process
Thread priorities& schedules
Thread synchronization and un synchronized.
III. Method of Teaching : brain storming , gap lecture, group discussion
3.1 Introduction:
Brian storming: what is multithreading?
Mini lecture:
The human body performs a great variety of operations in parallel—or concurrently.
Computers, too, can perform operations concurrently Only computers that have multiple processors can
truly execute multiple instructions concurrently .
Operating systems on single-processor computers create the illusion of concurrent execution by rapidly
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 16
Course Module of Advanced Java Programming
switching between activities, but on such computers only a single instruction can execute at once Java
makes concurrency available to you through the language and APIs.
A multithreaded application contains separate threads of execution, where each thread Has its own
method-call stack and program counter execute concurrently with other threads.
shares application-wide resources such as memory with other threads.
In single-threaded applications lengthy activities must complete before others can begin which leads to
poor responsiveness.
In a multithreaded application, threads can be distributed across multiple processors (if available) so that
multiple tasks execute concurrently and the application can operate more efficiently.
Multithreading can also increase performance on single-processor systems that simulate
concurrency—when one thread cannot proceed (because, for example, it is waiting for the result of an I/O
operation), another can use the processor.
An application of concurrent programming
o Start playback of an audio clip or a video clip while the clip downloads
o synchronize (coordinate the actions of) the threads so that the player thread doesn’ t begin until
there is a sufficient amount of the clip in memory to keep the player thread busy
The Java Virtual Machine (JVM) creates threads to run a program, the JVM also may create threads for
performing housekeeping tasks such as garbage collection
Programming concurrent applications is difficult and error-prone. Follow some simple guidelines
o Use existing classes from the Java API such as the ArrayBlockingQueue class that manage
synchronization for you.
o If you find that you need more custom functionality than that provided in the Java APIs, you should
use the synchronized keyword and Object methods wait, notify and notifyAll
o If you need even more complex capabilities, then you should use the Lock and Condition interfaces
A program has one or more locus of execution. Each execution is called a thread of execution. The set of
threads comprise a process.
Threads of execution
Each thread is a portion of a program that can execute concurrently with other threads (multithreading)
C and C++ are single-threaded
Gives Java powerful capabilities not found in C and C++
3.2 Thread States: Life Cycle of a Thread
A thread occupies one of several thread states (Fig. 1)
A new thread begins its life cycle in the new state.
When the program starts the thread it enters the runnable state. :-considered to be executing its task
Runnable thread transitions to the waiting state while it waits for another thread to perform a task
– transitions back to the runnable state only when another thread notifies the waiting thread to
continue executing
A runnable thread can enter the timed waiting state for a specified interval of time
– transitions back to the runnable state when that time interval expires or when the event it is
waiting for occurs.
Such browsers can display data before entire document is downloaded: performs multiple simultaneous
tasks
Fetch main HTML page, activate separate threads for other parts
Each thread sets up a separate connection with the server -Uses blocking calls
Each part (gif image) fetched separately and in parallel
Advantage: connections can be setup to different sources-Ad server, image server
Multi-threaded Server Example
Apache web server: pool of pre-spawned worker threads
Dispatcher thread waits for requests
For each request, choose an idle worker thread
Worker thread uses blocking system calls to service web request
Monitor ensures that its object’ s monitor lock is held by a maximum of only one thread at any time Can be
used to enforce mutual exclusion
To enforce mutual exclusion
Thread must acquire the lock before it can proceed with its operation
other threads attempting to perform an operation that requires the same lock will be blocked until the first
thread releases the lock
synchronized statement
Enforces mutual exclusion on a block of code
synchronized ( object )
{
statements
} // end synchronized statement
where object is the object whose monitor lock will be acquired (normally this)
A synchronized method is equivalent to a synchronized statement that encloses the entire body of a
method
Another thread can call Condition method signal to allow a thread in that Condition’ s waiting state to
return to the runnable state
– Default implementation of Condition signals the longest-waiting thread
Condition method signalAll transitions all the threads waiting for that condition to the runnable state
When finished with a shared object, thread must call unlock to release the Lock
Lock and Condition may be preferable to using the synchronized keyword
– Lock objects allow you to interrupt waiting threads or to specify a timeout for waiting to acquire
a lock
– Lock object is not constrained to be acquired and released in the same block of code
Condition objects can be used to specify multiple conditions on which threads may wait
– Possible to indicate to waiting threads that a specific condition object is now true
3.11 Deadlock
Deadlock occurs when a waiting thread (let us call this thread1) cannot proceed because it is waiting
(either directly or indirectly) for another thread (let us call this thread2) to proceed, while simultaneously
thread2 cannot proceed because it is waiting (either directly or indirectly) for thread1 to proceed. The
two threads are waiting for each other, so the actions that would enable each thread to continue
execution can never occur.
IV. Assessments:
1. The keyword -------------indicates that only one thread at a time should execute on an object.
1. Synchronization
2. Create new child of thread.
// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
UNIT FOUR
Networking in Java
Unit description
In these unit Networking in java, connecting to server, connection client with server, sockets, ports and
URLs be covers, To deliver these contents brain storming and presentation, group discussion, demonstration
methods will be used. And the way of assessment will takes place in the form of questioning and answer,
group work, individual assignment, lab assignment, test
I. Objectives: At the end of this unit, students will be able to:
4.1 Introduction:
Brian storming: what is Networking?
Interactive lecture:
Java provides:-Stream-based communications
a process establishes a connection to another process. While the connection is in place, data
flows between the processes
Connection-based protocol - Uses TCP
Packet-based communications
Individual packets transmitted
Connectionless service - Uses UDP (User Datagram Protocol)
Client-server relationship
Client requests some action be performed
Server performs the action and responds to client
Request-response model
Common implementation: Web browsers and Web servers
4.2 Manipulating URLs
The HTTP protocol uses URIs to locate data on the Internet.
A URI that represents a document is called a URL
• URL Refer to files, directories and complex objects
Applet method getAppletContext returns a reference to an AppletContext object that represents the
browser in which the applet is executing.
AppletContext method showDocument receives a URL as an argument and passes it to the
AppletContext (i.e., the browser), which displays the web resource associated with that URL.
param tag specifies parameters in HTML document.
Each parameter has a name and a value and the applet can read these values and use them to customize
itself.
. 4.3 Reading a File on a Web Server
Swing GUI component JEditorPane Retrieves files from a Web server at a given URI
JEditorPane method setPage downloads the document specified by its argument and displays it in the
JEditorPane.
If an HTML document is displayed in a JEditorPane and the user clicks a hyperlink, the JEditorPane
generates a HyperlinkEvent and notifies all registered HyperlinkListeners of the event.
Three event types
HyperlinkEvent.EventType.ACTIVATED
HyperlinkEvent.EventType.ENTERED
HyperlinkEvent.EventType.EXITED
4.4 Establishing a Simple Server Using Stream Sockets
Five steps to create a simple server in Java
Step 1: Create ServerSocket object
– ServerSocket server = new ServerSocket( portNumber, queueLength );
– Register an available port
– Specify a maximum number of clients
– Handshake point
– Binding the server to the port
• Only one client can be bound to a specific port
Step 2: Server listens for client connection
– Server blocks until client connects
– Socket connection = server.accept();
Step 3: Sending and receiving data
– OutputStream to send and InputStream to receive data
• Method getOutputStream returns Socket’ s OutputStream
• Methods getInputstream returns Socket’ s InputStream
Step 4: Process phase
– Server and Client communicate via streams
Step 5: Close streams and connections
– Method close
• Port numbers can be between 0 and 65,535. Most operating systems reserve port numbers below 1024
for system services.
4.5 Establishing a Simple Client Using Stream Sockets
• Four steps to create a simple client in Java
– Step 1: Create a Socket to connect to server
Socket connection = new Socket ( serverAddress, port );
– Step 2: Obtain Socket’ s InputStream and Outputstream
– Step 3: Process information communicated
– Step 4: Close streams and connection
4.6 Client/Server Interaction with Stream Socket Connections
Client/server chat application
– Uses stream sockets
– Server waits for a client connection attempt
– Client connects to the server
• Send and receive messages
– Client or server terminates the connection
– Server waits for the next client to connect
Software Engineering Observation 24.5
When using an ObjectOutputStream and ObjectInputStream to send and receive data over a network
connection, always create the ObjectOutputStream first and flush the stream so that the client’ s
ObjectInputStream can prepare to receive the data. This is required only for networking applications that
communicate using ObjectOutputStream and ObjectInputStream.
4.7 Connectionless Client/Server Interaction with Datagrams
• Connectionless transmission with datagrams
– No connection maintained with other computer
– Break message into separate pieces and send as packets
– Message arrive in order, out of order or not at all
– Receiver puts messages in order and reads them
Presentation:
Read more on this chapter and present in the class
IV. Assessments:
outC2.flush();
}
outC2.close();
inC1.close();
s2.close();
s1.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
}
UNIT FIVE
Remote Method Invocation (RMI)
Unit description
In this unit RMI, RMI Registry, Remote Interface and Implementing of RMI are contents to be covers, to
deliver these contents brain storming and gap lecture, group discussion, demonstration methods will be used.
And the way of assessment will takes place in the form of questioning and answer, group work, individual
assignment, lab assignment, test
I. Objectives: At the end of this unit students will be able to:
Explain RMI?
list the RMI Registry
Write the program of Remote Interface and Implementation of RMI?
I. Contents:
RMI
types of RMI Registry
RMI Implementation and Remote Interface
I. Method of Teaching : brain storming , gap lecture, group discussion, and Presentation
Brian storming: what is RMI?
5.1 Introduction:
Remote Method Invocation (RMI) is a Java mechanism similar to RPCs.
RMI allows a Java program on one machine to invoke a method on a remote object.
Marshalling of data
Marshalling Parameters
• If the marshaled parameters are local (non remote) objects, they are passed by copy
using a technique known as object serialization.
– Object serialization allowed the state of an object to be written to a byte stream.
import java.util.Vector;
UNIT SIX
Accessing Databases with JDBC
Unit description
In this unit Database system and SQL, Basic concepts of JDBC programming ,Installing and setting of JDBC,
Executing of database queries and RowsetInterface contents to be covers, to deliver these contents brain
storming and gap lecture, group discussion, demonstration methods will be used. And the way of assessment
will takes place in the form of questioning and answer, group work, individual assignment, lab assignment, test
II. Objectives: At the end of this unit students will be able to:
Explain Database system and SQL?
Explain the basic concepts of JDBC programming?
To use Prepared Statements to create precompiled SQL statements with parameters.
Display the database queries?
To use the RowSet interface from package javax.sql to manipulate databases.
I. Contents:
Database system and SQL
Manipulating of database with JDBC
Basic concepts of JDBC Programming
Database queries
Row Set Interface
I. Method of Teaching : brain storming , gap lecture, group discussion, and Presentation
Brian storming: what is Database system?
6.1 Introduction:
A database is an organized collection of data. There are many different strategies for organizing data to facilitate
easy access and manipulation. A database management system (DBMS) provides mechanisms for storing,
organizing, retrieving and modifying data for many users. Database management systems allow for the access
and storage of data without concern for the internal representation of data.
Today’ s most popular database systems are relational databases, where the data is stored without consideration
of its physical structure. A language called SQL—pronounced “ sequel,” or as its individual letters—is the
international standard language used almost universally with relational databases to perform queries (i.e., to
request information that satisfies given criteria) and to manipulate data.
Information stored in the database is in tables and the language used to query information from the database is
SQL .Using SQL we can query a table based on the requirement.
CRUD OPERATIONS
• CRUD stands for create, read, update, delete.
• Create statement in SQL looks like
– Create table mytab ( mynum number , name varchar2(25));
– READ statement looks like :-Select * from mytab where mynum=25;
– UPDATE statement looks as :-Update mytab set mynum=88 where mynum=25;
– DELETE statement like:-Delete from mytab where mynum=88;
Programs connect to, and interact with, relational databases via an interface—software that facilitates
communications between a database management system and a program.
Java programs communicate with databases and manipulate their data using the JDBC API.
A JDBC driver enables Java applications to connect to a database in a particular DBMS and allows you to
retrieve and manipulate database data.
Package java.sql contains classes and interfaces for accessing relational databases in Java.
Using the JDBC API enables developers to change the underlying DBMS without modifying the Java code
that accesses the database.
The result type specifies whether the ResultSet’ s cursor is able to scroll in both directions or forward only
and whether the ResultSet is sensitive to changes.
The result concurrency specifies whether the ResultSet can be updated with Result-Set’ s update methods.
Notes
Most major database vendors provide their own JDBC database drivers, and many third-party vendors
provide JDBC drivers as well.
Initially, a ResultSet cursor is positioned before the first row. Attempting to access a ResultSet’ s contents
before positioning the ResultSet cursor to the first row with method next causes a SQLException.
Specifying column number 0 when obtaining values from a ResultSet causes a SQLException.
Each Statement object can open only one ResultSet object at a time. When a Statement returns a new
ResultSet, the Statement closes the prior ResultSet. To use multiple ResultSets in parallel, separate
Statement objects must return the ResultSets.
ORACLE jdbc:oracle:thin:@hostname:portNumber:databaseName
DB2 jdbc:db2:hostname:portNumber/databaseName
Sybase jdbc:sybase:Tds:hostname:portNumber/databaseName
getColumnClassName obtains the fully qualified class name of the specified column.
getColumnName obtains the column name from the ResultSet.
ResultSet method
absolute positions the ResultSet cursor at a specific row.
AbstractTableModel method
fireTableStructureChanged notifies any JTable using a particular TableModel object as its model that
the data in the model has changed.
Some JDBC drivers do not support scrollable ResultSets. In such cases, the driver typically returns a
ResultSet in which the cursor can move only forward.
ResultSet static
type constant Description
TYPE_FORWARD_ONLY Specifies that a ResultSet’s cursor can move only in the forward
direction (i.e., from the first row to the last row in the ResultSet).
TYPE_SCROLL_INSENSITIVE Specifies that a ResultSet’s cursor can scroll in either direction
and that the changes made to the ResultSet during ResultSet
processing are not reflected in the ResultSet unless the program
queries the database again.
TYPE_SCROLL_SENSITIVE Specifies that a ResultSet’s cursor can scroll in either direction
and that the changes made to the ResultSet during ResultSet
processing are reflected immediately in the ResultSet.
Disconnected RowSet :-Connects to database, executes a query and then closes connection
Package javax.sql.rowset
JdbcRowSet
• Connected RowSet
• Wrapper around a ResultSet
• Scrollable and updatable by default
CachedRowSet
• Disconnected RowSet
• Cache the data of ResultSet in memory
• Scrollable and updatable by default
• Serializable :-Can be passed between Java application
• Limitation:-Amount of data that can be stored in memory is limited
A RowSet can provide scrolling capability for drivers that do not support scrollable ResultSets.
6.5 PreparedStatements
Program must specify the parameter values by using the PreparedStatement interface’ s set methods.
For the preceding query, both parameters are strings that can be set with PreparedStatement method
setString as follows:
PreparedStatement pstmt = con.preparestatement(select * from mytab where num=?” );pstmt.setInt(1,” 11” );
PreparedStatement authorBooks = connection.prepareStatement("SELECT lastName, firstName, title " +
"FROM authors INNER JOIN authorISBN " +
"ON authors.authorID=authorISBN.authorID " +
"INNER JOIN titles " +
"ON authorISBN.isbn=titles.isbn " +
"WHERE lastName = ? AND firstName = ?" );
setString automatically escapes String parameter values as necessary (e.g., the quote in the name O’ Brien)
More info at java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html
PreparedStatements are more efficient than Statements when executing SQL statements multiple times and
with different parameter values.
6.6 Stored Procedures
Stored procedures
– Store SQL statements in a database
– Invoke SQL statements by programs accessing the database
JDBC enables programs to invoke stored procedures using objects that implement interface
CallableStatement.
CallableStatement can specify input parameters, like PreparedStatement.
In addition, CallableStatement can specify output parameters in which a stored procedure can place
return values.
The interface CallableStatement provides a uniform interface for specifying input and output parameters
for stored procedures and for invoking stored procedures in different databases.
6.7 Transaction Processing
Many applications require guarantees that a series of database insertions, updates and deletions executes
properly before the applications continue processing the next database operation
Enables a program that interacts with a database to treat a database operation (or set of operations) as a
single operation
– Known as an atomic operation or a transaction
– At the end of a transaction, decide to commit or roll back
Committing a transaction finalizes the database operation(s); all insertions, updates and deletions
performed as part of the transaction cannot be reversed without performing a new database operation
Rolling back a transaction leaves the database in its state prior to the database operation
Group discussion:
Discuses on SQL statements by giving different sql commands .
III. Assessments:
1. Create apreapared statement that create table
//using prepared statements
import java.sql.*;
import java.util.Scanner;
class CreatgTable{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String title, no;
int credit;
byte addMoreRecord = 1;
try{
Connection con = DriverManager.getConnection(
"jdbc:odbc:student");
Statement stmt = con.createStatement();
String str = "CREATE TABLE t2(Title VARCHAR(30),"
+ "No VARCHAR(12)primary key, Credit int)";
int i = stmt.executeUpdate(str);
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO t2 (Title, No, Credit)"
+ " VALUES (?, ?, ?)");
do{
System.out.println("Enter course title");
title = sc.nextLine();
System.out.println("Enter course no");
no = sc.nextLine();
System.out.println("Enter credit hour");
credit = sc.nextInt();
pstmt.setString(1, title);
pstmt.setString(2, no);
pstmt.setInt(3, credit);
pstmt.executeUpdate();
System.out.println("Enter 0 to stop,"
+ " 1 to add more record");
addMoreRecord = sc.nextByte();
sc.nextLine();
}while(addMoreRecord !=0);
}
catch(Exception e){System.out.println(e.getClass());}
}
}
Unit Seven
Introduction To Servlets
Unit description
In this unit the Overview of servlets , HTTP requests and application of servlets contents to be covers, to deliver
these contents brain storming and gap lecture, group discussion, demonstration methods will be used. And the
way of assessment will takes place in the form of questioning and answer, group work, individual assignment,
lab assignment, test
II. Objectives: At the end of this unit students will be able to:
Define Servlets?
Explain the Basic HTTP requests?
Explain Application of Servlets?
III. Contents:
Introduction To Servlets
HTTP requests
Application of servlet
I. Method of Teaching : brain storming , gap lecture, group discussion, and Presentation
7.1 Introduction
Brian storming: what is Servlet?
Servlets
– Analog to applets:-Execute on server's machine, supported by most web servers
– Demonstrate communication via HTTP protocol
• Client sends HTTP request
• Server receives request, servlets process it
• Results returned (HTML document, images, binary data)
The Servlet API
– Implemented by all servlets
– Many methods invoked automatically by server
• Similar to applets (paint, init, start, etc.)
– abstract classes that implement Servlet
• GenericServlet (javax.servlet)
• HTTPServlet (javax.servlet.http)
– Examples in chapter extend HTTPServlet
• Methods
– void init( ServletConfig config )
• Automatically called, argument provided
• Methods
– ServletConfig getServletConfig()
• Returns reference to object, gives access to config info
– void service ( ServletRequest request, ServletResponse response )
• Key method in all servlets
• Provide access to input and output streams
– Read from and send to client
– void destroy()
• Cleanup method, called when servlet exiting
HttpServlet Class
• HttpServlet
– Base class for web-based servlets
– Overrides method service
• Request methods:
– GET - retrieve HTML documents or image
– POST - send server data from HTML form
– Methods doGet and doPost respond to GET and POST
• Called by service
• Receive HttpServletRequest and HttpServletResponse (return void) objects
HttpServletRequest Interface
• HttpServletRequest interface
– Object passed to doGet and doPost
– Extends ServletRequest
• Methods
– String getParameter( String name )
• Returns value of parameter name (part of GET or POST)
– Enumeration getParameterNames()
• Returns names of parameters (POST)
– String[] getParameterValues( String name )
• Returns array of strings containing values of a parameter
– Cookie[] getCookies()
• Returns array of Cookie objects, can be used to identify client
HttpServletResponse Interface
• HttpServletResponse
– Object passed to doGet and doPost
– Extends ServletResponse
• Methods
– void addCookie( Cookie cookie )
• Add Cookie to header of response to client
– ServletOutputStream getOutputStream()
• Gets byte-based output stream, send binary data to client
– PrintWriter getWriter()
• Gets character-based output stream, send text to client
– void setContentType( String type )
• Specify MIME type of the response (Multipurpose Internet Mail Extensions)
• MIME type “ text/html” indicates that response is HTML document.
• Helps display data
7.3 Handling HTTP GET Requests
• HTTP GET requests
– Usually gets content of specified URL
• Usually HTML document (web page)
• Example servlet
– Handles HTTP GET requests
– User clicks Get Page button in HTML document
• GET request sent to servlet HTTPGetServlet
– Servlet dynamically creates HTML document displaying "Welcome to Servlets!"
• Running servlets
– Must be running on a server
• Check documentation for how to install servlets
• Tomcat web server
• Apache Tomcat
• Port number
– Where server waits for client (handshake point)
– Client must specify proper port number
• Integers 1 - 65535, 1024 and below usually reserved
– Well-known port numbers
• Web servers - port 80 default
• JSDK/Apache Tomcat 4.0 Webserver- port 8080
• Change in default.cfg (server.port=8080)
Handling HTTP get Requests Containing Data
Responds to a get request that contains data
7.4 Handling HTTP POST Requests
HTTP POST
– Used to post data to server-side form handler (i.e. surveys)
– Both GET and POST can supply parameters
Example servlet
– Survey
Assessment
1. Write a servlet program that contains the methods of Handling HTTP get and post
requests ?
Assessment methods
The assessment methods are listed below by considering both domains of education and hierarch of
learning.
Formative Assessments:
Attendance & class activity .…............. 5 %
Quiz………………………….………....5 %
Group assignment (Lab.)......……...........5 %
Individual assignment …………….........5%
Test………...…………………….......... 30%
Project………...……………………....... 20%
Sub Total…………………..................... 70 %
Summative Assessment:
Final Exam …… ………………...........30 %