0% found this document useful (0 votes)
113 views112 pages

New Java Notes - 2023-2024

Uploaded by

narmatha20022003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views112 pages

New Java Notes - 2023-2024

Uploaded by

narmatha20022003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

23PCSC06 Advanced Java Programming

Paavendhar College of Arts & Science, M.V.South


Department of Computer Science
I M.Sc Computer Science
Subject Code: 23PCSC06
Subject Name: Advanced Java Programming Unit: I

Syllabus

Unit I BASICS OF JAVA


Java Basics Review: Components and event handling – Threading concepts –
Networking features – Media techniques.
Unit II REMOTE METHOD INVOCATION
Remote Method Invocation-Distributed Application Architecture- Creating stubs
and skeletons- Defining Remote objects- Remote Object Activation-Object
Serialization-Java Spaces.
Unit III DATABASE
Java in Databases- JDBC principles – database access- Interacting- database search –
Creating multimedia databases – Database support in web applications
Unit IV SERVLETS
Java Servlets: Java Servlet and CGI programming- A simple java Servlet-Anatomy of
a java Servlet-Reading data from a client-Reading http request header-sending data
to a client and writing the http response header-working with cookies
Java Server Pages: JSP Overview-Installation-JSP tags-Components of a JSP page-
Expressions- Scriptlets-Directives-Declarations-A complete example
Unit V ADVANCED TECHNIQUES
JAR file format creation – Internationalization – Swing Programming – Advanced
java Techniques
Unit VI Contemporary Issues
Expert lectures, online seminars – webinars
Text Book:
1. Jamie Jaworski, “Java Unleashed”, SAMS Techmedia Publications,1999.
2. Campione, Walrath and Huml, “The Java Tutorial”, AddisonWesley,1999.
Reference Book:
1.Jim Keogh,” The Complete Reference J2EE”, Tata McGrawHill Publishing
Company Ltd,2010.
2. David Sawyer McFarland, “JavaScript And JQuery- The Missing Manual”, Oreilly
Publications, 3rd Edition,2011.
3. Deitel and Deitel, “Java How to Program”, Third Edition, PHI/Pearson Education
Asia
I M.Sc(CS) Page 1
23PCSC06 Advanced Java Programming
Website Link:
1.https://www.javatpoint.com/servlet-tutorial
2. https://www.tutorialspoint.com/java/index.htm
3. https://onlinecourses.nptel.ac.in/noc19_cs84/preview

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 {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

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

Thread Concept in Java:


Before introducing the thread concept, we were unable to run more than one task in
parallel. It was a drawback, and to remove that drawback, Thread Concept was
introduced.

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

1) New (Ready to run)


A thread is in New when it gets CPU time.
2) Running
A thread is in a Running state when it is under execution.
3) Suspended
A thread is in the Suspended state when it is temporarily inactive or under
execution.
4) Blocked
A thread is in the Blocked state when it is waiting for resources.
5) Terminated
A thread comes in this state when at any given time, it halts its execution
immediately.
Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or
by extending the Thread class. These are the only two ways through which we can
create a thread.
Let's dive into details of both these way of creating a thread:
Thread Class
A Thread class has several methods and constructors which allow us to perform
various operations on a thread. The Thread class extends the Object class.
The Object class implements the Runnable interface. The thread class has the
following constructors that are used to perform various operations.
o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)

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

Creating thread by implementing the runnable interface


In Java, we can also create a thread by implementing the runnable interface. The
runnable interface provides us both the run() method and the start() method.
Let's takes an example to understand how we can create, start and run the thread
using the runnable interface.
Java Networking:
Java Networking is a concept of connecting two or more computing devices together
so that we can share resources.
Java socket programming provides facility to share data between different
computing devices.
Advantage of Java Networking
1. Sharing resources
2. Centralize software management
Do You Know ?
o How to perform connection-oriented Socket Programming in networking ?
o How to display the data of any online web page ?
o How to get the IP address of any host name e.g. www.google.com ?
o How to perform connection-less socket programming in networking ?
The java.net package supports two protocols,
1. TCP: Transmission Control Protocol provides reliable communication between
the sender and receiver. TCP is used along with the Internet Protocol referred
as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by
allowing packet of data to be transferred along two or more nodes
Java Networking Terminology
The widely used Java networking terminologies are given below:
1. IP Address
2. Protocol
3. Port Number

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

Understanding requirements for the distributed applications


If any application performs these tasks, it can be distributed application.
1. The application need to locate the remote method
2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.
The RMI applications have all these features, so it is called the distributed
application.
Java RMI Example
There is given the 6 steps to write the RMI program.
1. Create the remote interface

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.

1) create the remote interface


