New Java Notes - 2023-2024
New Java Notes - 2023-2024
Syllabus
BASICS OF JAVA
Review of Java Fundamentals:
Java programming language was originally developed by Sun Microsystems which
was initiated by James Gosling and released in 1995 as core component of Sun
Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of
Java and its widespread popularity, multiple configurations were built to suit
various types of platforms. For example: J2EE for Enterprise Applications, J2ME for
Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively.
Java is guaranteed to be Write Once, Run Anywhere.
Java is −
Object Oriented − In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
Platform Independent − Unlike many other programming languages
including C and C++, when Java is compiled, it is not compiled into platform
specific machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
Simple − Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
Secure − With Java's secure feature it enables to develop virus-free, tamper-
free systems. Authentication techniques are based on public-key encryption.
Architecture-neutral − Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors,
with the presence of Java runtime system.
Portable − Being architecture-neutral and having no implementation
dependent aspects of the specification makes Java portable. Compiler in Java is
written in ANSI C with a clean portability boundary, which is a POSIX subset.
Robust − Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
I M.Sc(CS) Page 2
23PCSC06 Advanced Java Programming
Multithreaded − With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.
Interpreted − Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and light-weight
process.
High Performance − with the use of Just-In-Time compilers, Java enables high
performance.
Distributed − Java is designed for the distributed environment of the internet.
Dynamic − Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.
Hello World using Java Programming.
Just to give you a little excitement about Java programming, I'm going to give you a
small conventional C Programming Hello World program, You can try it using
Demo link.
publicclassMyFirstJavaProgram {
publicstaticvoidmain(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many
set-top box projects. The language, initially called 'Oak' after an oak tree that stood
outside Gosling's office, also went by the name 'Green' and ended up later being
renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write
Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).
I M.Sc(CS) Page 3
23PCSC06 Advanced Java Programming
On 8 May, 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
Tools You Will Need
For performing the examples discussed in this tutorial, you will need a Pentium 200-
MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).
You will also need the following softwares −
Linux 7.1 or Windows xp/7/8 operating system
Java JDK 8
Microsoft Notepad or any other text editor
This tutorial will provide the necessary skills to create GUI, networking, and web
applications using Java.
What is Next?
The next chapter will guide you to how you can obtain Java and its documentation.
Finally, it instructs you on how to install Java and prepare an environment to
develop Java applications.
Java - Environment Setup
Live Demo Option Online
We have set up the Java Programming environment online, so that you can compile
and execute all the available examples online. It gives you confidence in what you
are reading and enables you to verify the programs with different options. Feel free
to modify any example and execute it online.
Try the following example using Live Demo option available at the top right corner
of the below sample code box −
publicclassMyFirstJavaProgram {
publicstaticvoidmain(String []args) {
System.out.println("Hello World");
}
}
For most of the examples given in this tutorial, you will find a Try it option in our
website code sections at the top right corner that will take you to the online compiler.
So just make use of it and enjoy your learning.
Local Environment Setup
If you want to set up your own environment for Java programming language, then
this section guides you through the whole process. Please follow the steps given
below to set up your Java environment.
Java SE is available for download for free. To download click here, please download
a version compatible with your operating system.
I M.Sc(CS) Page 4
23PCSC06 Advanced Java Programming
Follow the instructions to download Java, and run the .exe to install Java on your
machine. Once you have installed Java on your machine, you would need to set
environment variables to point to correct installation directories.
Setting Up the Path for Windows 2000/XP
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, edit the 'Path' variable and add the path to the Java executable directory
at the end of it. For example, if the path is currently set
to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin.
Setting Up the Path for Windows 95/98/ME
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Edit the 'C:\autoexec.bat' file and add the following line at the end −
SET PATH=%PATH%;C:\Program Files\java\jdk\bin
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD
Environment variable PATH should be set to point to where the Java binaries have
been installed. Refer to your shell documentation if you have trouble doing this.
For example, if you use bash as your shell, then you would add the following line at
the end of your .bashrc −
export PATH=/path/to/java:$PATH'
Popular Java Editors
To write Java programs, you need a text editor. There are even more sophisticated
IDEs available in the market. The most popular ones are briefly described below −
Notepad − On Windows machine, you can use any simple text editor like
Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a
free text editor which enhanced facilities.
Netbeans − It is a Java IDE that is open-source and free which can be
downloaded from www.netbeans.org/index.html.
Eclipse − It is also a Java IDE developed by the Eclipse open-source
community and can be downloaded from www.eclipse.org.
IDE or Integrated Development Environment, provides all common tools and
facilities to aid in programming, such as source code editor, build tools and
debuggers etc.
Components and Event Handling:
The GUI in Java processes the interactions with users via mouse, keyboard and
various user controls such as button, checkbox, text field, etc. as the events. These
I M.Sc(CS) Page 5
23PCSC06 Advanced Java Programming
events are to be handled properly to implement Java as an Event-Driven
Programming.
Components in Event Handling
Events
Event Sources
Event Listeners/Handlers
Events
The events are defined as an object that describes a change in the state of a
source object.
The Java defines a number of such Event Classes
inside java.awt.event package
Some of the events are ActionEvent, MouseEvent, KeyEvent, FocusEvent,
ItemEvent and etc.
Event Sources
A source is an object that generates an event.
An event generation occurs when an internal state of that object changes in
some way.
A source must register listeners in order for the listeners to receive the
notifications about a specific type of event.
Some of the event sources are Button, CheckBox, List, Choice, Window and
etc.
Event Listeners
A listener is an object that is notified when an event occurs.
A Listener has two major requirements, it should be registered to one more
source object to receiving event notification and it must implement methods
to receive and process those notifications.
Java has defined a set of interfaces for receiving and processing the events
under the java.awt.event package.
Some of the listeners
are ActionListener, MouseListener, ItemListener, KeyListener, WindowListe
ner and etc.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassEventListenerTestextendsJFrameimplementsActionListener{
JButton button;
publicstaticvoid main(String args[]){
I M.Sc(CS) Page 6
23PCSC06 Advanced Java Programming
EventListenerTestobject=newEventListenerTest();
object.createGUI();
}
void createGUI(){
button=newJButton(" Click Me !");
setSize(300,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(button);
button.addActionListener(this);
}
publicvoid actionPerformed(ActionEvent ae){
if(ae.getSource()== button){
JOptionPane.showMessageDialog(null,"Generates an Action Event");
}
}
}
Output
I M.Sc(CS) Page 7
23PCSC06 Advanced Java Programming
A Thread is a very light-weighted process, or we can say the smallest part of the
process that allows a program to operate more efficiently by running multiple tasks
simultaneously.
In order to perform complicated tasks in the background, we used the Thread
concept in Java. All the tasks are executed without affecting the main program. In a
program or process, all the threads have their own separate path for execution, so
each thread of a process is independent.
Another benefit of using thread is that if a thread gets an exception or an error at the
time of its execution, it doesn't affect the execution of the other threads. All the
threads share a common memory and have their own stack, local variables and
program counter. When multiple threads are executed in parallel at the same time,
this process is known as Multithreading.
In a simple way, a Thread is a:
o Feature through which we can perform multiple activities within a single
process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.
Thread Model
Just like a process, a thread exists in several states. These states are as follows:
I M.Sc(CS) Page 8
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 9
23PCSC06 Advanced Java Programming
o Thread(ThreadGroup group, Runnable target, String name, long stackSize)
Runnable Interface(run() method)
The Runnable interface is required to be implemented by that class whose instances
are intended to be executed by a thread. The runnable interface gives us
the run() method to perform an action for the thread.
start() method
The method is used for starting a thread that we have newly created. It starts a new
thread with a new callstack. After executing the start() method, the thread changes
the state from New to Runnable. It executes the run() method when the thread gets
the correct time to execute it.
Let's take an example to understand how we can create a Java thread by extending
the Thread class:
ThreadExample1.java
1. // Implementing runnable interface by extending Thread class
2. public class ThreadExample1 extends Thread {
3. // run() method to perform action for thread.
4. public void run()
5. {
6. int a= 10;
7. int b=12;
8. int result = a+b;
9. System.out.println("Thread started running..");
10. System.out.println("Sum of two numbers is: "+ result);
11. }
12. public static void main( String args[] )
13. {
14. // Creating instance of the class extend Thread class
15. ThreadExample1 t1 = new ThreadExample1();
16. //calling start method to execute the run() method of the Thread class
17. t1.start();
18. }
19. }
Output:
I M.Sc(CS) Page 10
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 11
23PCSC06 Advanced Java Programming
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For
example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network
Interface Controller). A network node can have multiple NIC but each with unique
MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is
reliable but slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is
not reliable but fast. The example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communications.
Visit next page for Java socket programming.
java.net package
The java.net package can be divided into two sections:
1. A Low-Level API: It deals with the abstractions of addresses i.e. networking
identifiers, Sockets i.e. bidirectional data communication mechanism and
Interfaces i.e. network interfaces.
I M.Sc(CS) Page 12
23PCSC06 Advanced Java Programming
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e.
connections to the resource pointed by URLs.
The java.net package provides many classes to deal with networking applications in
Java. A list of these classes is given below:
o Authenticator
o CacheRequest
o CacheResponse
o ContentHandler
o CookieHandler
o CookieManager
o DatagramPacket
o DatagramSocket
o DatagramSocketImpl
o InterfaceAddress
o JarURLConnection
o MulticastSocket
o InetSocketAddress
o InetAddress
o Inet4Address
o Inet6Address
o IDN
o HttpURLConnection
o HttpCookie
o NetPermission
o NetworkInterface
o PasswordAuthentication
o Proxy
o ProxySelector
o ResponseCache
o SecureCacheResponse
o ServerSocket
o Socket
o SocketAddress
o SocketImpl
o SocketPermission
o StandardSocketOptions
o URI
I M.Sc(CS) Page 13
23PCSC06 Advanced Java Programming
o URL
o URLClassLoader
o URLConnection
o URLDecoder
o URLEncoder
o URLStreamHandler
List of interfaces available in java.net package:
o ContentHandlerFactory
o CookiePolicy
o CookieStore
o DatagramSocketImplFactory
o FileNameMap
o SocketOption<T>
o SocketOptions
o SocketImplFactory
o URLStreamHandlerFactory
o ProtocolFamily
What we will learn in Networking Tutorial
o Networking and Networking Terminology
o Socket Programming (Connection-oriented)
o URL class
o Displaying data of a webpage by URLConnection class
o InetAddress class
o DatagramSocket and DatagramPacket (Connection-less)
Media with JavaFX:
Modern world's rich internet applications must be capable to play and edit the
media files when required. JavaFX provides the media-rich API that can play audio
and video on the user's demand.
JavaFX Media API enables the users to incorporate audio and video into the rich
internet applications (RIAs). JavaFX media API can distribute the media content
across the different range of devices like TV, Mobile, Tablets and many more.
In this part of the tutorial, we will discuss the capability of JavaFX to deal with the
media files in an interactive way. For this purpose, JavaFX provides the
package javafx.scene.media that contains all the necessary
classes. javafx.scene.media contains the following classes.
1. javafx.scene.media.Media
2. javafx.scene.media.MediaPlayer
3. javafx.scene.media.MediaStatus
I M.Sc(CS) Page 14
23PCSC06 Advanced Java Programming
4. javafx.scene.media.MediaView
Media Events
The JavaFX team have designed media API to be event driven. The callback
behaviour attached with the media functions are used to handle media events.
Instead of typing code for a button via a EventHandler, a code is implemented that
responds to the triggering of the media player's OnXXXX events where XXXX is the
event name.
java.lang.Runnable functional interfaces are used as the callbacks which are
invoked when an event is encountered. When playing the media content in javafx,
we would create the Lambda expressions (java.lang.Runnable interfaces) to be set on
the onReady event. Consider the following example.
1. Media media = new Media(url);
2. MediaPlayer mediaPlayer = new MediaPlayer(media);
3. Runnable playMusic = () -> mediaPlayer.play();
4. mediaPlayer.setOnReady(playMusic);
The playMusic variable is assigned to a lambda expression. This get passed into the
Media player's setOnReady() method. The Lambda expression will get invoked
when the onReady event is encountered.
UNIT II
REMOTE METHOD INVOCATION
1.1 RMI (Remote Method Invocation)
1. Remote Method Invocation (RMI)
2. Understanding stub and skeleton
1. stub
2. skeleton
3. Requirements for the distributed applications
4. Steps to write the RMI program
5. RMI Example
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.
Understanding 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. Let's
understand the stub and skeleton objects:
stub
I M.Sc(CS) Page 15
23PCSC06 Advanced Java Programming
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:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual
Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
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.
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for
skeletons
I M.Sc(CS) Page 16
23PCSC06 Advanced Java Programming
2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects
using the rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application
RMI Example
In this example, we have followed all the 6 steps to create and run the rmi
application. The client application needs 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.
I M.Sc(CS) Page 17
23PCSC06 Advanced Java Programming
In case, you extend the UnicastRemoteObject class, you must define a constructor
that declares RemoteException.
1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AdderRemote extends UnicastRemoteObject implements Adder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }
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.
1. rmic AdderRemote
4) Start the registry service by the rmiregistry tool
Now start the registry service by using the rmiregistry tool. If you don't specify the
port number, it uses a default port number. In this example, we are using the port
number 5000.
1. rmiregistry 5000
5) Create and run the server application
Now rmi services need to be hosted in a server process.
The Naming class provides methods to get and store the remote object.
The Naming class provides 5 methods.
public static java.rmi.Remote lookup(java.lang.String) throws It returns the reference
java.rmi.NotBoundException, of the remote object.
java.net.MalformedURLException,
java.rmi.RemoteException;
I M.Sc(CS) Page 18
23PCSC06 Advanced Java Programming
1. package com.javatpoint;
2. import java.rmi.*;
3. import java.util.*;
4. interface Bank extends Remote{
5. public List<Customer> getCustomers()throws RemoteException;
6. }
I M.Sc(CS) Page 20
23PCSC06 Advanced Java Programming
In this architecture, information processing is not confined to a single machine
rather it is distributed over several independent computers.
A distributed system can be demonstrated by the client-server architecture
which forms the base for multi-tier architectures; alternatives are the broker
architecture such as CORBA, and the Service-Oriented Architecture (SOA).
There are several technology frameworks to support distributed architectures,
including .NET, J2EE, CORBA, .NET Web services, AXIS Java Web services,
and Globus Grid services.
Middleware is an infrastructure that appropriately supports the development
and execution of distributed applications. It provides a buffer between the
applications and the network.
It sits in the middle of system and manages or supports the different
components of a distributed system. Examples are transaction processing
monitors, data convertors and communication controllers etc.
Middleware as an infrastructure for distributed system
Access
1 Hides the way in which resources are accessed and the
differences in data platform.
Location
2
Hides where resources are located.
3 Technology
I M.Sc(CS) Page 21
23PCSC06 Advanced Java Programming
Migration / Relocation
4 Hide resources that may be moved to another location
which are in use.
Replication
5
Hide resources that may be copied at several location.
Concurrency
6
Hide resources that may be shared with other users.
Failure
7
Hides failure and recovery of resources from user.
Persistence
8
Hides whether a resource ( software ) is in memory or disk.
Advantages
Resource sharing − Sharing of hardware and software resources.
Openness − Flexibility of using hardware and software of different vendors.
Concurrency − Concurrent processing to enhance performance.
Scalability − Increased throughput by adding new resources.
Fault tolerance − The ability to continue in operation after a fault has occurred.
Disadvantages
Complexity − They are more complex than centralized systems.
Security − More susceptible to external attack.
Manageability − More effort required for system management.
Unpredictability − Unpredictable responses depending on the system
organization and network load.
Centralized System vs. Distributed System
Criteria Centralized system Distributed System
I M.Sc(CS) Page 22
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 23
23PCSC06 Advanced Java Programming
Used when legacy systems are migrated to client server architectures in which
legacy system acts as a server in its own right with a graphical interface
implemented on a client
A major disadvantage is that it places a heavy processing load on both the
server and the network.
Thick/Fat-client model
In thick-client model, the server is only in charge for data management. The software
on the client implements the application logic and the interactions with the system
user.
Most appropriate for new C/S systems where the capabilities of the client
system are known in advance
More complex than a thin client model especially for management. New
versions of the application have to be installed on all clients.
Advantages
Separation of responsibilities such as user interface presentation and business
logic processing.
Reusability of server components and potential for concurrency
Simplifies the design and the development of distributed applications
It makes it easy to migrate or integrate existing applications into a distributed
environment.
It also makes effective use of resources when a large number of clients are
accessing a high-performance server.
Disadvantages
Lack of heterogeneous infrastructure to deal with the requirement changes.
Security complications.
Limited server availability and reliability.
Limited testability and scalability.
Fat clients with presentation and business logic together.
Multi-Tier Architecture (n-tier Architecture)
I M.Sc(CS) Page 24
23PCSC06 Advanced Java Programming
Multi-tier architecture is a client–server architecture in which the functions such as
presentation, application processing, and data management are physically separated.
By separating an application into tiers, developers obtain the option of changing or
adding a specific layer, instead of reworking the entire application. It provides a
model by which developers can create flexible and reusable applications.
The most general use of multi-tier architecture is the three-tier architecture. A three-
tier architecture is typically composed of a presentation tier, an application tier, and
a data storage tier and may execute on a separate processor.
Presentation Tier
Presentation layer is the topmost level of the application by which users can access
directly such as webpage or Operating System GUI (Graphical User interface). The
primary function of this layer is to translate the tasks and results to something that
user can understand. It communicates with other tiers so that it places the results to
the browser/client tier and all other tiers in the network.
Application Tier (Business Logic, Logic Tier, or Middle Tier)
Application tier coordinates the application, processes the commands, makes logical
decisions, evaluation, and performs calculations. It controls an application’s
functionality by performing detailed processing. It also moves and processes data
between the two surrounding layers.
Data Tier
In this layer, information is stored and retrieved from the database or file system.
The information is then passed back for processing and then back to the user. It
includes the data persistence mechanisms (database servers, file shares, etc.) and
provides API (Application Programming Interface) to the application tier which
provides methods of managing the stored data.
I M.Sc(CS) Page 25
23PCSC06 Advanced Java Programming
Advantages
Better performance than a thin-client approach and is simpler to manage than
a thick-client approach.
Enhances the reusability and scalability − as demands increase, extra servers
can be added.
Provides multi-threading support and also reduces network traffic.
Provides maintainability and flexibility
Disadvantages
Unsatisfactory Testability due to lack of testing tools.
More critical server reliability and availability.
Broker Architectural Style
Broker Architectural Style is a middleware architecture used in distributed
computing to coordinate and enable the communication between registered servers
and clients. Here, object communication takes place through a middleware system
called an object request broker (software bus).
Client and the server do not interact with each other directly. Client and server
have a direct connection to its proxy which communicates with the mediator-
broker.
A server provides services by registering and publishing their interfaces with
the broker and clients can request the services from the broker statically or
dynamically by look-up.
CORBA (Common Object Request Broker Architecture) is a good
implementation example of the broker architecture.
Components of Broker Architectural Style
The components of broker architectural style are discussed through following heads
Broker
I M.Sc(CS) Page 26
23PCSC06 Advanced Java Programming
Broker is responsible for coordinating communication, such as forwarding and
dispatching the results and exceptions. It can be either an invocation-oriented
service, a document or message - oriented broker to which clients send a message.
It is responsible for brokering the service requests, locating a proper server,
transmitting requests, and sending responses back to clients.
It retains the servers’ registration information including their functionality and
services as well as location information.
It provides APIs for clients to request, servers to respond, registering or
unregistering server components, transferring messages, and locating servers.
Stub
Stubs are generated at the static compilation time and then deployed to the client
side which is used as a proxy for the client. Client-side proxy acts as a mediator
between the client and the broker and provides additional transparency between
them and the client; a remote object appears like a local one.
The proxy hides the IPC (inter-process communication) at protocol level and
performs marshaling of parameter values and un-marshaling of results from the
server.
Skeleton
Skeleton is generated by the service interface compilation and then deployed to the
server side, which is used as a proxy for the server. Server-side proxy encapsulates
low-level system-specific networking functions and provides high-level APIs to
mediate between the server and the broker.
It receives the requests, unpacks the requests, unmarshals the method arguments,
calls the suitable service, and also marshals the result before sending it back to the
client.
Bridge
A bridge can connect two different networks based on different communication
protocols. It mediates different brokers including DCOM, .NET remote, and Java
CORBA brokers.
Bridges are optional component, which hides the implementation details when two
brokers interoperate and take requests and parameters in one format and translate
them to another format.
I M.Sc(CS) Page 27
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 28
23PCSC06 Advanced Java Programming
Features of SOA
A service-oriented architecture provides the following features −
Distributed Deployment − Expose enterprise data and business logic as
loosely, coupled, discoverable, structured, standard-based, coarse-grained,
stateless units of functionality called services.
Composability − Assemble new processes from existing services that are
exposed at a desired granularity through well defined, published, and
standard complaint interfaces.
Interoperability − Share capabilities and reuse shared services across a
network irrespective of underlying protocols or implementation technology.
Reusability − Choose a service provider and access to existing resources
exposed as services.
SOA Operation
The following figure illustrates how does SOA operate −
Advantages
I M.Sc(CS) Page 29
23PCSC06 Advanced Java Programming
Loose coupling of service–orientation provides great flexibility for enterprises
to make use of all available service recourses irrespective of platform and
technology restrictions.
Each service component is independent from other services due to the stateless
service feature.
The implementation of a service will not affect the application of the service as
long as the exposed interface is not changed.
A client or any service can access other services regardless of their platform,
technology, vendors, or language implementations.
Reusability of assets and services since clients of a service only need to know
its public interfaces, service composition.
SOA based business application development are much more efficient in terms
of time and cost.
Enhances the scalability and provide standard connection between systems.
Efficient and effective usage of ‘Business Services’.
Integration becomes much easier and improved intrinsic interoperability.
Abstract complexity for developers and energize business processes closer to
end users.
Defining Remote objects:
RMI stands for Remote Method Invocation. It is a mechanism that allows an object
residing in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication
between Java programs. It is provided in the package java.rmi.
Architecture of an RMI Application
In an RMI application, we write two programs, a server program (resides on the
server) and a client program (resides on the client).
Inside the server program, a remote object is created and reference of that
object is made available for the client (using the registry).
The client program requests the remote objects on the server and tries to
invoke its methods.
The following diagram shows the architecture of an RMI application.
I M.Sc(CS) Page 30
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 31
23PCSC06 Advanced Java Programming
At the server side, the packed parameters are unbundled and then the required
method is invoked. This process is known as unmarshalling.
RMI Registry
RMI registry is a namespace on which all server objects are placed. Each time the
server creates an object, it registers this object with the RMIregistry
(using bind() or reBind() methods). These are registered using a unique name
known as bind name.
To invoke a remote object, the client needs a reference of that object. At that time, the
client fetches the object from the registry using its bind name
(using lookup() method).
The following illustration explains the entire process −
Goals of RMI
Following are the goals of RMI −
To minimize the complexity of the application.
To preserve type safety.
Distributed garbage collection.
Minimize the difference between working with local and remote objects.
Serialization and Deserialization in Java
1.Serialization
2.Serializable Interface
3.Example of Serialization
4.Example of Deserialization
5.Serialization with Inheritance
6.Externalizable interface
7.Serialization and static data member
I M.Sc(CS) Page 32
23PCSC06 Advanced Java Programming
Serialization in Java:
It is a mechanism of writing the state of an object into a byte-stream. It is mainly
used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is
converted into an object. The serialization and deserialization process is platform-
independent, it means you can serialize an object on one platform and deserialize it
on a different platform.
Forserializingthebject,wecall the writeObject() method of ObjectOutputStream class,
and for deserialization we call the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
Advantages of Java Serialization
It is mainly used to travel object's state on the network (that is known as
marshalling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to
"mark" Java classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.
The Serializable interface must be implemented by the class whose object needs to
be persisted.
The String class and all the wrapper classes implement
the java.io.Serializable interface by default.
Let's see the example given below:
Student.java
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
I M.Sc(CS) Page 33
23PCSC06 Advanced Java Programming
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
In the above example, Student class implements Serializable interface. Now its
objects can be converted into stream. The main class implementation of is showed in
the next code.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects
to an OutputStream. Only objects that support the java.io.Serializable interface can
be written to streams.
Building distributed applications is difficult because you must take into account
several issues, such as partial failure, increased latency, distributed persistence, and
language compatibility.
The JavaSpaces technology is a simple and powerful high-level tool for building
distributed and collaborative applications. Based on the concept of shared network-
based space that serves as both object storage and exchange area, it provides a
simple API that is easy to learn and yet expressive for building sophisticated
distributed applications.
This article provides a fast-track tutorial to the JavaSpaces technology, including
An introduction to distributed computing
An introduction to the JavaSpaces technology
A comparison of JavaSpaces technology and databases
A description of JavaSpaces services and operations
The JavaSpaces technology application model
The JavaSpaces technology programming model
A flavor of the effort involved in developing applications using JavaSpaces
technology
Distributed Computing
Distributed computing is about building network-based applications as a set of
processes that are distributed across a network of computing nodes (or hosts) that
work together to solve a problem. The advantages of building applications using this
approach are many, including performance, resource sharing, scalability, and fault
tolerance. But using distributed technologies does not guarantee these advantages.
The developer must take special care in the design and implementation or
distributed applications in order to achieve such benefits.
I M.Sc(CS) Page 34
23PCSC06 Advanced Java Programming
The network environments on top of which you build distributed applications
introduce complexities that are not of concern when you write stand-alone
applications. The most obvious complexity is the varied architecture of machines.
However, Java technology's platform independence and its virtual machine allow for
applications that you write once and run anywhere. Other issues that have
significant impact on designing and implementing distributed applications include
latency, synchronization, and partial failure.
Several technologies can be used to build distributed applications, including low-
level sockets, message passing, and remote method invocation (RMI). The
JavaSpaces technology model is different in that it provides persistent object
exchange areas (or spaces) through which remote Java technology processes
coordinate actions and exchange data. Such an approach can simplify the design and
implementation of sophisticated distributed applications, and it enables you to deal
with the challenges of designing and implementing distributed applications.
The JavaSpaces Technology
The JavaSpaces technology is a high-level tool for building distributed applications,
and it can also be used as a coordination tool. A marked departure from classic
distributed models that rely on message passing or RMI, the JavaSpaces model
views a distributed application as a collection of processes that cooperate through
the flow of objects into and out of one or more spaces. This programming model has
its roots in Linda, a coordination language developed by Dr. David Gelernter at Yale
University. However, no knowledge of Linda is required to understand and use
JavaSpaces technology.
The JavaSpaces service specification lists the following design goals for the
JavaSpaces technology:
It should provide a platform that simplifies the design and implementation of
distributed computing systems.
The client side should have few classes, both to keep the client simple and to speed
the downloading of client classes.
The client side should have a small footprint because it will run on computers with
limited local memory.
A variety of implementations should be possible.
It should be possible to create a replicated JavaSpaces service.
JavaSpaces Technology vs. Databases
As mentioned earlier, a space is a shared network-accessible repository for objects:
The data you can store there is persistent and later searchable. But a JavaSpaces
service is not a relational or object database. JavaSpaces services are not used
I M.Sc(CS) Page 35
23PCSC06 Advanced Java Programming
primarily as data repositories. They are designed for a different purpose than either
relational or object databases.
Although a JavaSpaces service functions somewhat like a file system and somewhat
like a database, it is neither. The key differences between JavaSpaces technology and
databases are the following:
Relational databases understand the data they store and manipulate it directly
through query languages such as SQL. JavaSpaces services, on the other hand,
store entries that they understand only by type and the serialized form of each
field. As a result, there are no general queries in the JavaSpaces application design,
only "exact match" or "don't care" for a given field.
Object databases provide an object-oriented image of stored data that can be
modified and used, almost as if it were transient memory. JavaSpaces systems do
not provide a nearly transparent persistent or transient layer, and they work only
on copies of entries.
JavaSpaces Services and Operations
Application components (or processes) use the persistent storage of a space to store
objects and to communicate. The components coordinate actions by exchanging
objects through spaces; the objects do not communicate directly. Processes interact
with a space through a simple set of operations.
You can invoke four primary operations on a JavaSpaces service:
write(): Writes new objects into a space
take(): Retrieves objects from a space
read(): Makes a copy of objects in a space
notify: Notifies a specified object when entries that match the given template are
written into a space
Both the read() and take() methods have variants: readIfExists() and takeIfExists(). If
they are called with a zero timeout, then they are equivalent to their counterpart. The
timeout parameter comes into effect only when a transaction is used.
Each operation has parameters that are entries. Some are templates, which are a kind
of entry. The write() operation is a store operation. The read() and take() operations
are a combination of search and fetch operations. The notify method sets up repeated
search operations as entries are written to the space. If a take() or read() operation
doesn't find an object, the process can wait until an object arrives.
Unlike conventional object stores, objects are passive data. Therefore, processes do
not modify objects in the space or invoke their methods directly. In order to modify
an object, a process must explicitly remove, update, and reinsert it into the space.
How can we build sophisticated distributed applications with only a handful of
operations? The space itself provides a set of key features.
I M.Sc(CS) Page 36
23PCSC06 Advanced Java Programming
The JavaSpaces Technology Application Model
A JavaSpaces service holds entries, each of which is a typed group of objects
expressed in a class that implements the interface net.jini.core.entry.Entry. Once an
entry is written into a JavaSpaces service, it can be used in future look-up operations.
Looking up entries is performed using templates, which are entry objects that have
some or all of their fields set to specified values that must be matched exactly. All
remaining fields, which are not used in the lookup, are left as wildcards.
There are two look-up operations: read() and take(). The read() method returns
either an entry that matches the template or an indication that no match was found.
The take() method operates like read(), but if a match is found, the entry is removed
from the space. Distributed events can be used by requesting a JavaSpaces service to
notify you when an entry that matches the specified template is written into the
space. Note that each entry in the space can be taken at most once, but two or more
entries may have the exact same values.
Using JavaSpaces technology, distributed applications are modeled as a flow of
objects between participants, which is different from classic distributed models such
as RMIs. Figure 1 indicates what a JavaSpaces technology-based application looks
like.
I M.Sc(CS) Page 37
23PCSC06 Advanced Java Programming
the operations take place. Notifications go to event catches, which can be either
clients or proxies for clients.
To get a flavor of how to implement distributed applications using a handful of
JavaSpaces operations, consider a multiuser chat system. All the messages that make
up the discussion are written to a space that acts as a chat area. Participants write
message objects into the space, while other members wait for new message objects to
appear, then read them out and display their contents. The list of participants can be
kept in the space and updated whenever someone joins or leaves the discussion.
Because the space is persistent, a new member can read and view the entire
discussion.
You can implement such a multiuser chat system in RMI by creating remote
interfaces for the interactions discussed. But by using JavaSpaces technology, you
need only one interface.
The JavaSpaces Technology Programming Model
All operations are invoked on an object that implements
the net.jini.space.JavaSpace interface. A space stores entries, each of which is a
collection of typed objects that implements the Entry interface. Code Sample 1 shows
a MessageEntry that contains one field: content, which is null by default.
Information on how to compile and run the sample application appears later in this
article.
Code Sample 1: MessageEntry.java
Copy
Copied to Clipboard
Error: Could not Copy
import net.jini.core.entry.*;
public class MessageEntry implements Entry {
public String content;
public MessageEntry() {
}
public MessageEntry(String content) {
this.content = content;
}
public String toString() {
return "MessageContent: " + content;
}
}
MessageEntryspace
Copy
I M.Sc(CS) Page 38
23PCSC06 Advanced Java Programming
Copied to Clipboard
Error: Could not Copy
JavaSpace space = getSpace();
MessageEntry msg = new MessageEntry();
msg.content = "Hello there";
space.write(msg, null, Lease.FOREVER);
nullTransaction
The write() operation places a copy of an entry into the given JavaSpace service, and
the Entry passed is not affected by the operation. Each write() operation places a
new Entry into the space even if the same Entry object is used in more than
one write().
Entries written in a space are governed by a renewable lease. If you like, you can
change the lease (when the write() operation is invoked) to one hour as follows: >
space.write(msg, null, 60 * 60 * 1000);
write()Lease
Once the entry exists in the space, any process with access to the space can perform
a read() on it. To read an entry, a template is used, which is an entry that may have
one or more of its fields set to null. An entry matches a template if (a) the entry has
the same type as or is a subtype of the template and (b) if for every specified non-
null field in the template, their fields match exactly. The null fields act as wildcards
and match any value. The following code segment shows how to create a template
and perform a read() on the space:
Copy
Copied to Clipboard
Error: Could not Copy
MessageEntry template = new MessageEntry();
MessageEntry output = (MessageEntry) space.read(template, null,
Long.MAX_VALUE);
null MessageEntry Long.MAX_VALUE read() take() readIfExists()
Code Sample 2 shows the client that discovers the JavaSpace service, writes a
message into the space, and then reads it. Instructions on how to compile and run
this sample application appear later in this article.
Code Sample 2: SpaceClient.java
Copy
Copied to Clipboard
Error: Could not Copy
import net.jini.space.JavaSpace;
public class SpaceClient {
I M.Sc(CS) Page 39
23PCSC06 Advanced Java Programming
public static void main(String argv[]) {
try {
MessageEntry msg = new MessageEntry();
msg.content = "Hello there";
System.out.println("Searching for a JavaSpace...");
Lookup finder = new Lookup(JavaSpace.class);
JavaSpace space = (JavaSpace) finder.getService();
System.out.println("A JavaSpace has been discovered.");
System.out.println("Writing a message into the space...");
space.write(msg, null, 60*60*1000);
MessageEntry template = new MessageEntry();
System.out.println("Reading a message from the space...");
MessageEntry result = (MessageEntry) space.read(template, null,
Long.MAX_VALUE);
System.out.println("The message read is: "+result.content);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Transactions
The JavaSpaces API uses the package net.jini.core.transaction to provide basic atomic
transactions that group multiple operations across multiple JavaSpaces services into
a bundle that acts as a single atomic operation. Either all modifications within the
transactions will be applied or none will, regardless of whether the transaction spans
one or more operations or one or more JavaSpaces services. Note that transactions
can span multiple spaces and participants in general.
A read(), write(), or take() operation that has a null transaction acts as if it were in a
committed transaction that contained that operation. As an example, a take() with
a null transaction parameter performs as if a transaction was created, the take() was
performed under that transaction, and then the transaction was committed.
The Jini Outrigger JavaSpaces Service
The Jini Technology Starter Kit comes with the package com.sun.jini.outrigger,
which provides an implementation of a JavaSpaces technology-enabled service. You
can run it two ways:
As a transient space that loses its state between executions:
Use com.sun.jini.outrigger.TransientOutriggerImpl.
I M.Sc(CS) Page 40
23PCSC06 Advanced Java Programming
As a persistent space that maintains state between executions:
Use com.sun.jini.outrigger.PersistentOutriggerImpl.
TransientOutriggerImplPersistentOutriggerImpl
Compiling and Running the SpaceClient Application
To compile and run the sample application in this article, do the following:
1. Compile the code in Code Sample 1 ( MessageEntry.java) using javac as follows:
prompt> javac -classpath <pathToJiniInstallation\lib\jini-ext.jar> MessageEntry.java
Note that you need to include the JAR file jini-ext.jar in your classpath. This JAR file
comes with the starter kit and is in the lib directory of your installation.
2. Compile the code in Code Sample 2 ( SpaceClient.java). Note that this code makes
use of a utility class called Lookup to locate or discover a JavaSpace space. Therefore,
before you compile SpaceClient.java, you should download Lookup.java and then
compile both classes using javac as shown in step 2. Note that you should include
the directory that contains MessageEntry.class in your classpath when
compiling SpaceClient.java.
3. Run Launch-All, which is in the installverify directory of your Jini installation
directory. This will start a service browser (as shown in Figure 2) and six contributed
Jini network technology services, one of which is the JavaSpace service.
I M.Sc(CS) Page 41
23PCSC06 Advanced Java Programming
UNIT III
DATABASE
JDBC - Introduction
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
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.
I M.Sc(CS) Page 42
23PCSC06 Advanced Java Programming
JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.
Pre-Requisite
Before moving further, you need to have a good understanding of the following two
subjects −
Core JAVA Programming
SQL or MySQL Database
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 −
I M.Sc(CS) Page 43
23PCSC06 Advanced Java Programming
using communication sub protocol. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
Driver − This interface handles the communications with the database server.
You will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts the
details associated with working with Driver objects.
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.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest
JDBC version at the time of writing this tutorial. It offers the main classes for
interacting with your data sources.
The new features in these packages include changes in the following areas −
Automatic database driver loading.
Exception handling improvements.
Enhanced BLOB/CLOB functionality.
Connection and statement interface enhancements.
National character set support.
SQL ROWID access.
SQL 2003 XML data type support.
Annotations.
Database access:
JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC
( Open Database Connectivity ). JDBC is a standard API specification developed in
order to move data from the front end to the back end. This API consists of classes
and interfaces written in Java. It basically acts as an interface (not the one we use in
Java) or channel between your Java program and databases i.e it establishes a link
between the two so that a programmer can send data from Java code and store it in
the database for future use.
I M.Sc(CS) Page 44
23PCSC06 Advanced Java Programming
Illustration: Working of JDBC co-relating with real-time
I M.Sc(CS) Page 45
23PCSC06 Advanced Java Programming
Let us discuss these steps in brief before implementing by writing suitable code to
illustrate connectivity steps for JDBC.
Step 1: Import the Packages
Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before using it
in the program. Registration is to be done once in your program. You can register a
driver in one of two ways mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of using
new or create objects. The following example uses Class.forName() to load the
Oracle driver as shown below as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connectioncon=DriverManager.getConnection(url,user,password)
I M.Sc(CS) Page 46
23PCSC06 Advanced Java Programming
user: Username from which your SQL command prompt can be accessed.
password: password from which the SQL command prompt can be accessed.
con: It is a reference to the Connection interface.
Url: Uniform Resource Locator which is created as shown below:
Stringurl=“jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used, @localhost is the IP
Address where a database is stored, 1521 is the port number and xe is the service
provider. All 3 parameters above are of String type and are to be declared by the
programmer before calling the function. Use of this can be referred to form the final
code.
Step 4: Create a statement
Once a connection is established you can interact with the database. The
JDBCStatement, CallableStatement, and PreparedStatement interfaces define the
methods that enable you to send SQL commands and receive data from your
database.
Use of JDBC Statement is as follows:
Statementst=con.createStatement();
Note: Here, con is a reference to Connection interface used in previous step .
Step 5: Execute the query
Now comes the most important part i.e executing the query. The query here is an
SQL Query. Now we know we can have multiple types of queries. Some of them
are as follows:
The query for updating/inserting a table in a database.
The query for retrieving data.
The executeQuery() method of the Statement interface is used to execute queries of
retrieving values from the database. This method returns the object of ResultSet
that can be used to get all the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to execute
queries of updating/inserting.
Pseudo Code:
intm=st.executeUpdate(sql);
if(m==1)
System.out.println("insertedsuccessfully:"+sql);
else
System.out.println("insertion failed");
Here sql is SQL query of the type String:
Java
I M.Sc(CS) Page 47
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 48
23PCSC06 Advanced Java Programming
Output:
// Importing database
importjava.sql.*;
// Importing required classes
importjava.util.*;
// Main class
classMain {
I M.Sc(CS) Page 49
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 50
23PCSC06 Advanced Java Programming
database search
In order to deal with JDBC standard 7 steps are supposed to be followed:
1. Import the database
2. Load and register drivers
3. Create a connection
4. Create a statement
5. Execute the query
6. Process the results
7. Close the connection
I M.Sc(CS) Page 51
23PCSC06 Advanced Java Programming
Procedure:
1. Import the database-syntax for importing the sql database in java is-
import java.sql.* ;
2. Load and register drivers-syntax for registering drivers after the loading of
driver class is
forName(com.mysql.jdbc.xyz) ;
3. Creating a database irrespective of SQL or NoSQL. Creating a database
using sqlyog and creating some tables in it and fill data inside it in order to
search for the contents of a table. For example, the database is named as
“hotelman” and table names are “cuslogin” and “adminlogin”.
4. Create a connection: Open any IDE where the java executable file can be
generated following the standard methods. Creating a package further creating
the class. Inside the package, open a new java file and type the below code for
JDBC connectivity and save the filename with connection.java.
5. Searching content in a table, let’s suppose my “cuslogin” table has columns
namely “id”, “name”, “email”, “password” and we want to search the customer
whose id is 1.
6. Initialize a string with the SQL query as follows
String sql="select * from cuslogin where id=1";
If we want to search for any id in general, then the SQL query becomes
String sql="select * from cuslogin where id="+Integer.parseInt(textfield.getText());
The textfield is the area(in Jframe form) where the user types the id he wants to
search in the “cuslogin” table.
4.1: Initialize the below objects of Connection class, PreparedStatement class, and
ResultSet class(needed for JDBC) and connect with the database as follows
I M.Sc(CS) Page 52
23PCSC06 Advanced Java Programming
Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
con = connection.connectDB();
4.2: Now, add the SQL query of step 3.1 inside prepareStatement and execute it as
follows:
p =con.prepareStatement(sql);
rs =p.executeQuery();
4.3: We check if rs.next() is not null, then we display the details of that particular
customer present in “cuslogin” table
4.4: Open a new java file (here, its result.java) inside the same package and type the
full code (shown below) for searching the details of the customer whose id is 1,
from table “cuslogin”.
Note: both the file viz result.java and connection.java should be inside the same
package, else the program won’t give desired output!!
Implementation:
Example 1
Connection class of JDBC by making an object to be invoked in main(App) java
program below in 1B
Java
publicclassconnectionDB {
finalString DB_URL
= "jdbc:mysql://localhost:3306/testDB?useSSL=false";
// Database credentials
I M.Sc(CS) Page 53
23PCSC06 Advanced Java Programming
// 1. Root
finalString USER = "root";
I M.Sc(CS) Page 54
23PCSC06 Advanced Java Programming
App/Main Class where the program is compiled and run calling the above
connection class object
Java
// Main class
// It's connection class is shown above
publicclassGFG {
I M.Sc(CS) Page 55
23PCSC06 Advanced Java Programming
intid = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
String password = rs.getString("password");
I M.Sc(CS) Page 56
23PCSC06 Advanced Java Programming
Multimedia Databases:
The multimedia databases are used to store multimedia data such as images,
animation, audio, video along with text. This data is stored in the form of multiple
file types like .txt(text), .jpg(images), .swf(videos), .mp3(audio) etc.
I M.Sc(CS) Page 57
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 58
23PCSC06 Advanced Java Programming
Data is very important in Web App Development. With the help of a database, you can store
data safely and can access the data that is stored in the database.
Written by RamotionAug 9, 202221 min read
Last updated: Aug 22, 2023
Table of Contents
1. Role of Database in Web Application
2. Why Do Web App Developers Need a Database?
3. Types of Databases in Web Application
4. List of Popular Web App Databases
5. How to Connect Database to Web Application
6. Conclusion
Database plays a critical role in web app development. It is one of the most important aspects
of building an application. It is necessary that you have a piece of good knowledge of
databases before using them in your application. Database design plays a key role in the
operation of your website and provides you with information regarding transactions, data
integrity, and security issues. In this article, you will learn the role of databases in web
application development. You will also learn about the most popular web app databases and
how to connect databases to the web applications.
What is Database?
The term "database" was coined by Peter Naur in 1960 to describe his approach to
developing software systems. Naur produced a definition that stated, "A file may be
regarded as a logical record of facts or ideas, whereas a database contains information
organized so that it can be used readily and flexibly."
In the early days of computing, databases were synonymous with files on disk. The term is
still commonly used this way for example when people refer to their hard drive as their
"main database".
Data is the foundation of a web application. It is used to store user information, session data,
and other application data. The database is the central repository for all of this data. Web
applications use a variety of databases to store data such as flat files, relational databases,
object-relational databases, and NoSQL databases. Each type of database has its own
advantages and disadvantages when it comes to storing and retrieving data.
I M.Sc(CS) Page 59
23PCSC06 Advanced Java Programming
A database is a collection of data and information that is stored in an organized manner for
easy retrieval. The primary purpose of a database is to store, retrieve, and update
information. A database can be used to store data related to any aspect of business
operations.
Databases can be very large, containing millions of records, or very small, containing just a
few records or even a single record. They may be stored on hard disks or other media, or
they may exist only in memory. In the early days of computing, databases were stored on
tape drives or punch cards. Today they're stored on hard drives, flash memory cards, and
other media.
Databases are designed to ensure that the data they contain is organized and easily
retrievable. A database management system (DBMS) is the software used to create and
maintain a database.
Role of Database in Web Application
Web application development agency, developers, and designers use databases to store and
organize the data that their applications need. The role of databases in web application
development has increased over time. As a result, a number of developers create applications
that use databases. You can't fully understand web application development without
understanding the role of databases. A database is nothing but an organized collection of
data that helps us, whether creating or modifying any program. Some examples of this kind
of organization are the bookshelf, the NAS storage, and even databases on your desktop
computers!
The role of databases in a web application is very important. The web application interacts
with the database to store data and retrieve data from it. The database is used to store all the
information that the user needs to store. For example, if you are developing a shopping cart
website then it will contain product details, customer details, order details, etc. In this case,
you need to store this information in a database so that we can use them later on.
Why Do Web App Developers Need a Database?
I M.Sc(CS) Page 60
23PCSC06 Advanced Java Programming
The first thing one should know when it comes to databases is the need. There are huge
numbers of businesses out there, whose revenue depends on the success and future of their
database. You see, a database is extremely important for online companies and businesses as
well. These days databases are used for various purposes like managing financial records,
setting up customer profiles, keeping inventory and ordering information, etc. But what does
all this mean?
Most modern web applications are based on a database. The database stores information
about the users, products, orders, and more. A database is an important component of any
web application because it provides a central location for storing user information and
business logic. In addition to this, it allows you to store complex data structures with
minimal effort.
Databases are used by businesses to collect and store customer information, financial records,
and inventory data. They're also used in research projects to store information about
experiments or tests. For example, if you were conducting a survey on the habits of people
who eat cereal for breakfast, you might use a database to keep track of your results.
Databases are also used by government agencies to store public records like birth certificates
and marriage licenses. Databases are also used by medical researchers who need to record
the medical history of patients in order to determine how effective certain treatments may be
for different diseases or conditions.
Web Application Databases Offer Benefits
Web applications are becoming more and more popular because they allow users to access
information from different devices at the same time. A web application database offers
benefits such as:
Security
A web application database provides security features such as encryption and password
protection. If a user’s password becomes lost or compromised, it will not be possible for
someone else to access the information stored in the database.
Accessibility
Users can access their data from any internet-enabled device, which includes smartphones
and tablets as well as laptops and desktops. This means that users do not have to worry
about losing their valuable data because it is stored on another device.
Reliability and scalability
Web applications are usually accessed by many users simultaneously, unlike traditional
desktop applications that are accessed by one person at a time, so web apps need to be able
to handle more requests simultaneously than their desktop counterparts. Web application
databases use distributed architecture (multiple servers) to scale up quickly when demand
increases, so they can handle large numbers of simultaneous requests without slowing down
or crashing.
I M.Sc(CS) Page 61
23PCSC06 Advanced Java Programming
Ease of maintenance for IT staff
Because web application databases use distributed architecture, problems can be isolated
and fixed quickly, which reduces downtime for the end user and reduces costs for IT staffs
responsible for maintaining the system. Also, with database automation tools we can make
database tasks easier and safer.
Types of Databases in Web Application
A database is a collection of records, each of which is similar to other records in the same
database. There are two types of databases: relational and non-relational. Relational
databases are built on the principles of tabular data, which means there has to be a one-to-
one relationship between the columns and rows in the table. A non-Relational Database is
also known as NoSQL Database.
Relational
A database is a large collection of structured data, which can be accessed to find specific
information. Relational databases are famous for their structure and have been used by
programmers for years.
A relational database is data storage that maintains a relationship between two or more
entities. It is used whenever you want to store information in a way that it can be retrieved by
your application. In general, we can say that a relational database is a data storage structure
where each tuple on its own occupies one record and consists of values of attributes.
There are many advantages of using relational databases over other databases. Apart from
this, there are also some disadvantages associated with using these databases which need
careful consideration before employing them for storing your data.
Advantages
The main advantages of relational databases include:
Data integrity. A correctly implemented relational database ensures that all data entered
remains accurate, complete, and consistent over time. This helps ensure that all users have
access to the most up-to-date data possible at any given moment without having to worry
about whether it will still be there when they need it later on down the line.
They're easy to use. Relational databases are designed to be easy to understand and use. The
relationships between all the tables and data elements are clearly defined, making it easy to
understand how they work together. This makes it easier for people with little or no database
experience to understand how to use them without having to learn an entirely new
language.
I M.Sc(CS) Page 62
23PCSC06 Advanced Java Programming
Scalability. Relational databases scale easily from small applications up to large enterprise
systems. You can add more disk space and memory resources when needed without taking
down your application or disrupting end users. This makes relational databases ideal for
large-scale applications, such as data warehouses or customer relationship management
systems.
High availability and disaster recovery capabilities. Relational databases provide
automated backup capabilities that allow you to recover quickly from hardware failures or
other disasters without requiring human intervention or manual restoration procedures. This
makes relational databases ideal for mission-critical applications where downtime is not an
option.
Disadvantages
Not suitable for real-time data analysis. Relational databases can't be used for real-time data
analysis because they don't store the data in such a way that it can be queried quickly. This
means that if you want to analyze your data in real-time, you need a technology other than
Relational databases. A good example is NoSQL which is more suitable for real-time analysis
because it stores data in a different manner than relational databases do.
The inability to store documents or graphs in their native format. This means that you
need to transform your data into tabular format before storing it. This can be very
inconvenient if you want to query your data in a different way than what is supported by the
database engine itself (for example, by using SQL or Structured Query Language).
Not very good at storing sparse data (i.e., large empty spaces). For example, if you want to
store all email addresses from your customers and only non-empty addresses are stored,
then this will take up a lot of space compared to storing every single email address even if it's
empty (the latter would take less space).
Relational databases have a fixed schema. You cannot change the structure of the database
during its lifetime, this is called fixed schema. This can limit your ability to add new features
or change existing ones. For example, if you want to add a new column for an existing table
in a relational database, you will have to re-write all queries that use this table and also
update all other tables that reference this table. This can be time-consuming and error-prone.
Non-Relational
Non-relational databases (sometimes called object-oriented databases) are very different
from Relational databases. The term non-relational (or NoSQL) database describes any kind
of database in which there is no strict distinction between relations, rows, and columns. The
term non-relational comes from the fact that the objects stored within the databases are not
based on relationships (also called joins), but rather are based on an implicit, often
unstructured structure. Non-relational databases exist mainly to help solve problems relating
to responsiveness, scalability, and performance.
I M.Sc(CS) Page 63
23PCSC06 Advanced Java Programming
Non-relational databases (or NoSQL) is a class of database management systems that were
designed to be more flexible than a relational database. The main reason is that they are
disconnected from the original data structure and don't use the traditional relationships
between tables in database design which makes them easier to organize, manage, and access.
Advantages
Speed. The most obvious advantage of non-relational databases is that they can be extremely
fast. Non-relational databases can do things that would take too long in a relational database,
such as searching every record or even all records on disk, without having to query the
database first.
Simplicity. Non-relational databases are generally easier to understand and use than
relational ones, making them ideal for smaller projects where there aren't many users or
developers working with the data at any given time. NoSQL databases might not be ideal for
complex projects.
Scalability. Because they are not constrained by the schema, non-relational databases can
scale more easily than relational databases. You can add more hardware and therefore more
nodes, which increases the overall performance of the system. This is particularly useful
when you need to perform complex computations on large amounts of data.
Data can be stored in any format necessary for the application. For example, if your
application requires XML documents, then you can store them in an XML column instead of
forcing them into a table schema.
The processing time for queries is faster in some cases because there is no need to traverse
through multiple tables or join across multiple databases like with relational databases.
Disadvantages
No standardization. Each vendor has its own APIs and features, making it challenging to
implement cross-platform applications.
Some non-relational databases (especially those used for big data) have problems dealing
with large amounts of data at once because they don't have good query optimization
algorithms built into them as relational databases do.
A non-relational database doesn't have a fixed structure like a relational database, so you'll
need to write code that can handle the unexpected — for example, you might have to write
code that handles different field lengths depending on what kind of data is being stored. This
can make it harder to maintain your application, especially if it's being used by other people
who aren't aware of these differences.
The biggest disadvantage of non-relational databases is that they don't support ACID
transactions. In other words, to update data in a non-relational database, you need to
perform multiple queries and then combine them together. The other problem is that these
databases are not compatible with each other, so it's difficult to integrate them into a single
system.
I M.Sc(CS) Page 64
23PCSC06 Advanced Java Programming
Graph Databases (NoSQL)
Graph databases are a relatively new type of database that is able to store and query complex
relationships between entities. Graph databases have been around for many years, but have
recently become popular as large-scale applications like Facebook and LinkedIn have
adopted them.
I M.Sc(CS) Page 65
23PCSC06 Advanced Java Programming
They are relatively new. Many organizations have already invested heavily in relational or
document-oriented databases and may not want to throw away all that investment. In
addition, some organizations may not need the power of a graph database because their data
can be modeled using other types of databases.
List of Popular Web App Databases
Many different types of databases exist, with different features and capabilities. Some
databases are relational (or SQL-based), while others are non-relational (NoSQL). These are
the best databases for web applications. Depending upon your needs choose a right database
to build your software appplications.
MySQL (Relational)
MySQL is a relational database management system (RDBMS) based on SQL. It is a popular
database server, and a multi-user, multi-threaded SQL database. MySQL is developed by
Oracle Corporation. The name "MySQL" is a play on the name of co-founder Michael
Widenius's earlier project, Monty Python's Flying Circus. It is written in C and C++
programming languages, with some elements written in Java. It has been licensed under
GPLv2 since 2004, but it can be used under the terms of the GNU Affero General Public
License.
MySQL database is often used for data storage, especially in web applications, and it is also
widely used for creating and maintaining relational database tables. MySQL is owned by
Oracle Corporation and was developed by a Swedish company called MySQL AB, which
was bought by Sun Microsystems in 2008. As of 2009, the project is managed by Oracle
Corporation.
It has become the most popular open source and best database software in the world, used
on the web and mobile applications, by corporations large and small and across all
industries.
PostgreSQL (Relational)
An object-relational database management system that supports SQL-based queries, similar
to those used by other RDBMS systems such as MySQL or Oracle Database. PostgreSQL is
developed and maintained by PostgreSQL Global Development Group, which is made up of
several companies and individuals who have contributed code to the project over time.
PostgreSQL's developers do not require contributors to sign a Contributor License
Agreement (CLA). The PostgreSQL license includes a clause requiring attribution of original
authorship if it's not done automatically by the contributor's revision control system.
The software is distributed under an ISC license, which allows anyone to use it for any
purpose without paying royalties or fees.
MongoDB (Non-Relational)
I M.Sc(CS) Page 66
23PCSC06 Advanced Java Programming
MongoDB is an open-source document-oriented database developed by MongoDB Inc.
(formerly 10gen). The first version was released in 2009. It is written in C++ and provides a
document-oriented data model that can be queried using a JSON-like query language.
A document can be thought of as a virtual "sheet" or "document" in a spreadsheet application
such as Microsoft Excel or Google Sheets. A document contains multiple fields that may be
similar to cells in an Excel spreadsheet or cells in an Access database table. These fields can
have different types: text, numbers, dates, and so on.
MongoDB's development began in 2007 when its creators were working on software for the
social media website Facebook.com. They attempted to create a new kind of database that
would be better suited to the needs of web applications than traditional relational databases,
but they found that commercial offerings did not meet their requirements. As a result, they
developed a prototype called GridFS before founding 10gen to continue work on it as a
product named MongoDB. In 2009, the company changed its name to MongoDB Inc., and in
February 2010 it released the first production version of MongoDB.
Cassandra (Non-Relational)
Cassandra is an open-source database management system that runs on many servers,
making it well-suited for handling large amounts of data. It offers fast performance and can
scale up to a petabyte of data across multiple servers, making it useful for applications with
high write-throughput requirements.
Cassandra is built on the principles of Dynamo with the goal of addressing some of its
problems. The technology was developed at Facebook and released as an Apache Incubator
project in 2009. It graduated from incubation in June 2010 and became an Apache Top-level
Project (TLP) in January 2012.
Cassandra's architecture is based on Dynamo, but differs from it significantly in its design
details, especially regarding consistency guarantees and failure detection mechanisms. In
particular, Cassandra does not provide strong consistency; instead, it aims to provide high
availability by making it easy to deploy multiple copies of the data across many hosts while
tolerating failures at any one host. This makes Cassandra a popular choice for internet
startups that must scale quickly and cheaply.
Cassandra is a key-value store, but it has flexible data models, so you can use it to store
virtually any kind of data. You can also use Cassandra for full-text search, or even for storing
graph data (although there are better options for graph storage than Cassandra).
Neo4j (Graph database)
Neo4j is an open-source graph database management system that stores data in a native
graph database format. It's designed to store data and query it very quickly, making it ideal
for applications that involve complex relationships between entities. It uses the native graph
data model to provide ACID transactions, high availability, and indexing. It's used by many
companies to power their critical applications, including eBay and Walmart.
I M.Sc(CS) Page 67
23PCSC06 Advanced Java Programming
Unlike relational databases, Neo4j doesn't enforce a schema on your data. This makes it
easier to build applications that model real-world problems such as social networks or
product recommendations. You can create multiple nodes for the same entity without
duplicating data or having to use foreign keys. In addition, Neo4j allows you to add
properties to existing nodes without having to create a new table first. These features make
Neo4j much more agile than traditional relational databases when modeling complex
relationships between entities with many attributes and relationships between them.
MariaDB (Relational)
MariaDB is a fork of the MySQL relational database management system intended to remain
free under the GNU GPL. MariaDB was forked in 2009 by some of the original developers of
MySQL when Oracle announced that it would no longer fully support the community-
developed version of MySQL in favor of a paid enterprise product.
The original developers of MySQL created MariaDB to provide a better development
environment and more robust performance. MariaDB strives to be compatible with MySQL
and includes most of its storage engines. However, not all features are supported in MariaDB
Server so it is recommended that you check for compatibility before using any feature that
may be affected by a bug or limitation in MariaDB Server.
MSSQL (Relational)
MSSQL databases are the core of Microsoft SQL Server. It is a relational database
management system (RDBMS), a special type of database software that is used to create,
store and manipulate data in an organized manner.
MSSQL can be used to build enterprise-level business solutions and applications. Regardless
of the platform or device your users are using, you can use MSSQL to create a centralized
data store with a single version of the truth. You can also use it to create a single source of
truth for your data analytics and reporting technologies, such as Power BI and Tableau.
How to Connect Database to Web Application
Connecting a database to a web application is an important step in your development
process. By connecting your database to your web application, you can easily add new data,
modify existing data, delete data, and more.
I M.Sc(CS) Page 68
23PCSC06 Advanced Java Programming
There are a few ways to do it. The simplest way is to use a direct query to get the value you
need. This is not recommended because it will severely limit your flexibility and scalability.
Another approach is to use a stored procedure that returns the value. This can be done in
SQL Server, MySQL server, or other RDBMSs. But what if your web application needs more
than one value from the database? You would need to issue multiple queries or use another
method.
The most common way to connect a database to an application is by using an Object
Relational Mapper (ORM). This technology connects your program to the database and
allows you to use it like a normal object. There are many different ORMs available today, but
one of the most popular ones is called Active Record (AR). This library has been around for
over 10 years now and has served as the foundation for many other ORMs such as Yii2 and
Laravel.
Conclusion
The database is an integral part of any Web application or website. Whether it is used for
storing data in an easy-to-access manner or for maintenance, the database is going to play a
role in the success of your project and you can't overlook it. For those who are simply going
to be accessing data, the strength of the database will not matter much as long as it has all the
functionality they need. However, those who plan on using it or maintaining it should really
explore why one database type may work better than another. If a web app is going to run
fast and efficiently with minimal downtime, every consideration needs to be made so that
bottlenecks do not occur. The success of your project may depend on your choice of
database.
UNIT IV
SERVLETS
Java Servlet and CGI:
The world has changed into a mobile-first era but even today, none of the
applications could emerge as effective as the web-based apps. Surfacing on top of
this is the prevalence of progressive web apps that perform functions identical to
mobile apps. In this article, we will understand the difference between the two
functionalities in web-based applications namely servlets and CGI.
Servlet is a Java class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response model. Servlets are mainly
used to extend the applications hosted by web servers, however, they can respond to
other types of requests too. For such applications, HTTP-specific servlet classes are
defined by Java Servlet technology. All the programs of Servlets are written in JAVA
I M.Sc(CS) Page 69
23PCSC06 Advanced Java Programming
and they get to run on JAVA Virtual Machine. The following image describes how a
request from clients is served with the help of threads:
The following table explains the difference between the servlet and CGI:
Basis Servlet CGI
Language The codes are written in The codes are written any
Used JAVA programming programming language.
I M.Sc(CS) Page 70
23PCSC06 Advanced Java Programming
language.
Server It can use any of the web- It can use the web-server that
Independent server. supports it.
It can read and set HTTP It can neither read nor set HTTP
HTTP server
servers. servers.
Construction and
Construction and destruction of the
Cost destruction of new threads
new processes are costly.
are not costly.
I M.Sc(CS) Page 71
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 72
23PCSC06 Advanced Java Programming
}
Compiling a Servlet
Let us create a file with name HelloWorld.java with the code shown above. Place this
file at C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path
location must be added to CLASSPATH before proceeding further.
Assuming your environment is setup properly, go in ServletDevel directory and
compile HelloWorld.java as follows −
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on
your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm
not using any other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work
properly, you have to include the location of the Java SDK that you are using in the
PATH environment variable.
If everything goes fine, above compilation would produce HelloWorld.class file in
the same directory. Next section would explain how a compiled servlet would be
deployed in production.
Servlet Deployment
By default, a servlet application is located at the path <Tomcat-
installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet
class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes and create following
entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
I M.Sc(CS) Page 73
23PCSC06 Advanced Java Programming
Above entries to be created inside <web-app>...</web-app> tags available in
web.xml file. There could be various entries in this table already available, but never
mind.
You are almost done, now let us start tomcat server using <Tomcat-
installationdirectory>\bin\startup.bat (on Windows) or <Tomcat-
installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally
type http://localhost:8080/HelloWorld in the browser's address box. If everything
goes fine, you would get the following result
I M.Sc(CS) Page 74
23PCSC06 Advanced Java Programming
As displayed in the above diagram, there are three states of a servlet: new, ready and
end. The servlet is in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state. In the ready state, servlet performs all the
tasks. When the web container invokes the destroy() method, it shifts to the end
state.
I M.Sc(CS) Page 76
23PCSC06 Advanced Java Programming
getParameter() − You call request.getParameter() method to get the value of a
form parameter.
getParameterValues() − Call this method if the parameter appears more than
once and returns multiple values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all
parameters in the current request.
GET Method Example using URL
Here is a simple URL which will pass two values to HelloForm program using GET
method.
http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI
Given below is the HelloForm.java servlet program to handle input given by web
browser. We are going to use getParameter() method which makes it very easy to
access passed information
Assuming your environment is set up properly, compile HelloForm.java as follows −
$ javacHelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next
you would have to copy this class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes and create following
entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name
=ALI in your browser's Location:box and make sure you already started tomcat
server, before firing above command in the browser. This would generate following
result
Using GET Method to Read Form Data
First Name: ZARA
Last Name: ALI
I M.Sc(CS) Page 78
23PCSC06 Advanced Java Programming
PrintWriterout=response.getWriter();
String title ="Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+
"transitional//en\">\n";
out.println(docType +
"<html>\n"+
"<head><title>"+ title +"</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n"+
"<h1 align = \"center\">"+ title +"</h1>\n"+
"<ul>\n"+
" <li><b>First Name</b>: "
+request.getParameter("first_name")+"\n"+
" <li><b>Last Name</b>: "
+request.getParameter("last_name")+"\n"+
"</ul>\n"+
"</body>"
"</html>"
);
}
doGet(request, response);
}
}
Now compile and deploy the above Servlet and test it using Hello.htm with the
POST method as follows −
<html>
<body>
<formaction="HelloForm"method="POST">
First Name: <inputtype="text"name="first_name">
<br/>
Last Name: <inputtype="text"name="last_name"/>
<inputtype="submit"value="Submit"/>
I M.Sc(CS) Page 79
23PCSC06 Advanced Java Programming
</form>
</body>
</html>
Here is the actual output of the above form, Try to enter First and Last Name and
then click submit button to see the result on your local machine where tomcat is
running.
First Name: Last Name:
Based on the input provided, it would generate similar result as mentioned in the
above examples.
Reading http request header:
Servlets - Client HTTP Request
When a browser requests for a web page, it sends lot of information to the web
server which cannot be read directly because this information travel as a part of
header of HTTP request. You can check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and
you would use very frequently in web programming −
Sr.No. Header & Description
Accept
This header specifies the MIME types that the browser or
1 other clients can handle. Values
of image/png or image/jpeg are the two most common
possibilities.
Accept-Charset
2 This header specifies the character sets the browser can use
to display the information. For example ISO-8859-1.
Accept-Encoding
This header specifies the types of encodings that the
3 browser knows how to handle. Values
of gzip or compress are the two most common
possibilities.
Accept-Language
This header specifies the client's preferred languages in
4
case the servlet can produce results in more than one
language. For example en, en-us, ru, etc
I M.Sc(CS) Page 80
23PCSC06 Advanced Java Programming
Authorization
5 This header is used by clients to identify themselves when
accessing password-protected Web pages.
Connection
This header indicates whether the client can handle
persistent HTTP connections. Persistent connections permit
6
the client or other browser to retrieve multiple files with a
single request. A value of Keep-Alive means that
persistent connections should be used.
Content-Length
7 This header is applicable only to POST requests and gives
the size of the POST data in bytes.
Cookie
8 This header returns cookies to servers that previously sent
them to the browser.
Host
9 This header specifies the host and port as given in the
original URL.
Methods to read HTTP Header
There are following methods which can be used to read HTTP header in your servlet
program. These methods are available with HttpServletRequest object
Sr.No. Method & Description
Cookie[] getCookies()
1 Returns an array containing all of the Cookie objects the
client sent with this request.
Enumeration getAttributeNames()
2 Returns an Enumeration containing the names of the
attributes available to this request.
Enumeration getHeaderNames()
3 Returns an enumeration of all the header names this
request contains.
4 Enumeration getParameterNames()
I M.Sc(CS) Page 81
23PCSC06 Advanced Java Programming
HttpSession getSession()
5 Returns the current session associated with this request, or
if the request does not have a session, creates one.
PrintWriterout=response.getWriter();
String title ="HTTP Header Request Example";
String docType =
I M.Sc(CS) Page 82
23PCSC06 Advanced Java Programming
"<!doctype html public \"-//w3c//dtd html 4.0 "+"transitional//en\">\n";
out.println(docType +
"<html>\n"+
"<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>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);
while(headerNames.hasMoreElements()){
String paramName =(String)headerNames.nextElement();
out.print("<tr><td>"+ paramName +"</td>\n");
String paramValue =request.getHeader(paramName);
out.println("<td> "+ paramValue +"</td></tr>\n");
}
out.println("</table>\n</body></html>");
}
doGet(request, response);
}
}
Now calling the above servlet would generate the following result −
HTTP Header Request Example
accept */*
I M.Sc(CS) Page 83
23PCSC06 Advanced Java Programming
accept-language en-us
host localhost:8080
connection Keep-Alive
cache-control no-cache
I M.Sc(CS) Page 84
23PCSC06 Advanced Java Programming
Allow
1 This header specifies the request methods (GET, POST,
etc.) that the server supports.
Cache-Control
This header specifies the circumstances in which the
response document can safely be cached. It can have
values public, private or no-cache etc. Public means
2
document is cacheable, Private means document is for a
single user and can only be stored in private (non-shared)
caches and nocache means document should never be
cached.
Connection
This header instructs the browser whether to use persistent
3 in HTTP connections or not. A value of close instructs the
browser not to use persistent HTTP connections
and keepalive means using persistent connections.
Content-Disposition
4 This header lets you request that the browser ask the user
to save the response to disk in a file of the given name.
Content-Encoding
5 This header specifies the way in which the page was
encoded during transmission.
Content-Language
6 This header signifies the language in which the document
is written. For example en, en-us, ru, etc
Content-Length
This header indicates the number of bytes in the response.
7
This information is needed only if the browser is using a
persistent (keep-alive) HTTP connection.
Content-Type
8 This header gives the MIME (Multipurpose Internet Mail
Extension) type of the response document.
I M.Sc(CS) Page 85
23PCSC06 Advanced Java Programming
Expires
9 This header specifies the time at which the content should
be considered out-of-date and thus no longer be cached.
Last-Modified
This header indicates when the document was last
10 changed. The client can then cache the document and
supply a date by an If-Modified-Since request header in
later requests.
Location
This header should be included with all responses that
11 have a status code in the 300s. This notifies the browser of
the document address. The browser automatically
reconnects to this location and retrieves the new document.
Refresh
This header specifies how soon the browser should ask for
12
an updated page. You can specify time in number of
seconds after which a page would be refreshed.
Retry-After
This header can be used in conjunction with a 503 (Service
13
Unavailable) response to tell the client how soon it can
repeat its request.
Set-Cookie
14
This header specifies a cookie associated with the page.
Methods to Set HTTP Response Header
There are following methods which can be used to set HTTP response header in
your servlet program. These methods are available with HttpServletResponse object.
Sr.No. Method & Description
I M.Sc(CS) Page 86
23PCSC06 Advanced Java Programming
boolean isCommitted()
4 Returns a Boolean indicating if the response has been
committed.
void flushBuffer()
9
Forces any content in the buffer to be written to the client.
void reset()
10 Clears any data that exists in the buffer as well as the status
code and headers.
void resetBuffer()
11 Clears the content of the underlying buffer in the response
without clearing headers or status code.
I M.Sc(CS) Page 87
23PCSC06 Advanced Java Programming
Types of Cookie
There are 2 types of cookies in servlets.
I M.Sc(CS) Page 88
23PCSC06 Advanced Java Programming
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
It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
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
javax.servlet.http.Cookie class provides the functionality of using cookies. It
provides a lot of useful methods for cookies.
Constructor of Cookie class
Constructor Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be
changed after creation.
I M.Sc(CS) Page 89
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 90
23PCSC06 Advanced Java Programming
I M.Sc(CS) Page 92
23PCSC06 Advanced Java Programming
JAVA_HOME environment variables to refer to the directory that
contains java and javac,
typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and install the SDK in C:\jdk1.5.0_20, you need to add
the following line in your C:\autoexec.bat file.
set PATH = C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME = C:\jdk1.5.0_20
Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer,
select Properties, then Advanced, followed by Environment Variables. Then, you
would update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and
you use the C shell, you will put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.5.0_20
Alternatively,ifyouuse an Integrated Development Environment (IDE) like Borland
JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple
program to confirm that the IDE knows where you installed Java.
Setting up Web Server: Tomcat
A number of Web Servers that support JavaServer Pages and Servlets development
are available in the market. Some web servers can be downloaded for free and
Tomcat is one of them.
Apache Tomcat is an open source software implementation of the JavaServer Pages
and Servlet technologies and can act as a standalone server for testing JSP and
Servlets, and can be integrated with the Apache Web Server. Here are the steps to set
up Tomcat on your machine −
Download the latest version of Tomcat from https://tomcat.apache.org/.
Once you downloaded the installation, unpack the binary distribution into a
convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or
/usr/local/apache-tomcat-5.5.29 onLinux/Unixand
create CATALINA_HOME environment variable pointing to these locations.
Tomcat can be started by executing the following commands on the Windows
machine −
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-5.5.29\bin\startup.bat
I M.Sc(CS) Page 93
23PCSC06 Advanced Java Programming
Tomcat can be started by executing the following commands on the Unix (Solaris,
Linux, etc.) machine −
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After a successful startup, the default web-applications included with Tomcat will be
available by visiting http://localhost:8080/.
Upon execution, you will receive the following output −
Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site
− https://tomcat.apache.org/.
Tomcat can be stopped by executing the following commands on the Windows
machine −
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris,
Linux, etc.) machine −
I M.Sc(CS) Page 94
23PCSC06 Advanced Java Programming
$CATALINA_HOME/bin/shutdown.sh
or
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify
the servlet classes to the compiler.
If you are running Windows, you need to put the following lines in
your C:\autoexec.bat file.
set CATALINA = C:\apache-tomcat-5.5.29
set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%
Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer,
select Properties, then Advanced, then Environment Variables. Then, you would
update the CLASSPATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the
following lines into your .cshrc file.
setenv CATALINA = /usr/local/apache-tomcat-5.5.29
setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH
NOTE − Assuming that your development directory is C:\JSPDev
(Windows) or /usr/JSPDev (Unix), then you would need to add these directories as
well in CLASSPATH.
JSP Scriptlet tag (Scripting elements):
1.Scripting elements
2.JSP scriptlet tag
3.Simple Example of JSP scriptlet tag
4.Example of JSP scriptlet tag that prints the user name
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see
what are the scripting elements first.
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There
are three types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
1. <% java source code %>
I M.Sc(CS) Page 95
23PCSC06 Advanced Java Programming
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
Example of JSP scriptlet tag that prints the user name
In this example, we have created two files index.html and welcome.jsp. The
index.html file gets the username from the user and the welcome.jsp file prints the
username with the welcome message.
File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
JSP expression tag:
The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print
the values of variable or method.
Syntax of JSP expression tag
1. <%= statement %>
Example of JSP expression tag
In this example of jsp expression tag, we are simply displaying a welcome message.
I M.Sc(CS) Page 96
23PCSC06 Advanced Java Programming
1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>
Example of JSP expression tag that prints current time
To display the current time, we have used the getTime() method of Calendar class.
The getTime() is an instance method of Calendar class, so we have called it after
getting the instance of Calendar class by the getInstance() method.
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
Scriptlets:
JavaServer Pages often present dynamically generated content as part of an XHTML
document sent to the client in response to a request. In some cases, the content is
static, but is output only if certain conditions are met during a request (such as
providing values in a form that submits a request). JSP programmers can insert Java
code and logic in a JSP using scripting.
Scripting Components
JSP scripting components include scriptlets, comments, expressions, declarations
and escape sequences. This section describes each of these scripting components.
Many of these scripting components are demonstrated in Fig. 10.4 at the end of
Section 10.5.2.
Scriptlets are blocks of code delimited by <% and %>. They contain Java statements
that the container places in method _jspService at translation time.
JSPs support three comment styles: JSP comments, XHTML comments and
comments from the scripting language. JSP comments are delimited by <%-- and --
%>. Such comments can be placed throughout a JSP, but not inside scriptlets.
XHTML comments are delimited with <!-- and -->. These comments can be placed
throughout a JSP, but not inside scriptlets. Scripting language comments are
currently Java comments, because Java is the only JSP scripting language at the
present time. Scriptlets can use Java’s single-line comments (delimited by/ and /)
and multiline comments (delimited by /* and */).JSP comments and scripting-
language comments are ignored and do not appear in the response to a client. When
I M.Sc(CS) Page 97
23PCSC06 Advanced Java Programming
clients view the source code of a JSP response, they will see only the XHTML
comments in the source code. The different comment styles are useful for separating
comments that the user should be able to see from comments that document logic
processed on the server.
A JSP expression, delimited by <%= and %>, contains a Java expression that is
evaluated when a client requests the JSP containing the expression. The container
converts the result of a JSP expression to a String object, then outputs the String as
part of the response to the client.
Declarations (delimited by <%! and %>) enable a JSP programmer to define variables
and methods. Variables become instance variables of the servlet class that represents
the translated JSP. Similarly, methods become members of the class that represents
the translated JSP. Declarations of variables and methods in a JSP use Java syntax.
Thus, a variable declaration must end in a semicolon, as in
<%! int counter = 0; %>
Special characters or character sequences that the JSP container normally uses to
delimit JSP code can be included in a JSP as literal characters in scripting elements,
fixed template data and attribute values using escape sequences. Figure 10.3 shows
the literal character or characters and the corresponding escape sequences and
discusses where to use the escape sequences.
Scripting Example
The JSP of Fig. 10.4 demonstrates basic scripting capabilities by responding to get
requests. The JSP enables the user to input a first name, then outputs that name as
part of the response. Using scripting, the JSP determines whether a firstName
parameter was passed to the JSP as part of the request; if not, the JSP returns an
XHTML document containing a form through which the user can input a first name.
Otherwise, the JSP obtains the firstName value and uses it as part of an XHTML
document that welcomes the user to JavaServer Pages.
Literal Escape sequence Description
<% <\% The character sequence <% normally indicates the beginning
of a scriptlet. The <\% escape sequence places the literal
characters <% in the response to the client.
%> %\> The character sequence %> normally indicates the end of a
scriptlet. The %\> escape sequence places the literal characters
%> in the response to the client.
Directives:
Directives are messages to the JSP container that enable the programmer to specify
page settings (such as the error page), to include content from other resources and to
specify custom- tag libraries for use in a JSP. Directives (delimited by <%@ and %>)
I M.Sc(CS) Page 98
23PCSC06 Advanced Java Programming
are processed at translation time. Thus, directives do not produce any immediate
output, because they are processed before the JSP accepts any requests. Figure 10.26
summarizes the three directive types. These directives are discussed in the next
several subsections.
Page Directive
The page directive specifies global settings for the JSP in the JSP container. There can
be many page directives, provided that there is only one occurrence of each attribute.
The only exception to this rule is the import attribute, which can be used repeatedly
to import Java packages used in the JSP. Figure 10.27 summarizes the attributes of
the page directive.
Directive Description
page Defines page settings for the JSP container to process.
include Causes the JSP container to perform a translation-time insertion of
another resource’s content. As the JSP is translated into a servlet and
compiled, the referenced file replaces the include directive and is
translated as if it were originally part of the JSP.
taglib Allows programmers to include their own new tags in the form of tag
libraries. These libraries can be used to encapsulate functionality and
simplify the coding of a JSP.
include Directive
The include directive includes the content of another resource once, at JSP
translation time. The include directive has only one attribute—file—that specifies the
URL of the page to include. The difference between directive include and action
<jsp:include> is noticeable only if the included content changes. For example, if the
definition of an XHTML document changes after it is included with directive
include, future invocations of the JSP will show the original content of the XHTML
document, not the new content. In contrast, action <jsp:include> is processed in each
request to the JSP.
Therefore, changes to included content would be apparent in the next request to the
JSP that uses action <jsp:include>. JavaServer Page includeDirective.jsp (Fig. 10.28)
reimplements JavaServer Page include.jsp (Fig. 10.10) using include directives. To
test includeDirective. jsp in Tomcat, copy includeDirective.jsp into the jsp directory
created in Section 10.3. Open your Web browser and enter the following URL to test
include- Directive.jsp:
http://localhost:8080/advjhtp1/jsp/includeDirective.jsp
JSP Declaration Tag:
1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
I M.Sc(CS) Page 99
23PCSC06 Advanced Java Programming
3. Example of JSP declaration tag that declares field
4. Example of JSP declaration tag that declares method
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method
of auto generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag
The syntax of the declaration tag is as follows:
1. <%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration tag
Jsp Scriptlet Tag Jsp Declaration Tag
The jsp scriptlet tag can only declare The jsp declaration tag can declare
variables not methods. variables as well as methods.
UNIT V
ADVANCED TECHNIQUES
JAR file format creation
Java Create Jar Files
In Java, JAR stands for Java ARchive, whose format is based on the zip format. The
JAR files format is mainly used to aggregate a collection of files into a single one. It is
a single cross-platform archive format that handles images, audio, and class files.
With the existing applet code, it is backward-compatible. In Java, Jar files are
completely written in the Java programming language.
We can either download the JAR files from the browser or can write our own JAR
files using Eclipse IDE.
The steps to bundle the source code, i.e., .java files, into a JAR are given below. In
this section, we only understand how we can create JAR files using eclipse IDE. In
the following steps, we don't cover how we can create an executable JAR in Java.
1. In the first step, we will open Eclipse IDE and select the Export option from
the File When we select the Export option, the Jar File wizard opens with the
following screen:
2. From the open wizard, we select the Java JAR file and click on the Next The
Next button opens JAR Export for JAR File Specification.
3. Now, from the JAR File Specification page, we select the resources needed for
exporting in the Select the resources to export After that, we enter the JAR file
name and folder. By default, the Export generated class files and
If there are other Java files or resources which we want to include and which
are available in the open project, browse to their location and ensure the file or
resource is checked in the window on the right.
4. On the same page, there are three more checkboxes, i.e., Compress the content
of the JAR file, Add directory entries, and Overwrite existing files without
warning. By default, the Compress content of the JAR file checkbox is
checked.
5. Now, we have two options for proceeding next, i.e., Finish and Next. If we
click on the Next, it will immediately create a JAR file to that location which
we defined in the Select the export destination. If we click on the Next button,
it will open the Jar Packaging Option wizard for creating a JAR description,
6. For now, we skip the Next and click on the Finish button.
Java Internalization – Overview:
Internalization
Internalization or I18N refers to the capability of an Application to be able to serve
users in multiple and different languages. Java has in-built support for
Internalization. Java also provides formatting of numbers, currencies and adjustment
of date and time accordingly.
Java Internationalization helps to make a java application handle different
languages, number formats, currencies, region specific time formatting.
Localization
Localization or L10N is the adaptability of an application that is how an application
adapts itself with a specific language, number formats, date and time settings etc.
A java application should be internationalized in order to be able to localize itself.
Culturally Dependent Information
Following information items often varies with different time zones or cultures.
Messages
Date
Time
Locale
1
Represents a language along with country/region.
ResourceBundle
2
Contains localized text or objects.
NumberFormat
3
Use to format numbers/currencies as per the locale.
DecimalFormat
4 Use to format numbers as per customized format and as
per locale.
DateFormat
5
Use to format dates as per locale.
SimpleDateFormat
6 Use to format dates as per customized format and as per
locale.
3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.