7MCE1C3-Advanced Java Programming
7MCE1C3-Advanced Java Programming
Applications of JDBC
• Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows
for portable access to an underlying database. Java can be used to write different types of
executables, such as,
▪ Java Applications
▪ Java Applets
▪ Java Servlets
▪ Java ServerPages (JSPs)
▪ Enterprise JavaBeans (EJBs).
• All of these different executables are able to use a JDBC driver to access a database, and
take advantage of the stored data.
• JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
• The java.sql and javax.sql are the primary packages for JDBC 4.0.
• It offers the main classes for interacting with your data sources.
• The new features in these packages include changes in the following are as,
▪ Automatic database driver loading.
▪ Exception handling improvements.
▪ Enhanced BLOB/CLOB functionality.
1
Advanced Java Programming Unit - I JDBC
JDBC Architecture
• The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −
▪ JDBC API: This provides the application-to-JDBC Manager connection.
▪ JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
• The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
• The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
• Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application
JDBC Components
2
Advanced Java Programming Unit - I JDBC
• Connection: This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is through
connection object only.
• Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.
• ResultSet: These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its data.
• SQLException: This class handles any errors that occur in a database application.
JDBC Driver
• JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
• For example, using JDBC drivers enable you to open database connections and to interact
with it by sending SQL or database commands then receiving results with Java.
• The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementaions are done in third-party drivers. Third party
vendors implement the java.sql.Driver interface in their database driver.
• JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates.
• Sun has divided the implementation types into four categories:
▪ Type 1: JDBC-ODBC Bridge Driver
▪ Type 2: JDBC-Native API
▪ Type 3: JDBC-Net pure Java
▪ Type 4: 100% Pure Java
• In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine.
• Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.
3
Advanced Java Programming Unit - I JDBC
• When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or
when no other alternative is available.
• The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
• In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database.
• These drivers are typically provided by the database vendors and used in the same manner
as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client
machine.
• If we change the Database, we have to change the native API, as it is specific to a database
and they are mostly obsolete now, but you may realize some speed increase with a Type 2
driver, because it eliminates ODBC's overhead.
• In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server.
4
Advanced Java Programming Unit - I JDBC
• The socket information is then translated by the middleware application server into the call
format required by the DBMS, and forwarded to the database server.
• This kind of driver is extremely flexible, since it requires no code installed on the client and
a single driver can actually provide access to multiple databases.
• You can think of the application server as a JDBC "proxy," meaning that it makes calls for
the client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.
• Your application server might use a Type 1, 2, or 4 driver to communicate with the
database, understanding the nuances will prove helpful.
• In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's
database through socket connection. This is the highest performance driver available for
the database and is usually provided by the vendor itself.
• This kind of driver is extremely flexible, you don't need to install special software on the
client or server. Further, these drivers can be downloaded dynamically.
• MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
5
Advanced Java Programming Unit - I JDBC
• Extract data from result set: Requires that you use the
appropriate ResultSet.getXXX() method to retrieve the data from the result set.
• Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
• The Import statements tell the Java compiler where to find the classes you reference in
your code and are placed at the very beginning of your source code.
• To use the standard JDBC package, which allows you to select, insert, update, and delete
data in SQL tables, add the following imports to your source code
import java.sql.* ; // for standard JDBC programs
import java.math.* ; // for BigDecimal and BigInteger support
• You must register the driver in your program before you use it. Registering the driver is the
process by which the Oracle driver's class file is loaded into the memory, so it can be
utilized as an implementation of the JDBC interfaces.
• You need to do this registration only once in your program. You can register a driver in one
of two ways.
1. Approach I - Class.forName()
• The most common approach to register a driver is to use Java's Class.forName() method,
to dynamically load the driver's class file into memory, which automatically registers it.
This method is preferable because it allows you to make the driver registration
configurable and portable.
• The following example uses Class.forName( ) to register the Oracle driver −
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
6
Advanced Java Programming Unit - I JDBC
• You can use getInstance() method to work around noncompliant JVMs, but then you'll
have to code for two extra Exceptions as follows −
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}
2. Approach II - DriverManager.registerDriver()
• The second approach you can use to register a driver, is to use the
static DriverManager.registerDriver() method.
• You should use the registerDriver() method if you are using a non-JDK compliant JVM, such
as the one provided by Microsoft.
• The following example uses registerDriver() to register the Oracle driver
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
• The most commonly used form of getConnection() requires you to pass a database URL,
a username, and a password:
• Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value
for the database portion of the URL.
• If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle
listener is configured to listen on port 1521, and your database name is EMP, then complete
database URL would be:
jdbc:oracle:thin:@amrood:1521:EMP
• Now call getConnection() method with appropriate username and password to get
a Connection object as follows:
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
8
Advanced Java Programming Unit - I JDBC
• At the end of your JDBC program, it is required explicitly to close all the connections to the
database to end each database session. However, if you forget, Java's garbage collector will
close the connection when it cleans up stale objects.
• Relying on the garbage collection, especially in database programming, is a very poor
programming practice. You should make a habit of always closing the connection with the
close() method associated with connection object.
• To ensure that a connection is closed, you could provide a 'finally' block in your code.
A finally block always executes, regardless of an exception occurs or not.
• To close the above opened connection, you should call close() method as follows:
conn.close();
• Explicitly closing a connection conserves DBMS resources, which will make your database
administrator happy.
Metadata
• Generally, Data about data is known as metadata.
• JDBC has two types of Meta data:
▪ DatabaseMetaData
▪ ResultsetMetaData
DatabaseMetaData
• The DatabaseMetaData interface provides methods to get information about the database
you have connected with like, database name, database driver version, maximum column
length etc...
• Following are some methods of DatabaseMetaData class.
Method Description
getDriverName() Retrieves the name of the current JDBC driver
getDriverVersion() Retrieves the version of the current JDBC
9
Advanced Java Programming Unit - I JDBC
driver
getUserName() Retrieves the user name.
getDatabaseProductName() Retrieves the name of the current database.
getDatabaseProductVersion() Retrieves the version of the current database.
getNumericFunctions() Retrieves the list of the numeric functions
available with this database.
getStringFunctions() Retrieves the list of the numeric functions
available with this database.
getSystemFunctions() Retrieves the list of the system functions
available with this database.
getTimeDateFunctions() Retrieves the list of the time and date
functions available with this database.
getURL() Retrieves the URL for the current database.
supportsSavepoints() Verifies weather the current database
supports save points
supportsStoredProcedures() Verifies weather the current database
supports stored procedures.
supportsTransactions() Verifies weather the current database
supports transactions.
ResultsetMetaData
• The ResultSetMetaData provides information about the obtained ResultSet object like, the
number of columns, names of the columns, datatypes of the columns, name of the table etc…
• Following are some methods of ResultSetMetaData class.
Method Description
getColumnCount() Retrieves the number of columns in the current ResultSet object.
getColumnLabel() Retrieves the suggested name of the column for use.
getColumnName() Retrieves the name of the column.
getTableName() Retrieves the name of the table.
SQLException
• Exception handling allows you to handle exceptional conditions such as program-defined
errors in a controlled fashion.
• When an exception condition occurs, an exception is thrown. The term thrown means that
current program execution stops, and the control is redirected to the nearest applicable
catch clause. If no applicable catch clause exists, then the program's execution ends.
• JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the
most common exception you'll deal with is java.sql.SQLException.
SQLException Methods
• An SQLException can occur both in the driver and the database. When such an exception
occurs, an object of type SQLException will be passed to the catch clause.
• The passed SQLException object has the following methods available for retrieving
additional information about the exception:
Method Description
getErrorCode( ) Gets the error number associated with the
10
Advanced Java Programming Unit - I JDBC
exception.
getMessage( ) Gets the JDBC driver's error message for an
error, handled by the driver or gets the Oracle
error number and message for a database error.
getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC
driver error, no useful information is returned
from this method. For a database error, the five-
digit XOPEN SQLstate code is returned. This
method can return null.
getNextException( ) Gets the next Exception object in the exception
chain.
printStackTrace( ) Prints the current exception, or throwable, and
it's backtrace to a standard error stream.
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the
print stream you specify.
printStackTrace(PrintWriter w) Prints this throwable and it's backtrace to the
print writer you specify.
• By utilizing the information available from the Exception object, you can catch an exception
and continue your program appropriately. Here is the general form of a try block −
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
SQLWarning
11
Advanced Java Programming Unit - I JDBC
JDBC Statements
Statement Objects
Just as you close a Connection object to save database resources, for the same reason you should
also close the Statement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will
close the Statement object as well. However, you should always explicitly close the Statement
object to ensure proper cleanup.
Statement stmt = null;
try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
stmt.close();
}
The PreparedStatement interface extends the Statement interface, which gives you added
functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
13
Advanced Java Programming Unit - I JDBC
• All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object.
However, the methods are modified to use SQL statements that can input the parameters.
• Just as you close a Statement object, for the same reason you should also close the
PreparedStatement object.
• A simple call to the close() method will do the job. If you close the Connection object first, it
will close the PreparedStatement object as well. However, you should always explicitly
close the PreparedStatement object to ensure proper cleanup.
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
pstmt.close();
}
• Just as a Connection object creates the Statement and PreparedStatement objects, it also
creates the CallableStatement object, which would be used to execute a call to a database
stored procedure.
DELIMITER ;
• Three types of parameters exist: IN, OUT, and INOUT.
• The PreparedStatement object only uses the IN parameter.
• The CallableStatement object can use all the three. The following are the definitions:
Parameter Description
• The following code snippet shows how to employ the Connection.prepareCall() method
to instantiate a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
• The String variable SQL, represents the stored procedure, with parameter placeholders.
• Using the CallableStatement objects is much like using the PreparedStatement objects. You
must bind values to all the parameters before executing the statement, or you will receive
an SQLException.
• If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java data type
you are binding.
• When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The registerOutParameter() method
binds the JDBC data type, to the data type that the stored procedure is expected to return.
• Once you call your stored procedure, you retrieve the value from the OUT parameter with
the appropriate getXXX() method. This method casts the retrieved value of SQL type to a
Java data type.
15
Advanced Java Programming Unit - I JDBC
• Just as you close other Statement object, for the same reason you should also close the
CallableStatement object.
• A simple call to the close() method will do the job. If you close the Connection object first, it
will close the CallableStatement object as well. However, you should always explicitly close
the CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
cstmt.close();
}
JDBC Resutset
• The SQL statements that read data from a database query, return the data in a result set.
The SELECT statement is the standard way to select rows from a database and view them in
a result set. The java.sql.ResultSet interface represents the result set of a database query.
• A ResultSet object maintains a cursor that points to the current row in the result set. The
term "result set" refers to the row and column data contained in a ResultSet object.
• The methods of the ResultSet interface can be broken down into three categories −
▪ Navigational methods: Used to move the cursor around.
▪ Get methods: Used to view the data in the columns of the current row being
pointed by the cursor.
▪ Update methods: Used to update the data in the columns of the current row.
The updates can then be updated in the underlying database as well.
• The cursor is movable based on the properties of the ResultSet. These properties are
designated when the corresponding Statement that generates the ResultSet is created.
• JDBC provides the following connection methods to create statements with desired
ResultSet −
▪ createStatement(int RSType, int RSConcurrency);
▪ prepareStatement(String SQL, int RSType, int RSConcurrency);
▪ prepareCall(String sql, int RSType, int RSConcurrency);
• The first argument indicates the type of a ResultSet object and the second argument is one
of two ResultSet constants for specifying whether a result set is read-only or updatable.
Types of ResultSet
• The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.
16
Advanced Java Programming Unit - I JDBC
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and the result
set is not sensitive to changes made by others to the
database that occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and the result
set is sensitive to changes made by others to the database
that occur after the result set was created.
Concurrency of ResultSet
• The possible RSConcurrency are given below. If you do not specify any Concurrency type,
you will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.
• There are several methods in the ResultSet interface that involve moving the cursor,
including
S. No Methods & Description
public void beforeFirst() throws SQLException:
1
Moves the cursor just before the first row.
public void afterLast() throws SQLException
2
Moves the cursor just after the last row.
public boolean first() throws SQLException
3
Moves the cursor to the first row.
public void last() throws SQLException
4
Moves the cursor to the last row.
public boolean absolute(int row) throws SQLException
5
Moves the cursor to the specified row.
6 public boolean relative(int row) throws SQLException
17
Advanced Java Programming Unit - I JDBC
Moves the cursor the given number of rows forward or backward, from where it is
currently pointing.
public boolean previous() throws SQLException
7 Moves the cursor to the previous row. This method returns false if the previous
row is off the result set.
public boolean next() throws SQLException
8 Moves the cursor to the next row. This method returns false if there are no more
rows in the result set.
public int getRow() throws SQLException
9
Returns the row number that the cursor is pointing to.
public void moveToInsertRow() throws SQLException
10 Moves the cursor to a special row in the result set that can be used to insert a new
row into the database. The current cursor location is remembered.
public void moveToCurrentRow() throws SQLException
11 Moves the cursor back to the current row if the cursor is currently at the insert
row; otherwise, this method does nothing
• The ResultSet interface contains dozens of methods for getting the data of the current row.
• There is a get method for each of the possible data types, and each get method has two
versions −
▪ One that takes in a column name.
▪ One that takes in a column index.
• For example, if the column you are interested in viewing contains an int, you need to use
one of the getInt() methods of ResultSet
S. No Methods & Description
public int getInt(String columnName) throws SQLException
1
Returns the int in the current row in the column named columnName.
public int getInt(int columnIndex) throws SQLException
2 Returns the int in the current row in the specified column index. The column index starts
at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on.
• Similarly, there are get methods in the ResultSet interface for each of the eight Java
primitive types, as well as common types such as java.lang.String, java.lang.Object, and
java.net.URL.
• There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more
information about using these SQL data types.
• The ResultSet interface contains a collection of update methods for updating the data of a
result set.
• As with the get methods, there are two update methods for each data type −
▪ One that takes in a column name.
▪ One that takes in a column index.
• For example, to update a String column of the current row of a result set, you would use one
of the following updateString() methods:
18
Advanced Java Programming Unit - I JDBC
19
Advanced Java Programming Unit - II Networking
Unit II – NETWORKING
➢ InetAddress
➢ TCP/ IP client sockets
➢ TCP/ IP server sockets
➢ URL
➢ URL Connection
➢ Datagrams
➢ Client/ Server application using RMI.
Networking Basics
• In Java Networking is a concept of connecting two or more computing devices together so
that we can share resources.
• Java socket programming provides facility to share data between different computing
devices.
1) IP Address
2) Protocol
3) Port Number
6) Socket
java.net package
• The java.net package provides many classes to deal with networking applications in Java.
• A list of these classes is given below:
InetAddress class
Method Description
public static InetAddress getByName(String host) it returns the instance of InetAddress
throws UnknownHostException containing LocalHost IP and name.
public static InetAddress getLocalHost() throws it returns the instance of InetAdddress
UnknownHostException containing local host name and address.
public String getHostName() it returns the host name of the IP address.
public String getHostAddress() it returns the IP address in string format.
2
Advanced Java Programming Unit - II Networking
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}
Output:
Socket Programming
• Java Socket programming is used for communication between the applications running on
different JRE.
• Java Socket programming can be connection-oriented or connection-less.
• Socket and ServerSocket classes are used for connection-oriented socket programming
• DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
• The client in socket programming must know two information:
1. IP Address of Server
2. Port number
Methods:
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream returns the OutputStream attached with this
getOutputStream() socket.
3) public synchronized void close() closes this socket
3
Advanced Java Programming Unit - II Networking
• The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Methods:
Method Description
1) public Socket accept() returns the socket and establish a connection
between server and client.
2) public synchronized void close() closes the server socket.
Creating Server:
• To create the server application, we need to create the instance of ServerSocket class.
• Here, we are using 6666 port number for the communication between the client and server.
• You may also choose any other port number.
• The accept() method waits for the client. If clients connects with the given port number, it
returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection and waits for the client
Creating Client:
• To create the client application, we need to create the instance of Socket class.
• Here, we need to pass the IP address or hostname of the Server and a port number.
• Here, we are using "localhost" because our server is running on same system.
Socket s=new Socket("localhost",6666);
URL
• URL(String spec)
✓ Creates an instance of a URL from the String representation.
• URL(String protocol, String host, int port, String file)
✓ Creates an instance of a URL from the given protocol, host, port number, and file.
• URL(String protocol, String host, int port, String file, URLStreamHandler handler)
✓ Creates an instance of a URL from the given protocol, host, port number, file, and
handler.
• URL(String protocol, String host, String file)
4
Advanced Java Programming Unit - II Networking
✓ Creates an instance of a URL from the given protocol name, host name, and file name.
• The java.net.URL class provides many methods. The important methods of URL class are
given below.
Method Description
public String getProtocol() It returns the protocol of the URL.
public String getHost() It returns the host name of the URL.
public String getPort() It returns the Port Number of the URL.
public String getFile() It returns the file name of the URL.
public String getAuthority() It returns the authority of the URL.
public String toString() It returns the string representation of the URL.
public String getQuery() It returns the query string of the URL.
public String getDefaultPort() It returns the default port of the URL.
It returns the instance of URLConnection i.e.
public URLConnection openConnection() associated with this URL.
public boolean equals(Object obj) It compares the URL with the given object.
public Object getContent() It returns the content of the URL.
It returns the anchor or reference of the URL.
public String getRef()
public URI toURI() It returns a URI of the URL.
//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{ URL url=new URL("http://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
URLConnection class
• The Java URLConnection class represents a communication link between the URL and the
application.
• This class can be used to read and write data to the specified resource referred by the URL.
5
Advanced Java Programming Unit - II Networking
• The openConnection() method of URL class returns the object of URLConnection class.
• The URLConnection class provides many methods, we can display all the data of a webpage
by using the getInputStream() method.
• The getInputStream() method returns all the data of the specified URL in the stream that can
be read and displayed.
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}
HttpURLConnection class
• The Java HttpURLConnection class is http specific URLConnection. It works for HTTP
protocol only.
• By the help of HttpURLConnection class, you can information of any HTTP URL such as
header information, status code, response code etc.
• The java.net.HttpURLConnection is subclass of URLConnection class.
• The openConnection() method of URL class returns the object of URLConnection class.
Syntax:public URLConnection openConnection()throws IOException{}
HttpURLConnecton Example
import java.io.*;
import java.net.*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
6
Advanced Java Programming Unit - II Networking
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
}
huc.disconnect();
}catch(Exception e){System.out.println(e);}
}
}
Output:
Date = Wed, 10 Dec 2014 19:31:14 GMT
Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-age=2592000
Expires = Fri, 09 Jan 2015 19:31:14 GMT
Vary = Accept-Encoding,User-Agent
Connection = close
Transfer-Encoding = chunked
Datagrams
• Datagrams are bundles of information passed between machines.
• Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
DatagramSocket class
• Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets.
• A datagram is basically an information but there is no guarantee of its content, arrival or
arrival time.
DatagramPacket class
• Java DatagramPacket is a message that can be sent or received. If you send multiple packet,
it may arrive in any order. Additionally, packet delivery is not guaranteed
//DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
7
Advanced Java Programming Unit - II Networking
//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
• The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java.
• The RMI allows an object to invoke methods on an object running in another JVM.
• The RMI provides remote communication between the applications using two
objects stub and skeleton.
• RMI uses stub and skeleton object for communication with the remote object.
• A remote object is an object whose method can be invoked from another JVM.
Stub
• The stub is an object, acts as a gateway for the client side.
• All the outgoing requests are routed through it.
• It resides at the client side and represents the remote object.
• When the caller invokes method on the stub object, it does the following tasks:
Skeleton
• The skeleton is an object, acts as a gateway for the server side object.
• All the incoming requests are routed through it.
• When the skeleton receives the incoming request, it does the following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
8
Advanced Java Programming Unit - II Networking
• In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.
• If any application performs these tasks, it can be distributed application.
The RMI application has all these features, so it is called the distributed application.
RMI Example
• In this example, we have followed all the 6 steps to create and run the rmi application.
• The client application need only two files, remote interface and client application.
• In the rmi application, both client and server interacts with the remote interface.
• The client application invokes methods on the proxy object, RMI sends the request to the
remote JVM.
• The return value is sent back to the proxy object and then to the client application.
• For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface.
• Here, we are creating a remote interface that extends the Remote interface.
• There is only one method named add() and it declares RemoteException.
import java.rmi.*;
public interface Adder extends Remote{
public int add(int x,int y)throws RemoteException;
}
• Now provide the implementation of the remote interface. For providing the implementation
of the Remote interface, we need to
o Either extend the UnicastRemoteObject class, (or)
o Use the exportObject() method of the UnicastRemoteObject class
• In case, you extend the UnicastRemoteObject class, you must define a constructor that
declares RemoteException.
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder{
AdderRemote()throws RemoteException{
super();
}
public int add(int x,int y){return x+y;}
}
9
Advanced Java Programming Unit - II Networking
3) Create the stub and skeleton objects using the rmic tool
• Next step is to create stub and skeleton objects using the rmi compiler.
• The rmic tool invokes the RMI compiler and creates stub and skeleton objects.
rmic AdderRemote
4) Start the registry service by the rmiregistry tool
rmiregistry 5000
5) Create and run the server application
In this example, we are binding the remote object by the name sonoo.
import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}
6) Create and run the client application
• At the client we are getting the stub object by the lookup() method of the Naming class and
invoking the method on this object.
•
10
Advanced Java Programming Unit - II Networking
• In this example, we are running the server and client applications, in the same machine so
we are using localhost.
• If you want to access the remote object from another machine, change the localhost to the
host name (or IP address) where the remote object is located.
import java.rmi.*;
public class MyClient{
public static void main(String args[]){
try{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));
}catch(Exception e){}
}
}
11
Advanced Java Programming Unit - III Java Beans
• The java beans possess the property of “Write once and run anywhere”.
• Beans can work in different local platforms.
• Beans have the capability of capturing the events sent by other objects and
vice versa enabling object communication.
• The properties, events and methods of the bean can be controlled by the
application developer.(ex. Add new properties)
• Beans can be configured with the help of auxiliary software during design time.(no
hassle at runtime)
• The configuration setting can be made persistent.(reused)
• Configuration setting of a bean can be saved in persistent storage and restored later.
function, such as forecasting the performance of a stock portfolio. A Bean may be visible to
an end user. One example of this is a button on a graphical user interface.
• Software to generate a pie chart from a set of data points is an example of a Bean that can
execute locally.
• Bean that provides real-time price information from a stock or commodities exchange.
• Builder support: Enables you to create and group multiple JavaBeans in an application.
• Layout: Allows multiple JavaBeans to be arranged in a development environment.
• Interface publishing: Enables multiple JavaBeans in an application to communicate with each
other.
• Event handling: Refers to firing and handling of events associated with a JavaBean.
• Persistence: Enables you to save the last state of JavaBean
Is a development environment to create, configure, and test Java Beans. The features of BDK
environment are:
• Provides a GUI to create, configure, and test JavaBeans.
• Enables you to modify JavaBean properties and link multiple JavaBeans in an application
using BDK.
• Provides a set of sample JavaBeans.
• Enables you to associate pre-defined events with sample JavaBeans.
• Execute the run.bat file of BDK to start the BDK development environment.
3
Advanced Java Programming Unit - III Java Beans
Bean Box window: Is a workspace for creating the layout of Java Bean application.
Properties window: Displays all the exposed properties of a JavaBean. You can
modify JavaBean properties in the properties window.
Method Tracer window: Displays the debugging messages and method calls for a
JavaBean application.
• The manifest file for a JavaBean application contains a list of all the class files that
make up a JavaBean.
• The entry in the manifest file enables the target application to recognize
the JavaBean classes for an application.
• For example, the entry for the MyBean JavaBean in the manifest file is as shown:
5
Advanced Java Programming Unit - III Java Beans
• Write that 2 lines code in the notepad and save that file as MANIFEST.MF in META-INF
directory
• The rules to create a manifest file are:
✓ Press the Enter key after typing each line in the manifest file.
✓ Leave a space after the colon.
✓ Type a hyphen between Java and Bean.
✓ No blank line between the Name and the Java-Bean entry.
6
Advanced Java Programming Unit - III Java Beans
• JAR file allows you to efficiently deploy a set of classes and their associated resources.
• JAR file makes it much easier to deliver, install, and download. It is compressed.
• The files of a JavaBean application are compressed and grouped as JAR files to reduce
the size and the download time of the files.
• The syntax to create a JAR file from the command prompt is:
✓ jar <options><file_names>
• The file_names is a list of files for a JavaBean application that are stored in the JAR file.
The various options that you can specify while creating a JAR file are:
✓ f: Indicates that the first file in the file_names list is the name of the JAR file.
✓ m: Indicates that the second file in the file_names list is the name of the manifest file.
✓ t: Indicates that all the files and resources in the JAR file are to be displayed in a tabular format.
✓ x: Indicates that the files and resources of a JAR file are to be extracted.
6. Start BDK
• Go to C:\bdk1_1\beans\beanbox Click on run.bat file.
• Beanbox->File->Load jar
• Here we have to select our created jar file when we click on ok.
• our bean(userdefined) MyBean appear in the ToolBox.
• Select the MyBean from the ToolBox when we select that bean one + simple
appear then drag that Bean in to the Beanbox.
• If you want to apply events for that bean, now we apply the events for that Bean.
8
Advanced Java Programming Unit - III Java Beans
Introspection
SimpleBean.java
//Introspection
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.*;
import java.beans.PropertyDescriptor;
public class SimpleBean
{
private String
name="CMRCET"; private
int Size;
public String getName()
{
return this.name;
}
public int getSize()
{
return this.Size;
}
public void setSize(int size)
{
this.Size=size;
}
public void setName(String name)
{
this.name=name;
}
public static void main(String args[])throws IntrospectionException
9
Advanced Java Programming Unit - III Java Beans
{
BeanInfo info=Introspector.getBeanInfo(SimpleBean.class);
for(PropertyDescriptor pd:info.getPropertyDescriptors())
{
System.out.println("BeanInfo:="+pd.getName());
}
Output:
• A property is a subset of a Bean’s state. A bean property is a named attribute of a bean that
can affect its behavior or appearance.
• Examples of bean properties include color, label, font, font size, and display size.
• Properties are the private data members of the Java Bean classes.
• Properties are used to accept input from an end user in order to customize a Java Bean.
• Properties can retrieve and specify the values of various attributes, which determine the
behavior of a Java Bean.
• Simple properties
• Boolean properties
• Indexed properties
10
Advanced Java Programming Unit - III Java Beans
• Bound Properties
• Constrained Properties
Simple Properties
• Simple properties refer to the private variables of a JavaBean that can have only a single
value. Simple properties are retrieved and specified using the get and set methods
respectively.
✓ A read/write property has both of these methods to access its values. The get method
used to read the value of the property .The set method that sets the value of the
property.
✓ The setXXX() and getXXX() methods are the heart of the java beans properties
mechanism. This is also called getters and setters. These accessor methods are
used to set the property .
▪ public T getN();
▪ public void setN(T arg) N is the name of the property and T is its type
Example
public double getDepth()
{
return depth;
}
Boolean Properties
• A Boolean property is a property which is used to represent the values True or False.
• Have either of the two values, TRUE or FALSE. It can identified by the following
methods:
11
Advanced Java Programming Unit - III Java Beans
Syntax
• Let N be the name of the property and T be the type of the value then
• publicbooleanisN();
public void setN(boolean
parameter); public Boolean
getN(); publicboolean
is<PropertyName>()
publicboolean
get<PropertyName>()
Example
publicboolean
dotted=false;
publicbooleanisDotted()
{ return dotted; }
public void setDotted(boolean
dotted) { this.dotted=dotted; }
Indexed Properties
• Indexed Properties are consists of multiple values. If a simple property can hold an array
of value they are no longer called simple but instead indexed properties.
• The method’s signature has to be adapted accordingly. An indexed property may expose
set/get methods to read/write one element in the array (so-called ’index getter/setter’)
and/or so-called ’array getter/setter’ which read/write the entire array.
• Indexed Properties enable you to set or retrieve the values from an array of
property values.
• Indexed Properties are retrieved using the following get methods:
Example
private double data[];
public double getData(int index)
{
return data[index];
}
• Syntax:public property_datatype get<PropertyName>(int index)
Example
public void setData(intindex,double value)
{
12
Advanced Java Programming Unit - III Java Beans
Data[index]=value;
}
Indexed Properties are specified using the following set methods:
Example
public double[] getData()
{
return data;
}
Bound Properties
• A bean that has a bound property generates an event when the property is changed.
• Bound Properties are the properties of a JavaBean that inform its listeners about changes
in its values.
• Bound Properties are implemented using the PropertyChangeSupport class and its
methods. Bound Properties are always registered with an external event listener.
• The event is of type PropertyChangeEvent and is sent to objects that previously registered
an interest in receiving such notifications bean with bound property
• Event source Bean implementing listener -- event target.
• In order to provide this notification service a JavaBean needs to have the following two
methods:
▪ public void addPropertyChangeListener(PropertyChangeListener p)
{
changes.addPropertyChangeListener(p);
}
• public void removePropertyChangeListener(PropertyChangeListener p)
{
changes.removePropertyChangeListener(p);
}
• PropertyChangeListener is an interface declared in the java.beans package.
• Observers which want to be notified of property changes have to implement this interface,
which consists of only one method:
• public interface PropertyChangeListener extends EventListener
{
public void propertyChange(PropertyChangeEvent e );
}
13
Advanced Java Programming Unit - III Java Beans
Constrained Properties
14
Advanced Java Programming Unit - III Java Beans
// ConstrainedEx.java
package com.yellaswamy.constrainedexample;
//step1
import java.awt.*;
import java.beans.*;
public class ConstrainedEx extends Canvas
{
//Step2
String price="100";
VetoableChangeSupport vcs=new
VetoableChangeSupport(this); private PropertyChangeSupport
pcs=new PropertyChangeSupport(this);
//constructor
public ConstrainedEx()
{
setBackground(Color.red);
setForeground(Color.blue);
}
String
oldprice=price;
price=newprice
;
pcs.firePropertyChange("price","oldprice","newprice");
}
//step4
public void addVetoableChangeListener(VetoableChangeListener vcl)
15
Advanced Java Programming Unit - III Java Beans
{
vcs.addVetoableChangeListener(vcl);
}
public void removeVetoableChangeListener(VetoableChangeListener vcl)
{
vcs.removeVetoableChangeListener(vcl);
}
}
• Enables Beans to communicate and connect together. Beans generate events and these events
can be sent to other objects. Event means any activity that interrupts the current ongoing
activity.
• Example: mouse clicks, pressing key…
• User-defined JavaBeans interact with the help of user-defined events, which are also called
custom events. You can use the Java event delegation model to handle these custom events.
• The components of the event delegation model are:
✓ Event Source: Generates the event and informs all the event listeners that are registered with it
✓ Event Listener: Receives the notification, when an event source generates an event
✓ Event Object: Represents the various types of events that can be generated by the event
sources.
• The classes and interfaces that you need to define to create the custom JavaBean events are:
• An event class to define a custom JavaBean event.
• An event listener interface for the custom JavaBean event.
• An event handler to process the custom JavaBean event.
• A target Java application that implements the custom event.
• The event class that defines the custom event extends the EventObject class of the java.util
package.
Example
public class NumberEvent extends EventObject
{
publicint number1,number2;
publicNumberEvent(Object o,int number1,int number2)
{
super(o); this.number1=number1;
this.number2=number2;
} }
• Beans can generate events and send them to other objects.
16
Advanced Java Programming Unit - III Java Beans
• When the event source triggers an event, it sends a notification to the event listener
interface.
• The event listener interface implements the java.util.EventListener interface.
Syntax
public void addTListener(TListenereventListener);
public void addTListener(TListenereventListener)throws TooManyListeners;
public void removeTListener(TListenereventListener);
• The target application that uses the custom event implements the custom listener.
Example
public interface NumberEnteredListener extends EventListener
{
public void arithmeticPerformed(NumberEventmec);
}
The code snippet to define an event handler for the custom event NumberEvent
Persistence
• Persistence means an ability to save properties and events of our beans to non-volatile
storage and retrieve later.
• It has the ability to save a bean to storage and retrieve it at a later time Configuration
settings are saved It is implemented by Java serialization.
• If a bean inherits directly or indirectly from Component class it is automatically Serializable.
17
Advanced Java Programming Unit - III Java Beans
1. Juggle Bean.
2. Building an applet
3. Your own bean
Customizers
• The Properties window of the BDK allows a developer to modify the several properties of the
Bean.
• Property sheet may not be the best user interface for a complex component.
• It can provide step-by-step wizard guide to use component.
• It can provide a GUI frame with image which visually tells what is changed such as radio
button, check box, ...
• It can customize the appearance and behavior of the properties Online documentation can
also be provided.
• A Bean developer has great flexibility to develop a customizer that can differentiate his or
her product in the marketplace.
• To make it easy to configure a java beans component enables a developer to use an
application builder tool to customize the appearance and behavior of a bean.
18
Advanced Java Programming Unit – IV Java Servlets
Requirements of Servlets
• Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.
• Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
✓ Performance is significantly better.
✓ Servlets execute within the address space of a Web server. It is not necessary to create
a separate process to handle each client request.
✓ Servlets are platform-independent because they are written in Java.
✓ Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.
✓ The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
Servlets Architecture
• The following diagram shows the position of Servlets in a Web Application.
1
Advanced Java Programming Unit – IV Java Servlets
Servlets Tasks
Servlets perform the following major tasks −
• Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
• Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.
Servlets Packages
• Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.
• Servlets can be created using the javax.servlet and javax.servlet.http packages,
which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects.
• These classes implement the Java Servlet and JSP specifications. At the time of writing
this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
• Java servlets have been created and compiled just like any other Java class. After you
install the servlet packages and add them to your computer's Classpath, you can
compile servlets with the JDK's Java compiler or any other current compiler.
Servlet Environment
• A development environment is where you would develop your Servlet, test them and
finally run them.
• Like any other Java program, you need to compile a servlet by using the Java
compiler javac and after compilation the servlet application, it would be deployed in a
configured environment to test and run..
• This development environment setup involves the following steps:
2
Advanced Java Programming Unit – IV Java Servlets
3
Advanced Java Programming Unit – IV Java Servlets
• Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site − http://tomcat.apache.org
• Tomcat can be stopped by executing the following commands on windows machine
▪ C:\apache-tomcat-8.0.28\bin\shutdown
• Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine
▪ /usr/local/apache-tomcat-8.0.28/bin/shutdown.sh
• 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.
4
Advanced Java Programming Unit – IV Java Servlets
public void init() throws ServletException {
// Initialization code...
}
Servlets are Java classes which service HTTP requests and implement
the javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is
specially designed to handle HTTP requests.
Sample Code
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Servlet API
• The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet
api.
• The javax.servlet package contains many interfaces and classes that are used by the servlet
or web container. These are not specific to any protocol.
• The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
6
Advanced Java Programming Unit – IV Java Servlets
• HttpServletRequest HttpServletResponse
• HttpSession HttpSessionListener
• HttpSessionAttributeListener HttpSessionBindingListener
• HttpSessionContext HttpSessionActivationListener
GenericServlet class
7
Advanced Java Programming Unit – IV Java Servlets
File: First.java
import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
HttpServlet class
• The HttpServlet class extends the GenericServlet class and implements Serializable
interface.
• It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
8
Advanced Java Programming Unit – IV Java Servlets
GET Method
• The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ? (question mark) symbol as
follows
✓ http://www.test.com/hello?key1 = value1&key2 = value2
• The GET method is the default method to pass information from browser to web server
and it produces a long string that appears in your browser's Location:box. Never use the
GET method if you have password or other sensitive information to pass to the server.
The GET method has size limitation: only 1024 characters can be used in a request
string.
• This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests
using doGet() method.
POST Method
• A generally more reliable method of passing information to a backend program is the POST
method.
• This packages the information in exactly the same way as GET method, but instead of
sending it as a text string after a, ? (question mark) in the URL it sends it as a separate
message.
9
Advanced Java Programming Unit – IV Java Servlets
• This message comes to the backend program in the form of the standard input which you
can parse and use for your processing. Servlet handles this type of requests
using doPost() method.
out.println(docType +
"<html>\n" +
10
Advanced Java Programming Unit – IV Java Servlets
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
doGet(request, response);
}
}
Now, try the above servlet with the following form −
<html>
<body>
<form action = "ReadParams" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
11
Advanced Java Programming Unit – IV Java Servlets
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chem
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
Cookies
• A cookie is a small piece of information that is persisted between the multiple client
requests.
• A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
• It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Cookie class
12
Advanced Java Programming Unit – IV Java Servlets
• There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in
seconds.
public String getName() Returns the name of the cookie. The name
cannot be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
Creation of Cookie
Deletion of Cookie
Getting Cookies
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
{
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of
cookie
}
13
Advanced Java Programming Unit – IV Java Servlets
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
} }
14
Advanced Java Programming Unit – IV Java Servlets
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Output
15
Advanced Java Programming Unit – IV Java Servlets
Session tracking
16
Advanced Java Programming Unit – IV Java Servlets
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
17
Advanced Java Programming Unit – V JApplets
➢ JApplet
➢ Button
➢ Combo
➢ Trees
➢ Tables
➢ Panes
➢ AWT Classes
➢ Working with Graphics
➢ Working with Color
➢ Working with Font
Java Swing (JApplet)
• 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.
• Unlike AWT, Java Swing provides platform-independent and lightweight components.
• The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
• There are many differences between java awt and swing that are given below:
1
Advanced Java Programming Unit – V JApplets
• The methods of Component class are widely used in java swing that are given below.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by
default false.
JButton
• The JButton class is used to create a labeled button that has platform independent
implementation.
• The application result in some action when the button is pushed. It inherits AbstractButton
class.
2
Advanced Java Programming Unit – V JApplets
Constructors of JButton
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
JButton ExampleProgram
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
3
Advanced Java Programming Unit – V JApplets
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
JLabel
4
Advanced Java Programming Unit – V JApplets
Constructors of JLabel:
Constructor Description
JLabel() Creates a JLabel instance with no image and with
an empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment) image, and horizontal alignment.
JLabel Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
} }}
Output:
5
Advanced Java Programming Unit – V JApplets
JTextField
• The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.
Constructors of JTextField:
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text
columns) and columns.
JTextField(int columns) Creates a new empty TextField with the specified number
of columns.
Methods of JTextField:
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener
to receive action events from this textfield.
Action getAction() It returns the currently set Action for this
ActionEvent source, or null if no Action is
set.
void setFont(Font f) It is used to set the current font.
void It is used to remove the specified action
removeActionListener(ActionListener l) listener so that it no longer receives action
events from this textfield.
JTextField Example
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); } }
6
Advanced Java Programming Unit – V JApplets
Output:
JCheckBox
• The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false).
• Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
Constructors of JCheckBox:
Constructor Description
JJCheckBox() Creates an initially unselected check box button with
no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or
selected) not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from
the Action supplied.
Methods of JCheckBox:
Methods Description
AccessibleContext It is used to get the AccessibleContext associated with
getAccessibleContext() this JCheckBox.
7
Advanced Java Programming Unit – V JApplets
Output:
JRadioButton
Constructors of JRadioButton:
Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, boolean Creates a radio button with the specified text and selected
selected) status.
Methods of JRadioButton:
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.
Output:
9
Advanced Java Programming Unit – V JApplets
JComboBox
Constructors of JComboBox:
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the
specified array.
JComboBox(Vector<?> Creates a JComboBox that contains the elements in the
items) specified Vector.
Methods of JComboBox:
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox
is editable.
void addActionListener(ActionListener a) It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.
10
Advanced Java Programming Unit – V JApplets
Output:
JTree
• The JTree class is used to display the tree structured data or hierarchical data.
• JTree is a complex component. It has a 'root node' at the top most which is a parent for all
nodes in the tree. It inherits JComponent class.
Constructors of JTree:
Constructor Description
JTree() Creates a JTree with a sample model.
JTree(Object[] value) Creates a JTree with every element of the specified array as
the child of a new root node.
JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which
displays the root node.
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
Output:
JTable
12
Advanced Java Programming Unit – V JApplets
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Output:
JScrollPane
Constructors of JScrollPane:
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter,
when present, sets the scroll pane's client. The two int
JScrollPane(Component)
parameters, when present, set the vertical and
JScrollPane(int, int) horizontal scroll bar policies (respectively).
JScrollPane(Component, int, int)
13
Advanced Java Programming Unit – V JApplets
Methods of JScrollPane:
Modifier Method Description
Void setColumnHeaderView(Component) It sets the column header for the scroll pane.
Void setRowHeaderView(Component) It sets the row header for the scroll pane.
Void setCorner(String, Component) It sets or gets the specified corner. The int
Component getCorner(String) parameter specifies which corner and must
be one of the following constants defined in
ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
Void setViewportView(Component) Set the scroll pane's client.
JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Scroll Pane Example");
// Display the window.
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWA
YS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
14
Advanced Java Programming Unit – V JApplets
Output:
JTabbedPane
• The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.
Constructors of JTabbedPane:
Constructor Description
JTabbedPane() Creates an empty TabbedPane with a default tab
placement of JTabbedPane.Top.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab
placement.
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab
tabLayoutPolicy) placement and tab layout policy.
15
Advanced Java Programming Unit – V JApplets
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}
Output:
AWT Classes
AWT Hierarchy
16
Advanced Java Programming Unit – V JApplets
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.
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.
Panel
• The Panel is the container that doesn't contain title bar and menu bars.
• It can have other components like button, textfield etc.
Frame
• The Frame is the container that contain title bar and can have menu bars.
• It can have other components like button, textfield etc.
17
Advanced Java Programming Unit – V JApplets
AWT Example
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
Output:
19