For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface. Here, we are creating
a remote interface that extends the Remote interface. There is only one method
named add() and it declares RemoteException.
import java.rmi.*;
public interface Adder extends Remote{
public int add(int x,int y)throws RemoteException;
}
2) Provide the implementation of the remote interface
Now provide the implementation of the remote interface. For providing the
implementation of the Remote interface, we need to
o Either extend the UnicastRemoteObject class,
o or use the exportObject() method of the UnicastRemoteObject class

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;

public static void bind(java.lang.String, java.rmi.Remote) It binds the remote


throws java.rmi.AlreadyBoundException, object with the given
java.net.MalformedURLException, name.
java.rmi.RemoteException;

public static void unbind(java.lang.String) throws It destroys the remote


java.rmi.RemoteException, java.rmi.NotBoundException, object which is bound
java.net.MalformedURLException; with the given name.

public static void rebind(java.lang.String, java.rmi.Remote) It binds the remote

I M.Sc(CS) Page 18
23PCSC06 Advanced Java Programming

throws java.rmi.RemoteException, object to the new


java.net.MalformedURLException; name.

public static java.lang.String[] list(java.lang.String) throws It returns an array of


java.rmi.RemoteException, the names of the
java.net.MalformedURLException; remote objects bound
in the registry.
In this example, we are binding the remote object by the name sonoo.
1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
6) Create and run the client application
At the client we are getting the stub object by the lookup() method of the Naming
class and invoking the method on this object. In this example, we are running the
server and client applications, in the same machine so we are using localhost. If you
want to access the remote object from another machine, change the localhost to the
host name (or IP address) where the remote object is located.
1. import java.rmi.*;
2. public class MyClient{
3. public static void main(String args[]){
4. try{
5. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
6. System.out.println(stub.add(34,4));
7. }catch(Exception e){}
8. }
9. }
Meaningful example of RMI application with database
Consider a scenario, there are two applications running in different machines. Let's
say MachineA and MachineB, machineA is located in United States and MachineB in
India. MachineB want to get list of all the customers of MachineA application.
Let's develop the RMI application by following the steps.
I M.Sc(CS) Page 19
23PCSC06 Advanced Java Programming
1) Create the table
First of all, we need to create the table in the database. Here, we are using Oracle10
database.

2) Create Customer class and Remote interface


File: Customer.java
1. package com.javatpoint;
2. public class Customer implements java.io.Serializable{
3. private int acc_no;
4. private String firstname,lastname,email;
5. private float amount;
6. //getters and setters
7. }

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. }

Distributed Application Architecture:


In distributed architecture, components are presented on different platforms and
several components can cooperate with one another over a communication network
in order to achieve a specific objective or goal.

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

The basis of a distributed architecture is its transparency, reliability, and availability.


The following table lists the different forms of transparency in a distributed system −
Sr.No. Transparency & Description

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

Hides different technologies such as programming


language and OS from user.

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

Economics Low High

Availability Low High

Complexity Low High

Consistency Simple High

I M.Sc(CS) Page 22
23PCSC06 Advanced Java Programming

Scalability Poor Good

Technology Homogeneous Heterogeneous

Security High Low


Client-Server Architecture
The client-server architecture is the most common distributed system architecture
which decomposes the system into two major subsystems or logical processes −
 Client − This is the first process that issues a request to the second process i.e.
the server.
 Server − This is the second process that receives the request, carries it out, and
sends a reply to the client.
In this architecture, the application is modelled as a set of services that are provided
by servers and a set of clients that use these services. The servers need not know
about clients, but the clients must know the identity of servers, and the mapping of
processors to processes is not necessarily 1 : 1

Client-server Architecture can be classified into two models based on the


functionality of the client
Thin-client model
In thin-client model, all the application processing and data management is carried
by the server. The client is simply responsible for running the presentation software.

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

Broker implementation in CORBA


CORBA is an international standard for an Object Request Broker – a middleware to
manage communications among distributed objects defined by OMG (object
management group).

Service-Oriented Architecture (SOA)


A service is a component of business functionality that is well-defined, self-
contained, independent, published, and available to be used via a standard
programming interface. The connections between services are conducted by
common and universal message-oriented protocols such as the SOAP Web service
protocol, which can deliver requests and responses between services loosely.
Service-oriented architecture is a client/server design which support business-
driven IT approach in which an application consists of software services and
software service consumers (also known as clients or service requesters).

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

Let us now discuss the components of this architecture.


 Transport Layer − This layer connects the client and the server. It manages the
existing connection and also sets up new connections.
 Stub − A stub is a representation (proxy) of the remote object at client. It
resides in the client system; it acts as a gateway for the client program.
 Skeleton − This is the object which resides on the server
side. stub communicates with this skeleton to pass request to the remote
object.
 RRL(Remote Reference Layer) − It is the layer which manages the references
made by the client to the remote object.
Working of an RMI Application
The following points summarize how an RMI application works −
 When the client makes a call to the remote object, it is received by the stub
which eventually passes this request to the RRL.
 When the client-side RRL receives the request, it invokes a method
