I-msc Advanced Java Chitra Mama
I-msc Advanced Java Chitra Mama
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:
[Link] 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
Website Link:
1.[Link]
2. [Link]
3. [Link]
I [Link](CS) Page 1
23PCSC06 Advanced Java Programming
UNIT-I
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.
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.
I [Link](CS) Page 2
23PCSC06 Advanced Java Programming
Dynamic − Java is considered to be more dynamic than C or C++ since it is designed
to adapt to an evolving environment. Java programs can carry extensive amount of run-
time information that can be used to verify and resolve accesses to objects on run-time.
Hello World using Java Programming.
Just to give you a little excitement about Java programming, I'm going to give you a
small conventional C Programming Hello World program, You can try it using Demo link.
publicclassMyFirstJavaProgram {
publicstaticvoidmain(String []args) {
[Link]("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).
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.
I [Link](CS) Page 3
23PCSC06 Advanced Java Programming
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) {
[Link]("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.
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:\[Link]' 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.
I [Link](CS) Page 4
23PCSC06 Advanced Java Programming
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 [Link]/[Link].
Eclipse − It is also a Java IDE developed by the Eclipse open-source community and
can be downloaded from [Link].
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.
I [Link](CS) Page 5
23PCSC06 Advanced Java Programming
Java has defined a set of interfaces for receiving and processing the events under
the [Link] package.
Some of the listenersare ActionListener, MouseListener, ItemListener,
KeyListener, WindowListener and etc.
Example
import [Link].*;
import [Link].*;
import [Link].*;
publicclassEventListenerTestextendsJFrameimplementsActionListener{
JButton button;
publicstaticvoid main(String args[]){
EventListenerTestobject=newEventListenerTest();
[Link]();
}
void createGUI(){
button=newJButton(" Click Me !");
setSize(300,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(button);
[Link](this);
}
publicvoid actionPerformed(ActionEvent ae){
if([Link]()== button){
[Link](null,"Generates an Action Event");
}
}
}
I [Link](CS) Page 6
23PCSC06 Advanced Java Programming
Output:
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.
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.
I [Link](CS) Page 7
23PCSC06 Advanced Java Programming
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 [Link](CS) Page 8
23PCSC06 Advanced Java Programming
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)
o Thread(ThreadGroup group, Runnable target, String name, long stackSize)
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:
Thread [Link]
I [Link](CS) Page 9
23PCSC06 Advanced Java Programming
15. ThreadExample1 t1 = new ThreadExample1();
16. //calling start method to execute the run() method of the Thread class
17. [Link]();
18. }
19. }
Output:
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.
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. [Link] ?
o How to perform connection-less socket programming in networking ?
I [Link](CS) Page 10
23PCSC06 Advanced Java Programming
The [Link] 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
1) IP Address
IP address is a unique number assigned to a node of a network e.g. [Link] . 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 [Link].
I [Link](CS) Page 11
23PCSC06 Advanced Java Programming
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.
[Link] package
The [Link] 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
I [Link](CS) Page 12
23PCSC06 Advanced Java Programming
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
o URL
o URLClassLoader
o URLConnection
o URLDecoder
o URLEncoder
o URLStreamHandler
o
List of interfaces available in [Link] 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)
I [Link](CS) Page 13
23PCSC06 Advanced Java Programming
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 [Link] that contains all the necessary
classes. [Link] contains the following classes.
1. [Link]
2. [Link]
3. [Link]
4. [Link]
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.
[Link] 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 ([Link] 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 = () -> [Link]();
4. [Link](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.
I [Link](CS) Page 14
23PCSC06 Advanced Java Programming
UNIT II
I [Link](CS) Page 15
23PCSC06 Advanced Java Programming
I [Link](CS) Page 16
23PCSC06 Advanced Java Programming
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
I [Link](CS) Page 17
23PCSC06 Advanced Java Programming
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
public static void bind([Link], [Link]) throws It binds the remote object
[Link], with the given name.
[Link], [Link];
public static void rebind([Link], [Link]) throws It binds the remote object
[Link], [Link]; to the new name.
I [Link](CS) Page 18
23PCSC06 Advanced Java Programming
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 [Link].*;
2. public class MyClient{
3. public static void main(String args[]){
4. try{
5. Adder stub=(Adder)[Link]("rmi://localhost:5000/sonoo");
6. [Link]([Link](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.
1) Create the table
First of all, we need to create the table in the database. Here, we are using Oracle10
database.
I [Link](CS) Page 19
23PCSC06 Advanced Java Programming
2. public class Customer implements [Link]{
3. private int acc_no;
4. private String firstname,lastname,email;
5. private float amount;
6. //getters and setters
7. }
1. package [Link];
2. import [Link].*;
3. import [Link].*;
4. interface Bank extends Remote{
5. public List<Customer> getCustomers()throws RemoteException;
6. }
I [Link](CS) Page 20
23PCSC06 Advanced Java Programming
Access
1 Hides the way in which resources are accessed and the
differences in data platform.
Location
2
Hides where resources are located.
Technology
3 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.
I [Link](CS) Page 21
23PCSC06 Advanced Java Programming
Advantages
Resource sharing − Sharing of hardware and software resources.
Openness − Flexibility of using hardware and software of different vendors.
Concurrency − Concurrent processing to enhance performance.
Scalability − Increased throughput by adding new resources.
Fault tolerance − The ability to continue in operation after a fault has occurred.
Disadvantages
Complexity − They are more complex than centralized systems.
Security − More susceptible to external attack.
Manageability − More effort required for system management.
Unpredictability − Unpredictable responses depending on the system organization and
network load.
Centralized System vs. Distributed System
Criteria Centralized system Distributed System
I [Link](CS) Page 22
23PCSC06 Advanced Java Programming
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.
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.
I [Link](CS) Page 23
23PCSC06 Advanced Java Programming
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)
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.
I [Link](CS) Page 24
23PCSC06 Advanced Java Programming
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 [Link](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
I [Link](CS) Page 26
23PCSC06 Advanced Java Programming
Broker
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 [Link](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).
Features of SOA
A service-oriented architecture provides the following features −
I [Link](CS) Page 28
23PCSC06 Advanced Java Programming
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
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.
I [Link](CS) Page 29
23PCSC06 Advanced Java Programming
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 [Link].
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 [Link](CS) Page 30
23PCSC06 Advanced Java Programming
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.
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.
I [Link](CS) Page 31
23PCSC06 Advanced Java Programming
Serialization and Deserialization in Java
[Link]
[Link] Interface
[Link] of Serialization
[Link] of Deserialization
[Link] with Inheritance
[Link] interface
[Link] and static data member
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).
[Link] 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 [Link] interface by
default.
Let's see the example given below:
[Link]
I [Link](CS) Page 32
23PCSC06 Advanced Java Programming
1. import [Link];
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. [Link] = id;
7. [Link] = 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 [Link] 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.
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
I [Link](CS) Page 33
23PCSC06 Advanced Java Programming
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 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
I [Link](CS) Page 34
23PCSC06 Advanced Java Programming
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.
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 [Link]. 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
I [Link](CS) Page 35
23PCSC06 Advanced Java Programming
an entry that matches the specified template is written into the space. Note that each entry in
the space can be taken at most once, but two or more entries may have the exact same values.
Using JavaSpaces technology, distributed applications are modeled as a flow of objects
between participants, which is different from classic distributed models such as RMIs. Figure
1 indicates what a JavaSpaces technology-based application looks like.
I [Link](CS) Page 36
23PCSC06 Advanced Java Programming
Code Sample 1: [Link]
Copy
Copied to Clipboard
Error: Could not Copy
import [Link].*;
public class MessageEntry implements Entry {
public String content;
public MessageEntry() {
}
public MessageEntry(String content) {
[Link] = content;
}
public String toString() {
return "MessageContent: " + content;
}
}
MessageEntryspace
Copy
Copied to Clipboard
Error: Could not Copy
JavaSpace space = getSpace();
MessageEntry msg = new MessageEntry();
[Link] = "Hello there";
[Link](msg, null, [Link]);
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: >
[Link](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
I [Link](CS) Page 37
23PCSC06 Advanced Java Programming
MessageEntry template = new MessageEntry();
MessageEntry output = (MessageEntry) [Link](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: [Link]
Copy
Copied to Clipboard
Error: Could not Copy
import [Link];
public class SpaceClient {
public static void main(String argv[]) {
try {
MessageEntry msg = new MessageEntry();
[Link] = "Hello there";
[Link]("Searching for a JavaSpace...");
Lookup finder = new Lookup([Link]);
JavaSpace space = (JavaSpace) [Link]();
[Link]("A JavaSpace has been discovered.");
[Link]("Writing a message into the space...");
[Link](msg, null, 60*60*1000);
MessageEntry template = new MessageEntry();
[Link]("Reading a message from the space...");
MessageEntry result = (MessageEntry) [Link](template, null,
Long.MAX_VALUE);
[Link]("The message read is: "+[Link]);
} catch(Exception e) {
[Link]();
}
}
}
Transactions
The JavaSpaces API uses the package [Link] 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.
I [Link](CS) Page 38
23PCSC06 Advanced Java Programming
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 [Link], 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 [Link].
As a persistent space that maintains state between executions:
Use [Link].
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 ( [Link]) using javac as follows:
prompt> javac -classpath <pathToJiniInstallation\lib\[Link]> [Link]
Note that you need to include the JAR file [Link] 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 ( [Link]). Note that this code makes use of a
utility class called Lookup to locate or discover a JavaSpace space. Therefore, before you
compile [Link], you should download [Link] and then compile both classes
using javac as shown in step 2. Note that you should include the directory that
contains [Link] in your classpath when compiling [Link].
3. Run Launch-All, which is in the installverify directory of your Jini installation directory. This
will start a service browser (as shown in Figure 2) and six contributed Jini network
technology services, one of which is the JavaSpace service.
I [Link](CS) Page 39
23PCSC06 Advanced Java Programming
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\[Link];..\lib\[Link];..\lib\[Link] SpaceClient
If all goes well, you will see the output shown in Figure 3.
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).
I [Link](CS) Page 40
23PCSC06 Advanced Java Programming
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
Pre-Requisite
Before moving further, you need to have a good understanding of the following two subjects
−
Core JAVA Programming
SQL or MySQL Database
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −
JDBC API − This provides the application-to-JDBC Manager connection.
JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
I [Link](CS) Page 41
23PCSC06 Advanced Java Programming
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 [Link] and [Link] 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.
Illustration: Working of JDBC co-relating with real-time
I [Link](CS) Page 42
23PCSC06 Advanced Java Programming
I [Link](CS) Page 43
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 [Link]()
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 [Link]() to load the Oracle driver as
shown below as follows:
[Link](“[Link]”);
2-B [Link]()
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
[Link]()to register the Oracle driver as shown below:
[Link](new [Link]())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connectioncon=[Link](url,user,password)
user: Username from which your SQL command prompt can be accessed.
password: password from which the SQL command prompt can be accessed.
I [Link](CS) Page 44
23PCSC06 Advanced Java Programming
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=[Link]();
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=[Link](sql);
if(m==1)
[Link]("insertedsuccessfully:"+sql);
else
[Link]("insertion failed");
Here sql is SQL query of the type String:
Java
// This code is for establishing connection with MySQL
// database and retrieving data
// from db Java Database connectivity
/*
*1. import --->[Link]
*2. load and register the driver ---> [Link].
*3. create connection
*4. create a statement
I [Link](CS) Page 45
23PCSC06 Advanced Java Programming
I [Link](CS) Page 46
23PCSC06 Advanced Java Programming
Output:
// Importing database
[Link].*;
// Importing required classes
[Link].*;
// Main class
classMain {
I [Link](CS) Page 47
23PCSC06 Advanced Java Programming
Scanner k = newScanner([Link]);
[Link]("enter name");
String name = [Link]();
[Link]("enter roll no");
introll = [Link]();
[Link]("enter class");
String cls = [Link]();
// 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
[Link](
[Link]());
// Reference to connection interface
con = [Link](url, user,
pass);
// Creating a statement
Statement st = [Link]();
// Executing query
intm = [Link](sql);
if(m == 1)
[Link](
"inserted successfully : "+ sql);
else
[Link]("insertion failed");
I [Link](CS) Page 48
23PCSC06 Advanced Java Programming
}
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
Procedure:
1. Import the database-syntax for importing the sql database in java is-
import [Link].* ;
I [Link](CS) Page 49
23PCSC06 Advanced Java Programming
2. Load and register drivers-syntax for registering drivers after the loading of driver
class is
forName([Link]) ;
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 [Link].
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="+[Link]([Link]());
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
Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
con = [Link]();
4.2: Now, add the SQL query of step 3.1 inside prepareStatement and execute it as follows:
p =[Link](sql);
rs =[Link]();
4.3: We check if [Link]() 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 [Link]) 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 [Link] and [Link] 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
I [Link](CS) Page 50
23PCSC06 Advanced Java Programming
publicclassconnectionDB {
finalString DB_URL
= "jdbc:mysql://localhost:3306/testDB?useSSL=false";
// Database credentials
// 1. Root
finalString USER = "root";
I [Link](CS) Page 51
23PCSC06 Advanced Java Programming
PASS);
}
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
I [Link](CS) Page 52
23PCSC06 Advanced Java Programming
[Link].*;
// Main class
// It's connection class is shown above
publicclassGFG {
I [Link](CS) Page 53
23PCSC06 Advanced Java Programming
// in the object
if([Link]()) {
intid = [Link]("id");
String name = [Link]("name");
String email = [Link]("email");
String password = [Link]("password");
Multimedia Databases:
I [Link](CS) Page 54
23PCSC06 Advanced Java Programming
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 [Link](CS) Page 55
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.
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
I [Link](CS) Page 56
23PCSC06 Advanced Java Programming
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?
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.
I [Link](CS) Page 57
23PCSC06 Advanced Java Programming
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.
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.
I [Link](CS) Page 58
23PCSC06 Advanced Java Programming
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.
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).
I [Link](CS) Page 59
23PCSC06 Advanced Java Programming
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.
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.
I [Link](CS) Page 60
23PCSC06 Advanced Java Programming
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.
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
I [Link](CS) Page 61
23PCSC06 Advanced Java Programming
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.
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 [Link](CS) Page 62
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 [Link]. 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.
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.
I [Link](CS) Page 63
23PCSC06 Advanced Java Programming
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.
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
I [Link](CS) Page 64
23PCSC06 Advanced Java Programming
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.
I [Link](CS) Page 65
23PCSC06 Advanced Java Programming
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 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:
I [Link](CS) Page 66
23PCSC06 Advanced Java Programming
The following table explains the difference between the servlet and CGI:
Basis Servlet CGI
Language The codes are written in The codes are written any programming
Used JAVA programming language. language.
Since codes are written in Since codes are written in any language,
Object- Java, it is object oriented and all the languages are not object-oriented
Oriented the user will get the benefits of thread-based. So, the user will not get
OOPs the benefits of OOPs
It remains in the memory until It is removed from the memory after the
Persistence
it is not explicitly destroyed. completion of the process-basedrequest.
HTTP server It can read and set HTTP It can neither read nor set HTTP servers.
I [Link](CS) Page 67
23PCSC06 Advanced Java Programming
servers.
Platform
It can be Platform Independent It can be Platform dependent.
dependency
<servlet-mapping>
I [Link](CS) Page 69
23PCSC06 Advanced Java Programming
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in [Link] 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\[Link] (on Windows) or <Tomcat-
installationdirectory>/bin/[Link] (on Linux/Solaris etc.) and finally
type [Link] in the browser's address box. If everything goes fine,
you would get the following result
I [Link](CS) Page 70
23PCSC06 Advanced Java Programming
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.
I [Link](CS) Page 72
23PCSC06 Advanced Java Programming
Given below is the [Link] 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 [Link] as follows −
$ [Link]
If everything goes fine, above compilation would produce [Link] file. Next you
would have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-
INF/classes and create following entries in [Link] 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 [Link]
=ALI in your browser's Location:box and make sure you already started tomcat server, before
firing above command in the browser. This would generate following result
Using GET Method to Read Form Data
First Name: ZARA
Last Name: ALI
I [Link](CS) Page 73
23PCSC06 Advanced Java Programming
Keep this HTML in a file [Link] and put it in <Tomcat-
installationdirectory>/webapps/ROOT directory. When you would
access [Link] 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 [Link] servlet program to handle input given by web browser
using GET or POST methods.
// Import required java libraries
import [Link].*;
import [Link].*;
import [Link].*;
PrintWriterout=[Link]();
String title ="Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+
"transitional//en\">\n";
[Link](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>: "
+[Link]("first_name")+"\n"+
" <li><b>Last Name</b>: "
I [Link](CS) Page 74
23PCSC06 Advanced Java Programming
+[Link]("last_name")+"\n"+
"</ul>\n"+
"</body>"
"</html>"
);
}
doGet(request, response);
}
}
Now compile and deploy the above Servlet and test it using [Link] 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"/>
</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 −
[Link]. Header & Description
I [Link](CS) Page 75
23PCSC06 Advanced Java Programming
Accept
This header specifies the MIME types that the browser or other
1
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 browser
3
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 case the
4
servlet can produce results in more than one language. For
example en, en-us, ru, etc
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 the client or
6
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
I [Link](CS) Page 76
23PCSC06 Advanced Java Programming
There are following methods which can be used to read HTTP header in your servlet
program. These methods are available with HttpServletRequest object
[Link]. 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.
Enumeration getParameterNames()
4 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.
PrintWriterout=[Link]();
String title ="HTTP Header Request Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+"transitional//en\">\n";
[Link](docType +
"<html>\n"+
"<head><title>"+ title +"</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n"+
"<h1 align = \"center\">"+ title +"</h1>\n"+
"<table width = \"100%\" border = \"1\" align = \"center\">\n"+
"<tr bgcolor = \"#949494\">\n"+
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);
while([Link]()){
String paramName =(String)[Link]();
[Link]("<tr><td>"+ paramName +"</td>\n");
String paramValue =[Link](paramName);
[Link]("<td> "+ paramValue +"</td></tr>\n");
}
[Link]("</table>\n</body></html>");
}
doGet(request, response);
I [Link](CS) Page 78
23PCSC06 Advanced Java Programming
}
}
Now calling the above servlet would generate the following result −
HTTP Header Request Example
Accept */*
accept-language en-us
Host localhost:8080
connection Keep-Alive
cache-control no-cache
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
2 values public, private or no-cache etc. Public means 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 in
3 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. This
7
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 [Link](CS) Page 80
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 changed. The
10
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 have a
11 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 an
12
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.
[Link]. Method & Description
I [Link](CS) Page 81
23PCSC06 Advanced Java Programming
has already been set.
boolean isCommitted()
4
Returns a Boolean indicating if the response has been committed.
void flushBuffer()
9
Forces any content in the buffer to be written to the client.
void reset()
10 Clears any data that exists in the buffer as well as the status code
and headers.
void resetBuffer()
11 Clears the content of the underlying buffer in the response
without clearing headers or status code.
I [Link](CS) Page 82
23PCSC06 Advanced Java Programming
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: [Link] 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.
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
I [Link](CS) Page 83
23PCSC06 Advanced Java Programming
[Link] class provides the functionality of using cookies. It provides a lot
of useful methods for cookies.
Constructor of Cookie class
Constructor Description
Cookie(String name, String value) constructs a cookie with a specified name and 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.
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 [Link](CS) Page 85
23PCSC06 Advanced Java Programming
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.
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 −
I [Link](CS) Page 86
23PCSC06 Advanced Java Programming
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 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:\[Link] 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 [Link]
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\[Link]
or
C:\apache-tomcat-5.5.29\bin\[Link]
I [Link](CS) Page 87
23PCSC06 Advanced Java Programming
Tomcat can be started by executing the following commands on the Unix (Solaris, Linux,
etc.) machine −
$CATALINA_HOME/bin/[Link]
or
/usr/local/apache-tomcat-5.5.29/bin/[Link]
After a successful startup, the default web-applications included with Tomcat will be
available by visiting [Link]
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 − [Link]
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 −
$CATALINA_HOME/bin/[Link]
or
I [Link](CS) Page 88
23PCSC06 Advanced Java Programming
/usr/local/apache-tomcat-5.5.29/bin/[Link]
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:\[Link] file.
set CATALINA = C:\apache-tomcat-5.5.29
set CLASSPATH = %CATALINA%\common\lib\[Link];%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/[Link]:$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):
[Link] elements
[Link] scriptlet tag
[Link] Example of JSP scriptlet tag
[Link] 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 %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
1. <html>
2. <body>
3. <% [Link]("welcome to jsp"); %>
4. </body>
5. </html>
I [Link](CS) Page 89
23PCSC06 Advanced Java Programming
Example of JSP scriptlet tag that prints the user name
In this example, we have created two files [Link] and [Link]. The [Link] file
gets the username from the user and the [Link] file prints the username with the
welcome message.
File: [Link]
1. <html>
2. <body>
3. <form action="[Link]">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: [Link]
1. <html>
2. <body>
3. <%
4. String name=[Link]("uname");
5. [Link]("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 [Link]() 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.
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.
[Link]
I [Link](CS) Page 90
23PCSC06 Advanced Java Programming
1. <html>
2. <body>
3. Current Time: <%= [Link]().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
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
I [Link](CS) Page 91
23PCSC06 Advanced Java Programming
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 %>) 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
I [Link](CS) Page 92
23PCSC06 Advanced Java Programming
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 [Link] (Fig. 10.28) reimplements
JavaServer Page [Link] (Fig. 10.10) using include directives. To test includeDirective.
jsp in Tomcat, copy [Link] into the jsp directory created in Section 10.3. Open
your Web browser and enter the following URL to test include- [Link]:
[Link]
JSP Declaration Tag:
1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
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
variables not methods. as well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.
I [Link](CS) Page 93
23PCSC06 Advanced Java Programming
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.
[Link]
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>
I [Link](CS) Page 94
23PCSC06 Advanced Java Programming
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 [Link](CS) Page 95
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 [Link](CS) Page 96
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 resources checkbox is
checked. We also check the Export Java source files and resources checkbox to
I [Link](CS) Page 97
23PCSC06 Advanced Java Programming
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, setting the advance
I [Link](CS) Page 98
23PCSC06 Advanced Java Programming
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
Number
Currency
Measurements
I [Link](CS) Page 99
23PCSC06 Advanced Java Programming
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:
[Link]. 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.
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.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look
and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
public void setLayout(LayoutManager sets the layout manager for the component.
m)