Unit 4 Advance Java: Structure Page Nos
Unit 4 Advance Java: Structure Page Nos
Unit 4 Advance Java: Structure Page Nos
4.0 INTRODUCTION
This unit will introduce you to the advanced features of Java. To save data, you have
used the file system, which gives you functionality of accessing the data but it does
not offer any capability for querying on data conveniently.
You are familiar with various databases like Oracle, Sybase, SQL Server etc. They
do not only provide the file-processing capabilities, but also organize data in a manner
that facilitates applying queries.
Structured Query Language (SQL) is almost universally used in relational database
systems to make queries based on certain criteria. In this unit you will learn how you
can interact to a database using Java Database Connectivity (JDBC) feature of Java.
You will also learn about RMI (Remote Method Invocation) feature of Java. This will
give the notion of client/server distributed computing. RMI allows Java objects
running on the same or separate computers to communicate with one another via
remote method calls.
Java beans are nothing but small reusable pieces of components that you can add to a
program without disturbing the existing program code, are also introduced in this unit.
4.1 OBJECTIVES
79
Applets Programming
and Advance Java
• use basic database queries using Structured Query Language (SQL) in your
Concepts programs;
• explain Servlet Life Cycle;
• write simple servlets programs;
• explain the model of client/server distributed computing;
• explain architecture of RMI, and
• describe Java Beans and how they facilitate component-oriented software
construction.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
Let us see what are these parameters passed to get Connection method of
DriverManager class. The first string is the URL for the database including the
protocol, the vendor, the driver, and the server the port number. The username and
password are the name of the user of database and password is user password.
The connection con returned in the last step is an open connection, which will be used
to pass SQL statements to the database.
80
An active connection is needed to create a Statement object. The following code is a Advance Java
snippet, using our Connection object con
Another advantage offered by PreparedStatement object is that if you need to use the
same or similar query with different parameters multiple times, the statement can be
compiled and optimized by the DBMS just once. While with a normal Statement, each
use of the same SQL statement requires a compilation all over again.
PreparedStatements are also created with a Connection method. The following code
shows how to create a parameterized SQL statement with three input parameters:
PreparedStatement prepareUpdatePrice
= con.prepareStatement( "UPDATE Employee SET emp_address =? WHERE
emp_code =“1001” AND emp_name =?");
You can see two? symbol in the above PreparedStatement prepareUpdatePrice. This
means that you have to provide values for two variables emp_address and emp_name
in PreparedStatement before you execute it. Calling one of the setXXX methods
defined in the class PreparedStatement can provide values. Most often used methods
are setInt, setFloat, setDouble, setString, etc. You can set these values before each
execution of the prepared statement.
Executing SQL statements in JDBC varies depending on the intention of the SQL
statement. DDL (Data Definition Language) statements such as table creation and
table alteration statements, as well as statements to update the table contents, all are
executed using the executeUpdate method. The following snippet has examples of
executeUpdate statements.
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE Employee " +
"(emp_name VARCHAR2(40), emp_address VARCHAR2(40), emp_sal REAL)" );
stmt.executeUpdate("INSERT INTO Employee " +
"VALUES ('Archana', '10,Down California', 30000" );
String sqlString = "CREATE TABLE Employee " +
"(name VARCHAR2(40), address VARCHAR2(80), license INT)" ;
stmt.executeUpdate(sqlString);
Since the SQL statement will not quite fit on one line on the page, you can split it into
two or more strings concatenated by a plus sign(+).
"INSERT INTO Employee" to separate it in the resulting string from "VALUES".
81
Applets Programming The point to note here is that the same Statement object is reused rather than to create
and Advance Java
Concepts a new one each time.
When executeUpdate is used to call DDL statements, the return value is always zero,
while data modification statement executions will return a value greater than or equal
to zero, which is the number of tuples affected in the relation by execution of
modification statement.
The tuples resulting from the query are contained in the variable rs which is an
instance of ResultSet. A set is of not much use to you unless you can access each row
and the attributes in each row. The?
Now you should note that each invocation of the next method causes it to move to the
next row, if one exists and returns true, or returns false if there is no remaining row.
You can use the getXXX method of the appropriate type to retrieve the attributes of a
row. In the above program code getString and getFloat methods are used to access the
column values. One more thing you can observe that the name of the column whose
value is desired is provided as a parameter to the method.
1. ename = rs.getString(1);
eaddress = rs.getFloat(3);
esal = rs.getString(2);
82
2. ResultSet rs = prepareUpdateEmployee.executeQuery() ; Advance Java
Accessing ResultSet
Now to reach each record of the database, JDBC provides methods like getRow,
isFirst, isBeforeFirst, isLast, isAfterLas to access ResultSet.Also there are means to
make scroll-able cursors to allow free access of any row in the ResultSet. By default,
cursors scroll forward only and are read only. When creating a Statement for a
Connection, we can change the type of ResultSet to a more flexible scrolling or
updatable model:
Statement stmt = con.createStatement
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM Sells");
With the default cursor, we can scroll forward using rs.next(). With scroll-able cursors
we have more options:
rs.absolute(3); // moves to the third tuple or row
rs.previous(); // moves back one tuple (tuple 2)
rs.relative(2); // moves forward two tuples (tuple 4)
rs.relative(-3); // moves back three tuples (tuple 1)
JDBC allows SQL statements to be grouped together into a single transaction. Thus,
you can ensure the ACID (Atomicity, Consistency, Isolation, Durability) properties
using JDBC transactional features.
83
Applets Programming 2) What are the different kinds of drivers for JDBC?
and Advance Java
Concepts ……………………………………………………………………………………
……………………………………………………………………………………
3) Write a program code to show how you will perform commit() and rollback().
……………………………………………………………………………………
……………………………………………………………………………………
4) Read the following program assuming mytable already exists in database and
answer the questions given below:
i. What is the use of rs.next()?
ii. Value of which attribute will be obtained by rs.getString(3).
iii. If the statement “Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")” is
removed from the program what will happen.
import java.sql.*;
import java.io.*;
public class TestJDBC
{
public static void main(String[] args)
{
String dataSourceName = "mp";
String dbURL = "jdbc:odbc:" + dataSourceName;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(dbURL, "","");
Statement s = con.createStatement();
s.execute("insert into mytable values('AKM',20,'azn')");
s.executeQuery("select * from mytable ");
ResultSet rs = s.getResultSet();
rs.next();
String n = rs.getString(1);
System.out.println("Name:"+ n);
if (rs != null)
while ( rs.next() )
{
System.out.println("Data from column_name: " + rs.getString(1) );
System.out.println("Data from column_age: " + rs.getInt(2) );
System.out.println("Data from column_address: " + rs.getString(3) );
}
}
catch (Exception err)
{
System.out.println( "Error: " + err );
}
}
84
Java provides RMI (Remote Method Invocation), which is “a mechanism that allows Advance Java
one to invoke a method on an object that exists in another address space. The other
address space could be on the same machine or a different one. The RMI mechanism
is basically an object-oriented RPC mechanism.”
RPC (Remote Procedure Call) organizes the types of messages which an application
can receive in the form of functions. Basically it is a management of streams of data
transmission.
RMI applications often comprised two separate programs: a server and a client.
A typical server application creates some remote objects, makes references to them
accessible, and waits for clients to invoke methods on these remote objects.
A typical client application gets a remote reference to one or more remote objects in
the server and then invokes methods on them.
RMI provides the mechanism by which the server and the client communicate and
pass information back and forth. Such an application is sometimes referred to as a
distributed object application.
There are three processes that participate in developing applications based on remote
method invocation.
1. Within the address space where the object was constructed, the object is an
ordinary object, which can be used like any other object.
2. Within other address spaces, the object can be referenced using an object handle
While there are limitations on how one can use an object handle compared to an
object, for the most part one can use object handles in the same way as an
ordinary object.
A Remote class has two parts: the interface and the class itself.
The Remote interface must have the following properties:
Interface must be public.
Interface must extend the java.rmi.Remote interface. Every method in the interface
must declare that it throws java.rmi.RemoteException. Maybe other exceptions also
ought to be thrown.
85
Applets Programming It should extend the java.rmi.server.UnicastRemoteObject class. Objects of such a
and Advance Java
Concepts class exist in the address space of the server and can be invoked remotely. While there
are other ways to define a Remote class, this is the simplest way to ensure that objects
of a class can be used as remote objects.
It can have methods that are not in its Remote interface. These can only be invoked
locally. It is not necessary for both the Client and the Server to have access to the
definition of the Remote class.
The Server requires the definition of both the Remote class and the Remote interface,
but the client only uses the Remote interface.
All of the Remote interfaces and classes should be compiled using javac. Once this
has been completed, the stubs and skeletons for the Remote interfaces should be
compiled by using the rmic stub compiler. The stub and skeleton of the example
Remote interface are compiled with the command:
rmic <filename.class>
Client Server
Transport Transport
Network
RemoteObject
RemoteStub RemoteServer
UnicastRemoteObject
86
In Figure 2 above, the RMI Object Hierarchy is shown. The most general feature set Advance Java
associated with RMI is found in the java.rmi.Remote interface. Abstract class
java.rmi.server.RemoteObject supports the needed modifications to the Java object
model to cope with the indirect references.
Remote Server is a base class, which encapsulates transport semantics for
RemoteObjects. Currently RMI ships with a UnicastRemoteObject(single object)
A server in RMI is a named service which is registered with the RMI registry, and
listens for remote requests. For security reasons, an application can bind or unbind
only in the registry running on the same host.
4.3.4 Security
One of the most common problems with RMI is a failure due to security constraints.
Let us see Java the security model related to RMI. A Java program may specify a
security manager that determines its security policy. A program will not have any
security manager unless one is specified. You can set the security policy by
constructing a SecurityManager object and calling the setSecurityManager method of
the System class. Certain operations require that there be a security manager. For
example, RMI will download a Serializable class from another machine only if there
is a security manager and the security manager permits the downloading of the class
from that machine. The RMISecurityManager class defines an example of a security
manager that normally permits such download. However, many Java installations
have instituted security policies that are more restrictive than the default. There are
good reasons for instituting such policies, and you should not override them
carelessly.
The following are the basic steps be followed to develop a distributed application
using RMI:
87
Applets Programming
and Advance Java Check Your Progress 2
Concepts
1) What is Stub in RMI?
……………………………………………………………………………………
……………………………………………………………………………………
2) What are the basic actions performed by receiver object on server side?
……………………………………………………………………………………
……………………………………………………………………………………
3) What is the need of and Registry Service of RMI?
……………………………………………………………………………………
……………………………………………………………………………………
HTTP Servlet
Service
Web
Browser Server
88
Servlets are programs that run on servers, such as a web server. You all do net surfing Advance Java
and well known the data on which the web is submitted and you get the respond
accordingly. On web pages the data is retrieved from the corporate databases, which
should be secure. For these kinds of operations you can use servlets.
The program code given below will give you some idea to write a servlet program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Use "request" to read incoming HTTP headers (e.g. cookies)
// and HTML form data (e.g. data the user entered and submitted)
To act as a servlet, a class should extend HttpServlet and override doGet or doPost (or
both), depending on whether the data is being sent by GET or by POST. These
methods take two arguments: an HttpServletRequest and an HttpServletResponse
objects.
The HttpServletRequest has methods for information about incoming information
such as FORM data, HTTP request headers etc.
The httpServletResponse has methods that let you specify the HTTP response line
(200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most
importantly, a PrintWriter used to send output back to the client.
A Simple Servlet: Generating Plain Text
Here is a simple servlet that just generates plain text:
//Program file name: HelloWorld.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
89
Applets Programming
and Advance Java Compiling and Installing the Servlet
Concepts
Note that the specific details for installing servlets vary from Web server to Web
server. Please refer to the Web server documentation for definitive directions. The on-
line examples are running on Java Web Server (JWS) 2.0, where servlets are expected
to be in a directory called servlets in the JWS installation hierarchy.
You have to set the CLASSPATH to point to the directory above the one actually
containing the servlets. You can then compile normally from within the directory.
//HelloWWW.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" +
"<HTML>\n" +
90
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + Advance Java
"<BODY>\n" +
"<H1>Hello WWW</H1>\n" +
"</BODY></HTML>");
}
}
URL: http://localhost:8080/servlet/HelloWWW
HelloWWW Output:
It is essential to track client’s requests. To perform this task, Java servlets offers two
different ways:
1. It is possible to save information about client state on the server using a Session
object A session is
2. It is possible to save information on the client system using cookies. sequence of
HTTP requests,
HTTP is a stateless protocol. If a client makes a series of requests on a server, HTTP from the same
provides no help whatsoever to determine if those requests originated from the same client, over a
client. There is no way in HTTP to link two separate requests to the same client. period of time.
Hence, there is no way to maintain state between client requests in HTTP.
You need to maintain the state on the web for e-commerce type of applications. Just
like other software systems, web applications want and need state. The classic web
application example is the shopping cart that maintains a list of items you wish to
purchase at a web site. The shopping cart’s state is the items in the shopping basket at
any given time. This state, or shopping items, needs to be maintained over a series of
client requests. HTTP alone cannot do this; it needs help.
Now the question arises, for how long can you maintain the state of the same client?
Of course, this figure is application-dependent and brings into play the concept of a
web session. If a session is configured to last for 30 minutes, once it has expired the
client will need to start a new session. Each session requires a unique identifier that
can be used by the client.
There are various ways through which you maintain the state.
}
...
In this approach’ the search servlet gets the session id from the hidden form field and
uses it to determine whether it allows performing any more searches.
Hidden form fields implement the required anonymous session tracking features the
client needs but not without cost. For hidden fields to work the client must send a
hidden form field to the server and the server must always return that same hidden
form field. This tightly coupled dependency between client requests and server
responses requires sessions involving hidden form fields to be an unbreakable chain of
dynamically generated web pages. If at any point during the session the client
accesses a static page that is not point of the chain, the hidden form field is lost, and
with it the session is also lost.
URL Rewriting
URL rewriting stores session details as part of the URL itself. You can see below how
we look at request information for our search servlet:
i) http://www.archana.com/servlet/search
ii) http://www.archana.com/servlet/search/23434abc
iii) http://www.archana.com/servlet/search?sessionid=23434abc
For the original servlet [i] the URL is clean. In [ii] we have URL re-written at the
server to add extra path information as embedded links in the pages we send back to
the client. When the client clicks on one of these links, the search servlet will do the
following:
92
Technique [iii] simply re-writes the URL with parameter information that can be Advance Java
accessed as follows:
request.getParameterValue("sessionid");
URL re-writing, like, hidden forms provide a means to implement anonymous session
tracking. However, with URL rewriting you are not limited to forms and you can re-
write URLs in static documents to contain the required session information. But URL
re-writing suffers from the same major disadvantage that hidden form fields do, in that
they must be dynamically generated and the chain of HTML page generation cannot
be broken.
Session object
A HttpSession object (derived from Session object) allows the servlet to solve part of
the HTTP stateless protocol problems. After its creation a Session is available until an
explicit invalidating command is called on it (or when a default timeout occurs). The
same Session object can be shared by two or more cooperating servlets. This means
each servlet can track client’s service request history.
Note:
public abstract String getId( ): Returns a string containing session’s name. This name
is unique and is set by HttpSessionContext().
public abstract void putValue (String Name, Object Value): Connect the object Value
to the Session object identified by Name parameter. If another object has been
connected to the same session before, it is automatically replaced.
public abstract Object getValue (String name): Returns the object currently held by
current session. It returns a null value if no object has been connected before to the
session.
public abstract void removeValue (String name): Remove, if existing, the object
connected to the session identified by the Name parameter.
Cookies A cookie is a
text file with a
Using JSDK (Java Servlet Development Kit) it is possible to save client’s state
name, a value
sending cookies. Cookies are sent from the server and saved on client’s system. On
and a set of
client’s system cookies are collected and managed by the web browser. When a
cookie is sent, the server can retrieve it in a successive client’s connection. Using this attributes.
strategy it is possible to track client’s connections history.
Cookie class of Java is derives directly from the Object class. Each Cookie object
instance has some attributes like max age, version, server identification, comment.
93
Applets Programming Below are some cookie methods:
and Advance Java
Concepts
public Cookie (String Name, String Value): Cookie class' constructor. It has two
parameters. The first one is the name that will identity the cookie in the future; the
second one, Value, is a text representing the cookie value. Notice that Name parameter
must be a "token" according to the standard defined in RFC2068 and RFC2109.
Public String getName( ): Returns cookie’s name. A cookie name is set when the
cookie is created and can’t be changed.
public void setValue(String NewValue): This method can be used to set or change
cookie’s value.
public void setMaxAge (int MaxAge): Sets cookie’s max age in seconds. This means
client’s browser will delete the cookie in MaxAge seconds. A negative value indicate
the cookie has to be deleted when client’s web browser exits.
94
A “JavaBeans-enabled” builder tool examines the Bean’s patterns, discern its features, Advance Java
and exposes those features for visual manipulation. A builder tool maintains Beans in
a palette or toolbox. You can select a Bean from the toolbox, drop it into a form,
modify its appearance and behaviour, define its interaction with other Beans, and
compose it into applets, application, or new Bean. All this can be done without writing
a line of code.
To understand the precise meaning of this definition of a Bean, you must understand
the following terms:
• Software component
• Builder tool
• Visual manipulation.
Reusable software components are designed to apply the power and benefit of
reusable, interchangeable parts from other industries to the field of software
construction. Other industries have long profited from reusable components. Reusable
electronic components are found on circuit boards. A typical part in your car can be
replaced by a component made from one of many different competing manufacturers.
Lucrative industries are built around parts construction and supply in most
competitive fields. The idea is that standard interfaces allow for interchangeable,
reusable components.
Reusable software components can be simple like familiar push buttons, text fields list
boxes, scrollbars, dialogs boxes etc.
Features of JavaBeans
• Individual Java Beans will vary in functionality, but most share certain common
defining features.
• Support for introspection allowing a builder tool to analyze how a bean works.
• Support for customization allowing a user to alter the appearance and
behaviour of a bean.
• Support for events allowing beans to fire events, and informing builder tools
about both the events they can fire and the events they can handle.
• Support for properties allowing beans to be manipulated programmatically, as
well as to support the customization mentioned above.
• Support for persistence allowing beans that have been customized in an
application builder to have their state saved and restored. Typically persistence
is used with an application builder’s save and load menu commands to restore
any work that has gone into constructing an application.
It is not essential that Beans can only be primarily with builder tools. Beans can also
be manually manipulated by programmatic interfaces of Text tools. All key APIs,
95
Applets Programming including support for events, properties, and persistence, have been designed to be
and Advance Java
Concepts easily read and understood by human programmers as well as by builder tools.
BeanBox
BeanBox is a utility from the JavaBeans Development Kit (BDK). Basically the
BeanBox is a test container for your JavaBeans. It is designed to allow programmers
to preview how a Bean created by user will be displayed and manipulated in a builder
tool. The BeanBox is not a builder tool.It allows programmers to preview how a bean
will be displayed and used by a builder tool.
/WEB-INF/classes/com/myBean/bean/test/ folder
package com.mybean.bean.test;
public class SimpleBean implements java.io.Serializable
{
/* Properties */
private String ename = null;
private int eage = 0;
/* Empty Constructor */
public SimpleBean() {}
/* Getter and Setter Methods */
public String getEname()
{
return ename;
}
public void setEname(String s)
{
ename = s;
}
public int getAge()
{
return eage;
}
There are two variables which hold the name and age of a employee. These variables
inside a JavaBean are called properties. These properties are private and are thus not
directly accessible by other classes. To make them accessible, methods are defined.
Compiling JavaBean
You can compile JavaBean like you compile any other Java Class file. After
compilation, a SimpleBean.class file is created and is ready for use.
Finally you can say, JavaBeans are Java classes which adhere to an extremely simple
coding convention. All you have to do is to implement java.io.Serializable interface,
96
use a public empty argument constructor and provide public methods to get and set Advance Java
the values of private variables (properties).
4.6 SUMMARY
In this unit you have learn Java JDBC are used to connect databases and work with it.
JDBC allows the integration of SQL call into a general programming environment.
Vender specific drivers are needed in JDBC programming to make a code portable.
getConnection() method of DriverManager class is used to create connection object.
By PreparedStatement similar queries can be performed in efficient way. Tuples in
ResultSet are accessed by using next () method.
Distributed programming can be done using Java RMI (Remote Methods Invocation).
Every RMI program has two sets one for client side and other for server side. Remote
interface is essentially implemented in RMI programs.
Servlets are used with web servers. The HttpServlet class is an extension of
GenericServlet that include methods for handling HTTP. HTTP request for specific
data are handled by using doGet () and doPost () methods of HttpServlet. HttpSession
objects are used to solve the problems of HTTP caused due to the stateless nature of
HTTP.
Java Beans are a new dimension in software component model. Beans provide
introspection and persistency.
4.7 SOLUTIONS/ANSWERS
d) Native Protocol (pure Java): Talks directly to the RDBMS over a network
connection using an RDBMS-specific protocol. (pure Java library that
translates JDBC requests directly to a database-specific protocol.
4)
98
Check Your Progress 3 Advance Java
1) Java servlets are more efficient, easier to use, more powerful, more portable,
and cheaper than traditional CGI than many alternative CGI-like technologies.
Efficient. With servlets, the Java Virtual Machine stays up, and each request is
handled by a lightweight Java thread, not a heavyweight operating system
process. Similarly, in traditional CGI, if there are N simultaneous requests to the
same CGI program, then the code for the CGI program is loaded into memory N
times. With servlets, however, there are N threads but only a single copy of the
servlet class.
Powerful. Java servlets let us easily do several things that are difficult or
impossible with regular CGI. For example servlets can talk directly to the Web
server (regular CGI programs can’t). This simplifies operations that need to
look up images and other data stored in standard places. Servlets can also share
data among each other, making useful things like database connection pools
easy to implement.
3) i. The doGet() method is limited with 2k of data only to be sent, but this
limitation is not with doPost() method.
ii. A request string for doGet() looks like the following:
http://www.abc.com/svt1?p1=v1&p2=v2&...&pN=vN
But doPost() method does not need a long text tail after a servlet name in a
request.
4) An HTTP Servlet handles client requests through its service method, which
supports standard HTTP client requests. The service method dispatches each
request to a method designed to handle that request.
3) The difference in Beans from typical Java classes is introspection. Tools that
recognize predefined patterns in method signatures and class definitions can
“look inside” a Bean to determine its properties and behavior. A Bean’s state
can be manipulated at the time it is being assembled as a part within a larger
application. The application assembly is referred to as design time in contrast
to run time. In order for this scheme to work, method signatures within Beans
must follow a certain pattern for introspection tools to recognize how Beans
can be manipulated, both at design time, and run time.
100