called invoke() of the object remoteRef. It passes the request to the RRL on the
server side.
 The RRL on the server side passes the request to the Skeleton (proxy on the
server) which finally invokes the required object on the server.
 The result is passed all the way back to the client.
Marshalling and Unmarshalling
Whenever a client invokes a method that accepts parameters on a remote object, the
parameters are bundled into a message before being sent over the network. These
parameters may be of primitive type or objects. In case of primitive type, the
parameters are put together and a header is attached to it. In case the parameters are
objects, then they are serialized. This process is known as marshalling.

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.

Figure 1: A Typical JavaSpaces Technology Application


As you can see, a client can interact with as many JavaSpaces services as needed.
Clients perform operations that map entries to templates onto JavaSpaces services.
Such operations can be singleton or contained in a transaction so that all or none of

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.

Figure 2: Jini Network Technology Service Browser


4. Finally, run the SpaceClient application using the java command as follows. Here I
assume that your Jini installation directory is C:\Jini2_1beta and that the classes you
compiled earlier are at C:\Jini2_1beta\myclasses.
5. C:\Jini2_1beta\myclasses> java -classpath .\;
..\lib\jini-ext.jar;..\lib\reggie.jar;..\lib\outrigger.jar SpaceClient
If all goes well, you will see the output shown in Figure 3.

I M.Sc(CS) Page 41
23PCSC06 Advanced Java Programming

Figure 3: SpaceClient Sample Output


Conclusion
The JavaSpaces technology provides services and tools for building sophisticated
distributed applications. This technology is designed to work with applications that
can model themselves as flow objects through one or more servers. If your
application can be modeled this way, JavaSpaces technology will provide you with
many benefits, such as a reliable distributed storage system for the objects. In
addition, JavaSpaces technology handles concurrent access, storing and retrieving
entries atomically.

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 −

Common JDBC Components


The JDBC API provides the following interfaces and classes −
 DriverManager − This class manages a list of database drivers. Matches
connection requests from the java application with the proper database driver

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

Why JDBC Come into Existence?


As previously told JDBC is an advancement for ODBC, ODBC being platform-
dependent had a lot of drawbacks. ODBC API was written in C, C++, Python, and
Core Java and as we know above languages (except Java and some part of Python
)are platform-dependent. Therefore to remove dependence, JDBC was developed
by a database vendor which consisted of classes and interfaces written in Java.
Steps to Connect Java Application with Database
Below are the steps that explains how to connect to Database in Java:
Step1 –ImportthePackages
Step2 –Loadthedriversusingthe forName()method
Step3 –Registerthedrivers usingDriverManager
Step4 –Establishaconnection usingtheConnectionclassobject
Step5 –Createastatement
Step6 –Executethequery
Step 7 – Close the connections
Java Database Connectivity

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

// This code is for establishing connection with MySQL


// database and retrieving data
// from db Java Database connectivity
/*
*1. import --->java.sql
*2. load and register the driver ---> com.jdbc.
*3. create connection
*4. create a statement
*5. execute the query
*6. process the results
*7. close
*/
importjava.io.*;
importjava.sql.*;
classGFG {
publicstaticvoidmain(String[] args) throwsException
{
String url
= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query
= "select *from students"; // query to be run
Class.forName(
"com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(
url, username, password);
System.out.println(
"Connection Established successfully");
Statement st = con.createStatement();
ResultSet rs
= st.executeQuery(query); // Execute query
rs.next();
String name
= rs.getString("name"); // Retrieve name from db
System.out.println(name); // Print result on console
st.close(); // close statement

I M.Sc(CS) Page 48
23PCSC06 Advanced Java Programming

con.close(); // close connection


System.out.println("Connection Closed....");
}
}

Output:

Step 6: Closing the connections


So finally we have sent the data to the specified location and now we are on the
verge of completing our task. By closing the connection, objects of Statement and
ResultSet will be closed automatically. The close() method of the Connection
interface is used to close the connection. It is shown below as follows:
con.close();
Example:
 Java

// Java Program to Establish Connection in JDBC

// Importing database
importjava.sql.*;
// Importing required classes
importjava.util.*;

// Main class
classMain {

// Main driver method


publicstaticvoidmain(String a[])
{

I M.Sc(CS) Page 49
23PCSC06 Advanced Java Programming

// Creating the connection using Oracle DB


// Note: url syntax is standard, so do grasp
String url = "jdbc:oracle:thin:@localhost:1521:xe";
// Username and password to access DB
// Custom initialization
String user = "system";
String pass = "12345";
// Entering the data
Scanner k = newScanner(System.in);
System.out.println("enter name");
String name = k.next();
System.out.println("enter roll no");
introll = k.nextInt();
System.out.println("enter class");
String cls = k.next();
// Inserting data using SQL query
String sql = "insert into student1 values('"+ name
+ "',"+ roll + ",'"+ cls + "')";
// Connection class object
Connection con = null;
// Try block to check for exceptions
try{
// Registering drivers
DriverManager.registerDriver(
neworacle.jdbc.OracleDriver());
// Reference to connection interface
con = DriverManager.getConnection(url, user,
pass);
// Creating a statement
Statement st = con.createStatement();
// Executing query
intm = st.executeUpdate(sql);
if(m == 1)
System.out.println(
"inserted successfully : "+ sql);
else
System.out.println("insertion failed");

I M.Sc(CS) Page 50
23PCSC06 Advanced Java Programming

// Closing the connections


con.close();
}

// Catch block to handle exceptions


catch(Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}

Output after importing data in the database:

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

// Java program to search the contents of


// a table in JDBC Connection class for JDBC
// Connection class of JDBC

// Importing required classes


importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.SQLException;

publicclassconnectionDB {

finalString DB_URL
= "jdbc:mysql://localhost:3306/testDB?useSSL=false";

// Database credentials

// We need two parameters to access the database

I M.Sc(CS) Page 53
23PCSC06 Advanced Java Programming

// Root and password

// 1. Root
finalString USER = "root";

// 2. Password to fetch database


finalString PASS = "Imei@123";

// Connection class for our database connectivity


publicConnection connectDB()
{
// Initially setting NULL
// to connection class object
Connection con = null;

// Try block to check exceptions


try{

// Loading DB(SQL) drivers


Class.forName("com.mysql.cj.jdbc.Driver");

// Registering SQL drivers


con = DriverManager.getConnection(DB_URL, USER,
PASS);
}

// Catch block to handle database exceptions


catch(SQLException e) {

// Print the line number where exception occurs


e.printStackTrace();
}

// Catch block to handle exception


// if class not found
catch(ClassNotFoundException e) {

I M.Sc(CS) Page 54
23PCSC06 Advanced Java Programming

// Function prints the line number


// where exception occurs
e.printStackTrace();
}

// Returning Connection class object to


// be used in (App/Main) GFG class
returncon;
}
}

App/Main Class where the program is compiled and run calling the above
connection class object

 Java

// Java program to Search the


// contents of a table in JDBC

// Main Java program (App Class) of JDBC

// Step 1: Importing database files


// Importing SQL libraries
importjava.sql.*;

// Main class
// It's connection class is shown above
publicclassGFG {

// Main driver method


publicstaticvoidmain(String[] args)
{
// Step 2: Establishing a connection
connectionDB connection = newconnectionDB();

I M.Sc(CS) Page 55
23PCSC06 Advanced Java Programming

// Assigning NULL to object of Connection class


// as shown returned by above program
Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;

// Step 3: Loading and registereding drivers


// Loaded and registered in Connection class
// shown in above program
con = connection.connectDB();

// Try block to check exceptions


try{

// Step 4: Write a statement


String sql
= "select * from cuslogin where id=1";

// Step 5: Execute the query


p = con.prepareStatement(sql);
rs = p.executeQuery();

// Step 6: Process the results


System.out.println(
"id\t\tname\t\temail\t\tpassword");

// Condition check using next() method


// Holds true till there is single element remaining
// in the object
if(rs.next()) {

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

// Print and display name, emailID and password


System.out.println(id + "\t\t"+ name
+ "\t\t"+ email + "\t\t"
+ password);
}
}

// Catch block to handle exceptions


catch(SQLException e) {

// Print the exception


System.out.println(e);
}
}
}

Output: Based on the values stored inside the “cuslogin” table.

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

Contents of the Multimedia Database


The multimedia database stored the multimedia data and information related to it.
This is given in detail as follows −
Media data
This is the multimedia data that is stored in the database such as images, videos,
audios, animation etc.
Media format data
The Media format data contains the formatting information related to the media data
such as sampling rate, frame rate, encoding scheme etc.
Media keyword data
This contains the keyword data related to the media in the database. For an image
the keyword data can be date and time of the image, description of the image etc.
Media feature data
Th Media feature data describes the features of the media data. For an image, feature
data can be colours of the image, textures in the image etc.
Challenges of Multimedia Database
There are many challenges to implement a multimedia database. Some of these are:
 Multimedia databases contains data in a large type of formats such as .txt(text),
.jpg(images), .swf(videos), .mp3(audio) etc. It is difficult to convert one type of
data format to another.
 The multimedia database requires a large size as the multimedia data is quite
large and needs to be stored successfully in the database.
 It takes a lot of time to process multimedia data so multimedia database is
slow.
The Role of Database in Web Application Development

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.

Graph-based database management systems provide a way to model relationships between


objects as nodes connected by edges (lines). Graphs can be used to represent complex
relationships among people, places, and things in your world such as connections between
people on social media sites like Facebook.
Advantages
 Easy to model real-world situations: The structure of a graph database allows you to model
any type of relationship that exists in your real-world business problem — not just the ones
that fit into a traditional table. This makes them ideal for applications such as social networks
or recommendation engines. Graphs are also great for representing complex data structures
such as trees, hierarchies, and link graphs.
 Efficient for traversing linked data: Graphs are particularly useful for traversing linked data
because they allow you to follow links between objects as easily as searching within an
object. You can easily find all records related to a particular item or set of items by following
related links between those records.
 Graph databases also allow you to query data on both nodes and edges at the same time,
so they're great for analyzing relationships between entities no matter how deep those
relationships may go!
Disadvantages
 Performance. Graphs are not known for their fast performance. They do not perform well
when there are multiple levels of nesting or loops in the graph structure. This means that
they can be slow when dealing with large amounts of data or graphs with high-degree
vertices (vertices connected to many other vertices).
 Scalability. Graphs are not scalable in an easy way like tables are in relational databases.
Because graphs are implemented as networks and each vertex can have multiple edges
linking it to other vertices, adding more vertices and edges to a graph makes it more difficult
to manage efficiently. This is especially true when each vertex has a large number of edges
linking it to other vertices in the database.

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:

CommonGateway Interface(CGI): The Common Gateway Interface (CGI) provides


the middleware between WWW servers and external databases and information
sources. The World Wide Web Consortium (W3C) defined the Common Gateway
Interface (CGI) and also defined how a program interacts with a HyperText Transfer
Protocol (HTTP) server. The Web server typically passes the form information to a
small application program that processes the data and may send back a confirmation
message. This process or convention for passing data back and forth between the
server and the application is called the common gateway interface (CGI). The
following image describes how a web server acts as an intermediate between the
CGI program and the client browser.

The following table explains the difference between the servlet and CGI:
Basis Servlet CGI

It is thread based i.e. for


It is process-based i.e. for every
Approach every new request new
new request new process is created.
thread is created.

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

Basis Servlet CGI

language.

Since codes are written in any


Since codes are written in
language, all the languages are not
Object- Java, it is object oriented
object-oriented thread-based. So,
Oriented and the user will get the
the user will not get the benefits of
benefits of OOPs
OOPs

Portability It is portable. It is not portable.

It remains in the memory It is removed from the memory


Persistence until it is not explicitly after the completion of the process-
destroyed. basedrequest.

Server It can use any of the web- It can use the web-server that
Independent server. supports it.

Data Sharing Data sharing is possible. Data sharing is not possible.

It links directly to the It does not link the web server


Link
server. directly to the server.

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.

Speed Its can speed is slower. It can speed is faster.

Platform It can be Platform


It can be Platform dependent.
dependency Independent

I M.Sc(CS) Page 71
23PCSC06 Advanced Java Programming

A simple java Servlet:


Servlets are Java classes which service HTTP requests and implement
the javax.servlet.Servlet interface. Web application developers typically write
servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements
the Servlet interface and is specially designed to handle HTTP requests.
Sample Code
Following is the sample source code structure of a servlet example to show Hello
World −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}

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

Anatomy of a java Servlet:


Life Cycle of a Servlet (Servlet Life Cycle)
1.Life Cycle of a Servlet
1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked
The web container maintains the life cycle of a servlet instance. Let's see the life cycle
of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

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.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The
init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
1. public void init(ServletConfig config) throws ServletException
4) service method is invoked
The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method.
I M.Sc(CS) Page 75
23PCSC06 Advanced Java Programming
Notice that servlet is initialized only once. The syntax of the service method of the
Servlet interface is given below:
1. public void service(ServletRequest request, ServletResponse response)
2. throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:
1. public void destroy()
Reading data from a client:
You must have come across many situations when you need to pass some
information from your browser to web server and ultimately to your backend
program. The browser uses two methods to pass this information to web server.
These methods are GET Method and POST Method.
GET Method
The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? (question mark)
symbol as follows −
http://www.test.com/hello?key1 = value1&key2 = value2
The GET method is the default method to pass information from browser to web
server and it produces a long string that appears in your browser's Location:box.
Never use the GET method if you have password or other sensitive information to
pass to the server. The GET method has size limitation: only 1024 characters can be
used in a request string.
This information is passed using QUERY_STRING header and will be accessible
through QUERY_STRING environment variable and Servlet handles this type of
requests using doGet() method.
POST Method
A generally more reliable method of passing information to a backend program is
the POST method. This packages the information in exactly the same way as GET
method, but instead of sending it as a text string after a ? (question mark) in the URL
it sends it as a separate message. This message comes to the backend program in the
form of the standard input which you can parse and use for your processing. Servlet
handles this type of requests using doPost() method.
Reading Form Data using Servlet
Servlets handles form data parsing automatically using the following methods
depending on the situation −

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

GET Method Example Using Form


I M.Sc(CS) Page 77
23PCSC06 Advanced Java Programming
Here is a simple example which passes two values using HTML FORM and submit
button. We are going to use same Servlet HelloForm to handle this input.
<html>
<body>
<formaction="HelloForm"method="GET">
First Name: <inputtype="text"name="first_name">
<br/>
Last Name: <inputtype="text"name="last_name"/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
Keep this HTML in a file Hello.htm and put it in <Tomcat-
installationdirectory>/webapps/ROOT directory. When you would
access http://localhost:8080/Hello.htm, here is the actual output of the above form.
First Name: Last Name:
Try to enter First Name and Last Name and then click submit button to see the result
on your local machine where tomcat is running. Based on the input provided, it will
generate similar result as mentioned in the above example.
POST Method Example Using Form
Let us do little modification in the above servlet, so that it can handle GET as well as
POST methods. Below is HelloForm.java servlet program to handle input given by
web browser using GET or POST methods.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


publicclassHelloFormextendsHttpServlet{

// Method to handle GET method request.


publicvoid doGet(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

// Set response content type


response.setContentType("text/html");

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>"
);
}

// Method to handle POST method request.


publicvoid doPost(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

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

Returns an Enumeration of String objects containing the


names of the parameters contained in this request

HttpSession getSession()
5 Returns the current session associated with this request, or
if the request does not have a session, creates one.

HttpSession getSession(boolean create)


Returns the current HttpSession associated with this
6
request or, if if there is no current session and value of
create is true, returns a new session.
HTTP Header Request Example
Following is the example which uses getHeaderNames() method of
HttpServletRequest to read the HTTP header information. This method returns an
Enumeration that contains the header information associated with the current HTTP
request.
Once we have an Enumeration, we can loop down the Enumeration in the standard
manner, using hasMoreElements() method to determine when to stop and
using nextElement() method to get each parameter name
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


publicclassDisplayHeaderextendsHttpServlet{

// Method to handle GET method request.


publicvoid doGet(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

// Set response content type


response.setContentType("text/html");

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"
);

Enumeration headerNames =request.getHeaderNames();

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>");
}

// Method to handle POST method request.


publicvoid doPost(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

doGet(request, response);
}
}
Now calling the above servlet would generate the following result −
HTTP Header Request Example

Header Name Header Value(s)

accept */*

I M.Sc(CS) Page 83
23PCSC06 Advanced Java Programming

accept-language en-us

Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;


user-agent
Trident/4.0; InfoPath.2; MS-RTC LM 8)

accept-encoding gzip, deflate

host localhost:8080

connection Keep-Alive

cache-control no-cache

Sending data to a client and writing the http response header:


Servlets - Server HTTP Response
when a Web server responds to an HTTP request, the response typically consists of a
status line, some response headers, a blank line, and the document. A typical
response looks like this −
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status
code (200 in the example), and a very short message corresponding to the status code
(OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go
back to the browser from web server side and you would use them very frequently
in web programming −
Sr.No. Header & Description

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

String encodeRedirectURL(String url)


Encodes the specified URL for use in the sendRedirect
1
method or, if encoding is not needed, returns the URL
unchanged.

2 String encodeURL(String url)

I M.Sc(CS) Page 86
23PCSC06 Advanced Java Programming

Encodes the specified URL by including the session ID in


it, or, if encoding is not needed, returns the URL
unchanged.

boolean containsHeader(String name)


3 Returns a Boolean indicating whether the named response
header has already been set.

boolean isCommitted()
4 Returns a Boolean indicating if the response has been
committed.

void addCookie(Cookie cookie)


5
Adds the specified cookie to the response.

void addDateHeader(String name, long date)


6 Adds a response header with the given name and date-
value.

void addHeader(String name, String value)


7
Adds a response header with the given name and value.

void addIntHeader(String name, int value)


8 Adds a response header with the given name and integer
value.

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.

void sendError(int sc)


12 Sends an error response to the client using the specified
status code and clearing the buffer.

I M.Sc(CS) Page 87
23PCSC06 Advanced Java Programming

void sendError(int sc, String msg)


13 Sends an error response to the client using the specified
status.

void sendRedirect(String location)


14 Sends a temporary redirect response to the client using the
specified redirect location URL.

void setBufferSize(int size)


15
Sets the preferred buffer size for the body of the response.
HTTP Header Response Example
You already have seen setContentType() method working in previous examples and
following example would also use same method, additionally we would
use setIntHeader() method to set Refresh header.
Now calling the above servlet would display current system time after every 5
seconds as follows. Just run the servlet and wait to see the result −
Auto Refresh Header Setting
Current Time is: 9:44:50 PM
Working with cookies:
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by default.
Thus, we recognize the user as the old user.

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

Cookie() constructs a cookie.

Cookie(String name, String constructs a cookie with a specified name and


value) value.
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.
Method 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.

public String getValue() Returns the value of the cookie.

public void setName(String changes the name of the cookie.


name)

I M.Sc(CS) Page 89
23PCSC06 Advanced Java Programming

public void setValue(String changes the value of the cookie.


value)
Other methods required for using Cookies
For adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse
interface is used to add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is
used to return all the cookies from the browser.

How to create Cookie?


Let's see the simple code to create cookie.
1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
2. response.addCookie(ck);//adding cookie in the response
How to delete Cookie?
Let's see the simple code to delete cookie. It is mainly used to logout or signout the
user.
1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response
How to get Cookies?
Let's see the simple code to get all the cookies.
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value o
f cookie
4. }
Simple example of Servlet Cookies
In this example, we are storing the name of the user in the cookie object and
accessing it in another servlet. As we know well that session corresponds to the
particular user. So if you access it from too many browsers with different values, you
will get the different value.

I M.Sc(CS) Page 90
23PCSC06 Advanced Java Programming

Java Server Pages: JSP Overview


JSP - Overview
What is JavaServer Pages?
JavaServer Pages (JSP) is a technology for developing Webpages that supports
dynamic content. This helps developers insert java code in HTML pages by making
use of special JSP tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the
role of a user interface for a Java web application. Web developers write JSPs as text
files that combine HTML or XHTML code, XML elements, and embedded JSP
actions and commands.
Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing
control between pages, and sharing information between requests, pages etc.
Why Use JSP?
JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in
comparison with the CGI.
 Performance is significantly better because JSP allows embedding Dynamic
Elements in HTML Pages itself instead of having separate CGI files.
 JSP are always compiled before they are processed by the server unlike
CGI/Perl which requires the server to load an interpreter and the target script
each time the page is requested.
I M.Sc(CS) Page 91
23PCSC06 Advanced Java Programming
 JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP
also has access to all the powerful Enterprise Java APIs, including JDBC,
JNDI, EJB, JAXP, etc.
 JSP pages can be used in combination with servlets that handle the business
logic, the model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the
most complex and demanding.
Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −
vs. Active Server Pages (ASP)
The advantages of JSP are twofold. First, the dynamic part is written in Java, not
Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.
vs. Pure Servlets
It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
vs. Server-Side Includes (SSI)
SSI is really only intended for simple inclusions, not for "real" programs that use
form data, make database connections, and the like.
vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with
the web server to perform complex tasks like database access and image processing
etc.
vs. Static HTML
Regular HTML, of course, cannot contain dynamic information.
JSP - Environment Setup
A development environment is where you would develop your JSP programs, test
them and finally run them.
This tutorial will guide you to setup your JSP development environment which
involves the following steps −
Setting up Java Development Kit
This step involves downloading an implementation of the Java Software
Development Kit (SDK) and setting up the PATH environment variable
appropriately.
You can download SDK from Oracle's Java site − Java SE Downloads.
Once you download your Java implementation, follow the given instructions to
install and configure the setup. Finally set the PATH and

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.

The declaration of scriptlet tag is The declaration of jsp declaration tag is


placed inside the _jspService() placed outside the _jspService() method.
method.
Example of JSP declaration tag that declares field
In this example of JSP declaration tag, we are declaring the field and printing the
value of the declared field using the jsp expression tag.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
Example of JSP declaration tag that declares method
In this example of JSP declaration tag, we are defining the method which returns the
cube of given number and calling this method from the jsp expression tag. But we
can also use jsp scriptlet tag to call the declared method.
index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){

I M.Sc(CS) Page 100


23PCSC06 Advanced Java Programming
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>

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:

I M.Sc(CS) Page 101


23PCSC06 Advanced Java Programming

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.

I M.Sc(CS) Page 102


23PCSC06 Advanced Java Programming

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

I M.Sc(CS) Page 103


23PCSC06 Advanced Java Programming
resources checkbox is checked. We also check the Export Java source files and
resources checkbox to export the source code.

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,

I M.Sc(CS) Page 104


23PCSC06 Advanced Java Programming
setting the advance option, or changing the default manifest.

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

I M.Sc(CS) Page 105


23PCSC06 Advanced Java Programming
 Number
 Currency
 Measurements
 Phone Numbers
 Postal Addresses
 GUI labels
Internationalization Classes
Java has a set of built-in classes which help in internationalization of an application.
These classes are following:
Sr.No. Class & Description

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.

7. Now, we go to the specified location, which we defined in the Select the


export destination, to ensure that the JAR file is created successfully or not.

I M.Sc(CS) Page 106


23PCSC06 Advanced Java Programming
Java Swing:
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight
components.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing
There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components


are platform-independent.

2) AWT components are heavyweight. Swing components


are lightweight.

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.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and view.
What is JFC
The Java Foundation Classes (JFC) is a set of GUI components which simplify the
development of desktop applications.
Do You Know
o How to create runnable jar file in java?
o How to display image on a button in swing?
o How to change the component color by choosing a color from ColorChooser ?
o How to display the digital watch in swing tutorial ?
o How to create a notepad in swing?

I M.Sc(CS) Page 107


23PCSC06 Advanced Java Programming
o How to create puzzle game and pic puzzle game in swing ?
o How to create tic tac toe game in swing ?
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given
below.
Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int sets size of the component.


height)

public void sets the layout manager for the component.


setLayout(LayoutManager m)

public void setVisible(boolean b) sets the visibility of the component. It is by


default false.
Java Swing Examples
There are two ways to create a frame:
o By creating the object of Frame class (association)

I M.Sc(CS) Page 108


23PCSC06 Advanced Java Programming
o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding it on
the JFrame object inside the main() method.
File: FirstSwingExample.java
1.import javax.swing.*;
2.public class FirstSwingExample {
3.public static void main(String[] args) {
4.JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }

download this example


What we will learn in Swing Tutorial
o JButton class
o JRadioButton class
o JTextArea class
o JComboBox class
o JTable class

I M.Sc(CS) Page 109


23PCSC06 Advanced Java Programming
o JColorChooser class
o JProgressBar class
o JSlider class
o Digital Watch
o Graphics in swing
o Displaying image
o Edit menu code for Notepad
o OpenDialog Box
o Notepad
o Puzzle Game
o Pic Puzzle Game
o Tic Tac Toe Game
o BorderLayout
o GridLayout
o FlowLayout
o CardLayout
Advanced java Techniques:
Introduction
Core Java (J2SE) and Advanced Java are the two components that make up the Java
programming language (JEE). The foundations of the Java programming language,
including its data types, functions, operators, loops, threads, and exception handling,
are discussed in the "core Java" section of this book. It is used in the process of
developing apps for widespread usage. Whereas Intermediate Java focuses on more
advanced topics, such as database connection, networking, Servlet, web services, and
so on, Advanced Java addresses more fundamental ideas. In this article, we will talk
about what advanced Java is, and the concepts of advanced Java.
Advanced java
Everything that is beyond Core Java is known as Advanced Java. This includes the
application programming interfaces (APIs) that are specified in Java Enterprise
Edition, as well as Servlet programming, Web Services, the API, and so on. It is a
Web and Enterprise application development platform that, in its most basic form,
adheres to the client-server architectural model.
Important concepts of advanced Java
Majorly there are three most important concepts in advanced Java and they are −
 JSP (Java server pages)
 JDBC (Java DataBase Connectivity)
 Java servlets
We will discuss these concepts in detail in the upcoming sections.

I M.Sc(CS) Page 110


23PCSC06 Advanced Java Programming
JSP (Java server pages)
Java Server Pages, sometimes known as JSP, is a server-side programming tool that
allows the construction of web-based applications in a manner that is both dynamic
and independent of the underlying platform. JSP is able to access the whole family of
Java APIs, including the JDBC API, which is used to connect to business databases.
In a series of straightforward and uncomplicated stages, this article will show you
how to create online apps by making use of Java Server Pages.
The following is a list of the primary characteristics of JSP technology −
 A language used for the development of JSP pages, which are documents
written in text format that specifies how to handle a request and generate a
response.
 An expression language that allows access to things stored on the server.
 In the JSP programming language, the mechanisms for introducing new
extensions
JDBC (Java DataBase Connectivity)
Java Application Programming Interface (API) known as JDBC, which stands for
Java Database Connectivity, allows users to connect to databases and run queries on
them. It is a specification developed by Sun Microsystems that aims to give Java
programs a standardized abstraction (API or Protocol) for communicating with a
variety of databases. It offers the language standards for connecting to Java
databases. It is used in the process of writing programs, which are necessary in order
to access databases. Access to databases and spreadsheets is possible using JDBC
when combined with a database driver. JDBC application programming interfaces
allow users access to the business data kept in a relational database (RDB).
Purpose of JDBC
It is necessary for enterprise applications built with the JAVA EE technology to
connect with databases in order to store information that is unique to the
application. Therefore, an effective database connection is required for interacting
with a database. This connectivity need may be met by using the ODBC (Open
database connectivity) driver. This driver is used in conjunction with JDBC in order
to interface or communicate with several sorts of databases, including SQL server
databases, Mysql, Oracle, and MS Access amongst others.
Java Servlets
The Java applications known as servlets are executed on a web server or application
server that supports the Java programming language. They are put to use to handle
the request that has been acquired from the web server, to process the request, to
generate the response, and finally to send the response back to the web server.
The following is a list of properties of Servlets −

I M.Sc(CS) Page 111


23PCSC06 Advanced Java Programming
 Servlets are programs that run on the server.
 Servlets are capable of managing requests that are very sophisticated and are
received from the web server.
The technologies that are used in the process of developing dynamic web pages are
what are known as server-side extensions. In point of fact, in order to provide the
functionality of dynamic web pages, web pages need a container, also known as a
web server. Independent Web server vendors provide certain proprietary solutions
in the form of application programming interfaces (APIs) to satisfy this need
(Application Programming Interface).

I M.Sc(CS) Page 112

You might also like