0% found this document useful (0 votes)
26 views88 pages

I MSC Cs Advanced Java Programming

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

I MSC Cs Advanced Java Programming

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

VIDHYAA ARTS AND SCIENCE COLLEGE

KONGANAPURAM

ADVANCED JAVA PROGRAMMING


M.Sc (Computer Science), Semester-II

DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS

Prepared By

Mr.V.RASAGOUNDAN M.C.A.,M.Phil.,

Version: 2023 – 2024 - 1.0


Contents
UNIT-I...........................................................................................................1
1.1 JAVA BASIC REVIEW...............................................................................1
1.1.1 COMPONENTS AND EVENT HANDLING............................................2
1.1.2 THREADING CONCEPTS...................................................................6
1.1.3 NETWORKING FEATURES...............................................................11
1.1.4 MEDIA TECHNIQUES......................................................................15
UNIT-II........................................................................................................18
2.1 REMOTE METHOD INVOCATION...........................................................18
2.2 DISTRIBUTED APPLICATION ARCHITECTURE........................................19
2.3 CREATING STUBS AND SKELETONS.....................................................20
2.4 DEFINING REMOTE OBJECTS................................................................25
2.5 REMOTE OBJECT ACTIVATION..............................................................27
2.6 OBJECT SERIALIZATION.......................................................................28
2.7 JAVA SPACES.......................................................................................30
UNIT-III.......................................................................................................32
3.1 JAVA IN DATABASES............................................................................32
3.2 JDBC PRINCIPLES.................................................................................33
3.3 DATABASE ACCESS..............................................................................35
3.4 INTERACTING DATABASE SEARCH.......................................................37
3.5 CREATING MULTIMEDIA DATABASE.....................................................38
3.6 DATABASE SUPPORT IN WEB APPLICATION.........................................39
UNIT – IV....................................................................................................42
4.1 JAVA SERVLETS....................................................................................42
4.1.1 JAVA SERVLET AND CGI PROGRAMMING..........................................43
4.1.2 ANATOMY OF A JAVA SERVLET........................................................44
4.1.3 READING DATA FROM A CLIENT.......................................................46
4.1.4 READING HTTP REQUEST HEADER................................................48
4.1.5 SENDING DATA TO A CLIENT AND WRITING THE HTTP RESPONSE
HEADER..................................................................................................51
4.1.6 WORKING WITH COOKIES..............................................................53
4.2 JAVA SERVER PAGES............................................................................54
4.2.1 JSP OVERVIEW...............................................................................55
4.2.2 JSP INSTALLATION.........................................................................56
4.2.3 JSP TAGS........................................................................................57
4.2.4 COMPONENTS OF A JSP PAGE............................................................58
4.2.5 EXPRESSIONS...................................................................................60
4.2.6 SCRIPTS...........................................................................................61
4.2.7 DIRECTIVES.....................................................................................62
4.2.8 DECLARATION.................................................................................66
UNIT – V.....................................................................................................68
5.1 JAR FILE FORMAT CREATION................................................................68
5.2 INTERNATIONALIZATION......................................................................73
5.3 SWING PROGRAMMING........................................................................74
5.4 ADVANCED JAVA..................................................................................76
MODEL QUESTION PAPER..........................................................................78
OBJECTIVE QUESTIONS...........................................................................81

SYLLABUS
ADVANCED JAVA PROGRAMMING
Unit:1 BASICS OF JAVA
Java Basics Review: Components and event handling – Threading concepts – Networking
features – Media techniques

Unit:2 REMOTE METHOD INVOCATION

Remote Method Invocation-Distributed Application Architecture- Creating stubs and


skeletons-

Defining Remote objects- Remote Object Activation-Object Serialization-Java Spaces

Unit:3 DATABASE

Java in Databases- JDBC principles – database access- Interacting- database search –


Creating

multimedia databases – Database support in web applications

Unit:4 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:5 ADVANCED TECHNIQUES 12 hours

JAR file format creation – Internationalization – Swing Programming – Advanced java

Text Books

1 Jamie Jaworski, “Java Unleashed”, SAMS Techmedia Publications,1999.


2 Campione, Walrath and Huml, “The Java Tutorial”, AddisonWesley,1999.

Reference Books

1 Jim Keogh,” The Complete Reference J2EE”, Tata McGrawHill Publishing Company

Ltd,2010.

2 David Sawyer McFarland, “JavaScript And JQuery- The Missing Manual”, Oreilly

Publications, 3rd Edition,2011.

3 Deitel and Deitel, “Java How to Program”, Third Edition, PHI/Pearson Education Asia.
Vidhyaa Arts And Science College-Konganapuram

UNIT-I

1.1 JAVA BASIC REVIEW

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.

1
Vidhyaa Arts And Science College-Konganapuram

 Interpreted − Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and analytical since
the linking is an incremental and light-weight process.
 High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
 Distributed − Java is designed for the distributed environment of the internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it is designed
to adapt to an evolving environment. Java programs can carry extensive amount of
run-time information that can be used to verify and resolve accesses to objects on run-
time
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.

1.1.1 COMPONENTS AND EVENT HANDLING

The GUI in Java processes the interactions with users via mouse, keyboard and
various user controls such as button, checkbox, text field, etc. as the events. These events are
to be handled properly to implement Java as an Event-Driven Programming.
Components in Event Handling
 Events
 Event Sources
 Event Listeners/Handlers
Events
 The events are defined as an object that describes a change in the state of a source
object.

2
Vidhyaa Arts And Science College-Konganapuram

 The Java defines a number of such Event Classes inside java.awt.event package
 Some of the events are ActionEvent, MouseEvent, KeyEvent, FocusEvent, ItemEvent
and etc.
Event Sources
 A source is an object that generates an event.
 An event generation occurs when an internal state of that object changes in some way.
 A source must register listeners in order for the listeners to receive the notifications
about a specific type of event.
 Some of the event sources are Button, CheckBox, List, Choice, Window and etc.
Event Listeners
 A listener is an object that is notified when an event occurs.
 A Listener has two major requirements, it should be registered to one more source
object to receiving event notification and it must implement methods to receive and
process those notifications.
 Java has defined a set of interfaces for receiving and processing the events under the
java.awt.event package.
 Some of the listeners are ActionListener, MouseListener, ItemListener, KeyListener,
WindowListener and etc.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:

3
Vidhyaa Arts And Science College-Konganapuram

 Register the component with the Listener


 Registration Methods
 For registering the component with the Listener, many classes provide the registration
methods.
For example
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventListenerTest extends JFrame implements ActionListener {
JButton button;
public static void main(String args[]) {
EventListenerTest object = new EventListenerTest();
object.createGUI();
}
void createGUI() {
button = new JButton(" Click Me !");
setSize(300,200);

4
Vidhyaa Arts And Science College-Konganapuram

setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button) {
JOptionPane.showMessageDialog(null, "Generates an Action Event");
}
}
}

OUTPUT

1.1.2 THREADING CONCEPTS

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.

5
Vidhyaa Arts And Science College-Konganapuram

A Thread is a very light-weighted process, or we can say the smallest part of the
process that allows a program to operate more efficiently by running multiple tasks
simultaneously.
In order to perform complicated tasks in the background, we used the Thread concept
in Java. All the tasks are executed without affecting the main program. In a program or
process, all the threads have their own separate path for execution, so each thread of a process
is independent.

Another benefit of using thread is that if a thread gets an exception or an error at the
time of its execution, it doesn't affect the execution of the other threads. All the threads share
a common memory and have their own stack, local variables and program counter. When
multiple threads are executed in parallel at the same time, this process is known as
Multithreading.
In a simple way, a Thread is a:
 Feature through which we can perform multiple activities within a single process.
 Lightweight process.
 Series of executed statements.
 Nested sequence of method calls.

6
Vidhyaa Arts And Science College-Konganapuram

Thread Model
Just like a process, a thread exists in several states. These states are as follows:

1) New (Ready to run)


A thread is in New when it gets CPU time.
2) Running
A thread is in a Running state when it is under execution.
3) Suspended
A thread is in the Suspended state when it is temporarily inactive or under execution.
4) Blocked
A thread is in the Blocked state when it is waiting for resources.
5) Terminated
A thread comes in this state when at any given time, it halts its execution
immediately.
Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or by
extending the Thread class. These are the only two ways through which we can create a
thread.
Thread Class
A Thread class has several methods and constructors which allow us to perform
various operations on a thread. The Thread class extends the Object class. The Object class

7
Vidhyaa Arts And Science College-Konganapuram

implements the Runnable interface. The thread class has the following constructors that are
used to perform various operations.
Thread()
Thread(Runnable, String name)
Thread(Runnable target)
Thread(ThreadGroup group, Runnable target, String name)
Thread(ThreadGroup group, Runnable target)
Thread(ThreadGroup group, String name)
Thread(ThreadGroup group, Runnable target, String name, long stackSize)
Runnable Interface(run() method)

The Runnable interface is required to be implemented by that class whose instances


are intended to be executed by a thread. The runnable interface gives us the run() method to
perform an action for the thread
start() method
The method is used for starting a thread that we have newly created. It starts a new
thread with a new callstack. After executing the start() method, the thread changes the state
from New to Runnable. It executes the run() method when the thread gets the correct time to
execute it.
Let's take an example to understand how we can create a Java thread by extending the
Thread class:
ThreadExample1.java
// Implementing runnable interface by extending Thread class
public class ThreadExample1 extends Thread {
// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )

8
Vidhyaa Arts And Science College-Konganapuram

{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the Thread class
t1.start();
}
}

Output:

Creating thread by implementing the runnable interface


In Java, we can also create a thread by implementing the runnable interface. The
runnable interface provides us both the run() method and the start() method.
Let's takes an example to understand how we can create, start and run the thread using
the runnable interface.
ThreadExample2.java
class NewThread implements Runnable {
String name;
Thread thread;
NewThread (String name){
this.name = name;
thread = new Thread(this, name);
System.out.println( "A New thread: " + thread+ "is created\n" );
thread.start();
}
public void run() {

9
Vidhyaa Arts And Science College-Konganapuram

try {
for(int j = 5; j > 0; j--) {
System.out.println(name + ": " + j);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + " thread Interrupted");
}
System.out.println(name + " thread exiting.");
}
}
class ThreadExample2 {
public static void main(String args[]) {
new NewThread("1st");
new NewThread("2nd");
new NewThread("3rd");
try {
Thread.sleep(8000);
} catch (InterruptedException excetion) {
System.out.println("Inturruption occurs in Main Thread");
}
System.out.println("We are exiting from Main Thread");
} }

Output:

10
Vidhyaa Arts And Science College-Konganapuram

1.1.3 NETWORKING FEATURES

Java Networking is a concept of connecting two or more computing devices together


so that we can share resources.
Java socket programming provides facility to share data between different computing
devices.
Advantage of Java Networking
 Sharing resources
 Centralize software management
The java.net package supports two protocols,
TCP: Transmission Control Protocol provides reliable communication between the
sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
UDP: User Datagram Protocol provides a connection-less protocol service by allowing
packet of data to be transferred along two or more nodes
Java Networking Terminology
The widely used Java networking terminologies are given below:
 IP Address

11
Vidhyaa Arts And Science College-Konganapuram

 Protocol
 Port Number
 MAC Address
 Connection-oriented and connection-less protocol
 Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
 TCP
 FTP
 Telnet
 SMTP
 POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network
Interface Controller). A network node can have multiple NIC but each with unique MAC
address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol


In connection-oriented protocol, acknowledgement is sent by the receiver. So it is
reliable but slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is
not reliable but fast. The example of connection-less protocol is UDP.
6) Socket

12
Vidhyaa Arts And Science College-Konganapuram

A socket is an endpoint between two way communications.


java.net package
The java.net package can be divided into two sections:
A Low-Level API: It deals with the abstractions of addresses i.e. networking
identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces i.e.
network interfaces.
A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to the
resource pointed by URLs.
The java.net package provides many classes to deal with networking applications in Java.
A list of these classes is given below:
 Authenticator
 CacheRequest
 CacheResponse
 ContentHandler
 CookieHandler
 CookieManager
 DatagramPacket
 DatagramSocket
 DatagramSocketImpl
 InterfaceAddress
 JarURLConnection
 MulticastSocket
 InetSocketAddress
 InetAddress
 Inet4Address
 Inet6Address
 IDN
 HttpURLConnection
 HttpCookie
 NetPermission
 NetworkInterface
 PasswordAuthentication
 Proxy

13
Vidhyaa Arts And Science College-Konganapuram

 ProxySelector
 ResponseCache
 SecureCacheResponse
 ServerSocket
 Socket
 SocketAddress
 SocketImpl
 SocketPermission
 StandardSocketOptions
 URI
 URL
 URLClassLoader
 URLConnection
 URLDecoder
 URLEncoder
 URLStreamHandler
List of interfaces available in java.net package:
 ContentHandlerFactory
 CookiePolicy
 CookieStore
 DatagramSocketImplFactory
 FileNameMap
 SocketOption<T>
 SocketOptions
 SocketImplFactory
 URLStreamHandlerFactory
 ProtocolFamily

1.1.4 MEDIA TECHNIQUES

Historically, Java has provided weak support for multimedia. The JDK 1.0 and JDK
1.1 core platform releases provided minimal support for sound in applets and no official
support of sound in applications.

14
Vidhyaa Arts And Science College-Konganapuram

In addition, Sun provided no support for video manipulation, streaming media capture
or playback, 2D or 3D graphics (except through the use of basic drawing primitives), or
numerous other advanced multimedia services.

Media support in the Java platform, at least in any well-organized form, historically
has been nil. Sun and its partners have set out to change this -- and to complete an important
piece of the Java-as-a-platform puzzle -- by designing and implementing the Java Media and
Communication APIs.
The Java Media and Communication APIs
There are a number of APIs that fall within the purview of media and
communications. These, and what they enable in the Java platform, include:
 Java 2D -- 2D graphics and image manipulation
 Java 3D -- 3D graphics runtime
 Java Media Framework -- playback of synchronized media
 Java Sound -- software sound processor and MIDI synthesizer
 Java Speech -- speech recognition and synthesis
 Java Telephony -- computer and telephony integration
 Sun has also discussed several less well-defined Media APIs, both at JavaOne in
March 1998 and in previous public forums:
 Java Advanced Imaging -- advanced 2D image processing.
 Java Animation -- 2D Animation.
 Java Collaboration -- media data sharing.
(Please refer to the Resources at the end of this column for the location of Java Media-related
presentation materials from this year's JavaOne conference.)

15
Vidhyaa Arts And Science College-Konganapuram

The Media APIs are available in various states of readiness, from being hinted at in
marketing literature, to being discussed only in whitepapers, to being available with full
specifications and in some cases implementations.
The states of the various Java Media and Communication APIs as of May 11th, 1998 are:

16
Vidhyaa Arts And Science College-Konganapuram

UNIT-II

2.1 REMOTE METHOD INVOCATION

RMI stands for Remote Method Invocation. It is a mechanism that allows an object
residing in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between
Java programs. It is provided in the package java.rmi.
Architecture of an RMI Application
In an RMI application, we write two programs, a server program (resides on the
server) and a client program (resides on the client).
Inside the server program, a remote object is created and reference of that object is
made available for the client (using the registry).

17
Vidhyaa Arts And Science College-Konganapuram

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.

Let us now discuss the components of this architecture.


 Transport Layer − This layer connects the client and the server. It manages the
existing connection and also sets up new connections.
 Stub − A stub is a representation (proxy) of the remote object at client. It resides in
the client system; it acts as a gateway for the client program.
 Skeleton − This is the object which resides on the server side. stub communicates
with this skeleton to pass request to the remote object.
 RRL(Remote Reference Layer) − It is the layer which manages the references made
by the client to the remote object.
Working of an RMI Application
The following points summarize how an RMI application works −
 When the client makes a call to the remote object, it is received by the stub which
eventually passes this request to the RRL.
 When the client-side RRL receives the request, it invokes a method called invoke() of
the object remoteRef. It passes the request to the RRL on the server side.
 The RRL on the server side passes the request to the Skeleton (proxy on the server)
which finally invokes the required object on the server.
 The result is passed all the way back to the client.

18
Vidhyaa Arts And Science College-Konganapuram

2.2 DISTRIBUTED APPLICATION ARCHITECTURE

Java provides a standardized way to enable interactions between distributed applications


and disparate information sources.
It provides framework for development of distributed applications and is one of the
leading platform for the deployment of service oriented architecture (SOA) based
applications using web services.
Java applications can be divided into following application tiers.
 Client-tier components run on the client machine.
 Web-tier components run on the Java server.
 Business-tier components run on the Java server.
 Enterprise information system (EIS)-tier software runs on the EIS server.
It uses a distributed multi tiered application model for enterprise applications where
application logic is divided into components according to function, and the various
application components that make up a Java application are installed on different machines
depending on the tier in the multi-tiered Java environment to which the application
component belongs.
Since Java-based applications are designed to work together, the enterprise-wide adoption
of Java makes it easier to create seamless computing environments. This reduces costs for
companies already integrating their distributed systems and processes and enables more
businesses to achieve the benefits of business integration.

2.3 CREATING STUBS AND SKELETONS

STUB
The stub is an object, acts as a gateway for the client side. All the outgoing requests
are routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
 It initiates a connection with remote Virtual Machine (JVM),
 It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
 It waits for the result
 It reads (unmarshals) the return value or exception, and
 It finally, returns the value to the caller.

19
Vidhyaa Arts And Science College-Konganapuram

skeleton
The skeleton is an object, acts as a gateway for the server side object. All the
incoming requests are routed through it. When the skeleton receives the incoming request, it
does the following tasks:
 It reads the parameter for the remote method
 It invokes the method on the actual remote object, and
 It writes and transmits (marshals) the result to the caller.
 In the Java 2 SDK, an stub protocol was introduced that eliminates the need for
skeletons.

Java RMI Example


The given 6 steps to write the RMI program.
 Create the remote interface
 Provide the implementation of the remote interface
 Compile the implementation class and create the stub and skeleton objects using the
rmic tool
 Start the registry service by rmiregistry tool
 Create and start the remote application
 Create and start the client application
RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application.
The client application needs only two files, remote interface and client application. In the rmi
application, both client and server interacts with the remote interface. The client application
invokes methods on the proxy object, RMI sends the request to the remote JVM. The return
value is sent back to the proxy object and then to the client application.

20
Vidhyaa Arts And Science College-Konganapuram

1) create the remote interface


For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface. Here, we are creating a
remote interface that extends the Remote interface. There is only one method named add()
and it declares RemoteException.
import java.rmi.*;
public interface Adder extends Remote{
public int add(int x,int y)throws RemoteException;
}

2) Provide the implementation of the remote interface


Now provide the implementation of the remote interface. For providing the
implementation of the Remote interface, we need to
 Either extend the UnicastRemoteObject class,
 or use the exportObject() method of the UnicastRemoteObject class
In case, you extend the UnicastRemoteObject class, you must define a constructor that
declares RemoteException.

import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder{
AdderRemote()throws RemoteException{

21
Vidhyaa Arts And Science College-Konganapuram

super();
}
public int add(int x,int y){return x+y;}
}

3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool
invokes the RMI compiler and creates stub and skeleton objects.
rmic AdderRemote
4) Start the registry service by the rmiregistry tool
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. rmiregistry 5000
5) Create and run the server application
Now rmi services need to be hosted in a server process. The Naming class provides
methods to get and store the remote object. The Naming class provides 5 methods

In this example, we are binding the remote object by the name sonoo.
import java.rmi.*;

22
Vidhyaa Arts And Science College-Konganapuram

import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}

6) Create and run the client application


At the client we are getting the stub object by the lookup() method of the Naming
class and invoking the method on this object. In this example, we are running the server and
client applications, in the same machine so we are using localhost. If you want to access the
remote object from another machine, change the localhost to the host name (or IP address)
where the remote object is located.

import java.rmi.*;
public class MyClient{
public static void main(String args[]){
try{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));
}catch(Exception e){}
}
}

For running this rmi example,


1) compile all the java files
javac *.java
2)create stub and skeleton object by rmic tool
rmic AdderRemote
3)start rmi registry in one command prompt
rmiregistry 5000

23
Vidhyaa Arts And Science College-Konganapuram

4)start the server in another command prompt


java MyServer
5)start the client application in another command prompt
java MyClient
Output of this RMI example

24
Vidhyaa Arts And Science College-Konganapuram

2.4 DEFINING REMOTE OBJECTS

The RMI (Java Remote Method Invocation) system is a mechanism that enables an
object on one Java virtual machine to invoke methods on an object in another Java virtual
machine. Any object whose methods can be invoked in this way must implement the
java.rmi.Remote interface. When such an object is invoked, its arguments are marshalled and
sent from the local virtual machine to the remote one, where the arguments are unmarshalled
and used. When the method terminates, the results are marshalled from the remote machine
and sent to the caller's virtual machine.
To make a remote object accessible to other virtual machines, a program typically
registers it with the RMI registry. The program supplies to the registry the string name of the
remote object as well as the remote object itself. When a program wants to access a remote
object, it supplies the object's string name to the registry that is on the same machine as the
remote object. The registry returns to the caller a reference (called stub) to the remote object.
When the program receives the stub for the remote object, it can invoke methods on the
object (through the stub).
A program can also obtain references to remote objects as a result of remote calls to
other remote objects or from other naming services. For example, the program can look up a
reference to a remote object from an LDAP server that supports the schema defined RFC
2713.
The string name accepted by the RMI registry has the syntax
"rmi://hostname:port/remoteObjectName", where hostname and port identify the machine
and port, respectively, on which the RMI registry is running and remoteObjectName is the

25
Vidhyaa Arts And Science College-Konganapuram

string name of the remote object. hostname, port, and the prefix, "rmi:", are optional. If
hostname is not specified, then it defaults to the local host. If port is not specified, then it
defaults to 1099. If remoteObjectName is not specified, then the object being named is the
RMI registry itself. See the RMI specification for details.
RMI can be supported by using the Java Remote Method Protocol (JRMP) and the
Internet Inter-ORB Protocol (IIOP). The JRMP is a specialized protocol designed for RMI;
the IIOP is the standard protocol for communication between CORBA objects.
RMI over IIOP allows Java remote objects to communicate with CORBA objects that
might be written in a non-Java programming language.
Some service providers, such as Sun's LDAP service provider, support the binding of
java.rmi.Remote objects into directories. When java.rmi.Remote objects and/or RMI
registries are bound into an enterprise-wide shared namespace such as the LDAP, RMI clients
can look up java.rmi.Remote objects without knowing on which machine the objects are
running.
Binding a Remote Object
The following example defines a java.rmi.Remote interface Hello that has one
method, sayHello().
public interface Hello extends Remote {
public String sayHello() throws RemoteException;
}
It also defines an implementation of this interface, HelloImpl.
public class HelloImpl extends UnicastRemoteObject implements Hello {
public HelloImpl() throws RemoteException {
}

public String sayHello() throws RemoteException {


return ("Hello, the time is " + new java.util.Date());
}
}

2.5 REMOTE OBJECT ACTIVATION

Declaring a Remote Object Class


We can declare class HelloImpl, e.g. as follows:

26
Vidhyaa Arts And Science College-Konganapuram

public class HelloImpl extends UnicastRemoteObject


implements Hello {

This declaration states that the class implements the Hello remote interface and
extends the class java.rmi.server.UnicastRemoteObject .
By extending UnicastRemoteObject, the HelloImpl class can be used to create a
remote object that:
 Supports unicast (point-to-point) remote communication
 Uses RMI's default sockets-based transport for communication
 Runs all the time
Constructing a Remote Object
The constructor for a remote class provides the same functionality as the constructor
for a non-remote class: it initializes the variables of each newly created instance of the class,
and returns an instance of the class to the program which called the constructor.
In addition, the remote object instance will need to be "exported" . Exporting a
remote object makes it available to accept incoming remote method requests, by listening for
incoming calls to the remote object on an anonymous port. When you extend
java.rmi.server.UnicastRemoteObject or java.rmi.activation.Activatable, your class will be
exported automatically upon creation.
If you choose to extend a remote object from any class other than
UnicastRemoteObject or Activatable, you will need to explicitly export the remote object by
calling either the UnicastRemoteObject.exportObject method or the Activatable.exportObject
method from your class's constructor (or another initialization method, as appropriate).
Because the object export could potentially throw a java.rmi.RemoteException , you
must define a constructor that throws a RemoteException , even if the constructor does
nothing else. If you forget the constructor, javac will produce the following error message:
HelloImpl.java:13: Exception java.rmi.RemoteException must be caught, or it must
be declared in the throws clause of this method.
super();
^
1 error
To review: The implementation class for a remote object needs to:
 Implement a remote interface

27
Vidhyaa Arts And Science College-Konganapuram

 Export the object so that it can accept incoming remote method calls
 Declare its constructor(s) to throw at least a java.rmi.RemoteException
Here is the constructor for the hello.HelloImpl class:
public HelloImpl() throws RemoteException {
super();
}

2.6 OBJECT SERIALIZATION


Serialization in Java 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.
For serializing the object, we call 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).

28
Vidhyaa Arts And Science College-Konganapuram

java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to
"mark" Java classes so that the objects of these classes may get a certain capability. The
Cloneable and Remote are also marker interfaces.
The Serializable interface must be implemented by the class whose object needs to be
persisted.
The String class and all the wrapper classes implement the java.io.Serializable
interface by default.
Let's see the example given below:
Student.java
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

2.7 JAVA SPACES

The distributed application paradigm supported by JavaSpaces is one in which remote


agents interact with each other indirectly through shared data object spaces. Objects are
stored in a JavaSpace in the form of entries. Clients write entries into the space, read entries
from the space, or take entries from the space, as shown in Figure.

29
Vidhyaa Arts And Science College-Konganapuram

Access to the entries in JavaSpaces is through a small set of basic operations:


Read
Read an entry from the space that matches a template.
Write
Add an entry to the space.
Take
Read and remove an entry from the space.
Notify
Send a notification through a given event handler if entries that match a template are
added to the space. A notification request has a time-out period associated with it: if a
matching entry isn't added within the time-out period, the notify request fails and is dropped
from the Java Space.
Multiple basic operations can be assembled into transactions that group basic
operations into a single, atomic aggregate operation.
There can be many clients and many JavaSpaces in a given distributed application.
One client, and even one transaction from one client, can access multiple JavaSpaces. So
instead of one agent sending a message to another, or invoking a remote method directly on
another object within an agent, agents interact by writing and reading objects in JavaSpaces.
An important feature of the JavaSpaces specification is that all operations on a given

30
Vidhyaa Arts And Science College-Konganapuram

JavaSpace are considered unordered. If you have multiple threads or multiple remote agents
issuing operations on a JavaSpace, and for some reason you want to impose some order on
the operations, then it's up to you to synchronize your threads or agents as needed.
Each JavaSpace holds data in the form of entries, which can either be read, written, or
taken from a JavaSpace. Each entry has one or more fields that are used to match incoming
requests from clients. Each request to read, take, or be notified about an entry includes a
template for the entry to match. In order for an entry in the JavaSpace to match, the entry
must be of the same type as the template object. Each field in the template can either have a
non-null value, which must match the fields in a matching entry in the JavaSpace, or a null
value, which matches any value in that field.

UNIT-III
3.1 JAVA IN DATABASES

Java DB is Oracle's supported distribution of the open source Apache Derby database. Its
ease of use, standards compliance, full feature set, and small footprint make it the ideal
database for Java developers. Java DB is written in the Java programming language,
providing "write once, run anywhere" portability. It can be embedded in Java applications,
requiring zero administration by the developer or user. It can also be used in client server

31
Vidhyaa Arts And Science College-Konganapuram

mode. Java DB is fully transactional and provides a standard SQL interface as well as a
JDBC 4.1 compliant driver.
Database handlers create a database in such a way that only one set of software program
provides access of data to all the users.
The main purpose of the database is to operate a large amount of information by storing,
retrieving, and managing data.
DBMS (Data Base Management System)
Database management System is software which is used to store and retrieve the
database. For example, Oracle, MySQL, etc.; these are some popular DBMS tools.
 DBMS provides the interface to perform the various operations like creation, deletion,
modification, etc.
 DBMS allows the user to create their databases as per their requirement.
 DBMS accepts the request from the application and provides specific data through the
operating system.
 DBMS contains the group of programs which acts according to the user instruction.
 It provides security to the database.
Advantage of DBMS
1. Controls redundancy
It stores all the data in a single database file, so it can control data redundancy.
2. Data sharing
An authorized user can share the data among multiple users.
3. Backup
It providesBackup and recovery subsystem. This recovery system creates automatic
data from system failure and restores data if required.

4. Multiple user interfaces


It provides a different type of user interfaces like GUI, application interfaces.
Disadvantage of DBMS
1. Size
It occupies large disk space and large memory to run efficiently.
2. Cost
DBMS requires a high-speed data processor and larger memory to run DBMS
software, so it is costly.
3. Complexity

32
Vidhyaa Arts And Science College-Konganapuram

DBMS creates additional complexity and requirements.

3.2 JDBC PRINCIPLES

What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a wide range
of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database. Java can be used to write different types
of executables, such as,
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database, and
take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code
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.

33
Vidhyaa Arts And Science College-Konganapuram

The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver
manager with respect to the JDBC drivers and the Java application

Common JDBC Components


The JDBC API provides the following interfaces and classes:
DriverManager: This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication sub
protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to
establish a database Connection.
Driver: This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager objects,
which manages objects of this type. It also abstracts the details associated with working with
Driver objects.
Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with database is
through connection object only.
Statement: You use objects created from this interface to submit the SQL statements
to the database. Some derived interfaces accept parameters in addition to executing stored
procedures.

34
Vidhyaa Arts And Science College-Konganapuram

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.

3.3 DATABASE ACCESS

There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
 Register the Driver class
 Create connection
 Create statement
 Execute queries
 Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method
is used to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection
with the database.
Syntax of getConnection() method

35
Vidhyaa Arts And Science College-Konganapuram

1) public static Connection getConnection(String url)throws SQLException


2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the records of
a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();

36
Vidhyaa Arts And Science College-Konganapuram

3.4 INTERACTING DATABASE SEARCH

To connect to a database using JDBC, we first need to load the appropriate JDBC driver
using the DriverManager class. The following code snippet demonstrates how to load the
MySQL JDBC driver:
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Once the driver is loaded, we can establish a connection to the database using the
getConnection() method of the DriverManager class. The getConnection() method takes three
parameters: the URL of the database, the username to use for authentication, and the
password to use for authentication. The following code snippet demonstrates how to establish
a connection to a MySQL database:
Connection connection = null;
try {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "myusername";
String password = "mypassword";
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}

3.5 CREATING MULTIMEDIA DATABASE

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.

37
Vidhyaa Arts And Science College-Konganapuram

Contents of the Multimedia Database


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

38
Vidhyaa Arts And Science College-Konganapuram

The multimedia database requires a large size as the multimedia data is quite large
and needs to be stored successfully in the database.
It takes a lot of time to process multimedia data so multimedia database is slow.

3.6 DATABASE SUPPORT IN WEB APPLICATION

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
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!

39
Vidhyaa Arts And Science College-Konganapuram

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

40
Vidhyaa Arts And Science College-Konganapuram

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.

UNIT – IV

4.1 JAVA SERVLETS

Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming

41
Vidhyaa Arts And Science College-Konganapuram

language. However, there were many disadvantages to this technology. We have discussed
these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
 Servlet can be described in many ways, depending on the context.
 Servlet is a technology which is used to create a web application.
 Servlet is an API that provides many interfaces and classes including documentation.
 Servlet is an interface that must be implemented for creating any Servlet.
 Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
 Servlet is a web component that is deployed on the server to create a dynamic web
page.

4.1.1 JAVA SERVLET AND CGI PROGRAMMING

What is a web application?


A web application is an application accessible from the web. A web application is
composed of web components like Servlet, JSP, Filter, etc. and other elements such as
HTML, CSS, and JavaScript. The web components typically execute in Web Server and
respond to the HTTP request.
CGI (Common Gateway Interface)

42
Vidhyaa Arts And Science College-Konganapuram

CGI technology enables the web server to call an external program and pass HTTP
request information to the external program to process the request. For each request, it starts a
new process.

Disadvantages of CGI
There are many problems in CGI technology:
 If the number of clients increases, it takes more time for sending the response.
 For each request, it starts a process, and the web server is limited to start processes.
 It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet

43
Vidhyaa Arts And Science College-Konganapuram

There are many advantages of Servlet over CGI. The web container creates threads
for handling the multiple requests to the Servlet. Threads have many benefits over the
Processes such as they share a common memory area, lightweight, cost of communication
between the threads are low. The advantages of Servlet are as follows:
 Better performance: because it creates a thread for each request, not process.
 Portability: because it uses Java language.
 Robust: JVM manages Servlets, so we don't need to worry about the memory leak,
garbage collection, etc.
 Secure: because it uses java language.

4.1.2 ANATOMY OF A JAVA SERVLET

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of
the servlet:
 Servlet class is loaded.
 Servlet instance is created.
 init method is invoked.
 service method is invoked.
 destroy method is invoked.

44
Vidhyaa Arts And Science College-Konganapuram

As displayed in the above diagram, there are three states of a servlet: new, ready and
end. The servlet is in new state if servlet instance is created. After invoking the init() method,
Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the
web container invokes the destroy() method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException
4) service method is invoked
The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above then
calls the service method. If servlet is initialized, it calls the service method. Notice that

45
Vidhyaa Arts And Science College-Konganapuram

servlet is initialized only once. The syntax of the service method of the Servlet interface is
given below:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet interface is given below:
public void destroy()

4.1.3 READING DATA FROM A CLIENT

Servlet Read Form Data


This Servlet tutorial is to take you to the next step in learning servlets. As stated
earlier in start of the servlet tutorial series, servlets are primarily meant for web applications.
In this let us see how we can read html form data from a URL and process it in a servlet and
then send the response back to the client.
GET and POST method
As seen earlier in Servlet terminologies, GET and POST methods are used to pass
information from a form to a Java Servlet. While using GET method the form data is passed
in the url as query parameters. GET method is the default method used. It looks like,
http://localhost:8080/hello?key1=value1&key2=value2
If POST method is used then the form data is passed in the HTTP request message
body. It cannot be seen in the URL as seen in GET method. URL length has a limitation and
so if we are passing large volume of data we should use POST. Similarly sensitive data like
passwords should also be passed using POST method.
Read Form Data
We have methods doXYZ(…) in the HTTPServlet class. The method doGet(…) is
invoked by the servlet container if the form uses GET method or doPost(…) if the the form
uses POST method. In this example we are using GET method.
package com.javapapers.servlet.introduction;

46
Vidhyaa Arts And Science College-Konganapuram

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloFormData extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet: Read Form Data";
out.println("<html>" + "<head><title>" + title
+ "</title></head><body>"
+ "<h1>" + title + "</h1>"
+ "<p>Hi "
+ request.getParameter("name")
+ "</p>"
+ "</body></html>");
}
}

Read using POST method


In the above HTML page in form tag instead of GET use as POST. Then in the servlet
to read the form data add a doPost method as below,

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

47
Vidhyaa Arts And Science College-Konganapuram

4.1.4 READING HTTP REQUEST HEADER

When a browser requests for a web page, it sends lot of information to the web server
which cannot be read directly because this information travel as a part of header of HTTP
request. You can check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and
you would use very frequently in web programming

Sr.No. Header & Description


1 Accept
This header specifies the MIME types that the browser or other clients
can handle. Values of image/png or image/jpeg are the two most common
possibilities.
2 Accept-Charset
This header specifies the character sets the browser can use to display
the information. For example ISO-8859-1.
3 Accept-Encoding

48
Vidhyaa Arts And Science College-Konganapuram

This header specifies the types of encodings that the browser knows
how to handle. Values of gzip or compress are the two most common
possibilities.
4 Accept-Language
This header specifies the client's preferred languages in case the servlet
can produce results in more than one language. For example en, en-us, ru, etc
5 Authorization
This header is used by clients to identify themselves when accessing
password-protected Web pages.
6 Connection
This header indicates whether the client can handle persistent HTTP
connections. Persistent connections permit the client or other browser to
retrieve multiple files with a single request. A value of Keep-Alive means that
persistent connections should be used.
7 Content-Length
This header is applicable only to POST requests and gives the size of
the POST data in bytes.

8 Cookie
This header returns cookies to servers that previously sent them to the
browser.
9 Host
This header specifies the host and port as given in the original URL.
10 If-Modified-Since
This header indicates that the client wants the page only if it has been
changed after the specified date. The server sends a code, 304 which means
Not Modified header if no newer result is available.
11 If-Unmodified-Since
This header is the reverse of If-Modified-Since; it specifies that the
operation should succeed only if the document is older than the specified date.
12 Referer
This header indicates the URL of the referring Web page. For example,
if you are at Web page 1 and click on a link to Web page 2, the URL of Web

49
Vidhyaa Arts And Science College-Konganapuram

page 1 is included in the Referrer header when the browser requests Web page
2.
13 User-Agent
This header identifies the browser or other client making the request
and can be used to return different content to different types of browsers.
Request Header Example
Following example displays the HTTP header information. Here we have used
method getHeaderNames() to get the information.
package javabeat.net.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestHeaderDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Headers<hr/>");
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
out.print("Header Name: <em>" + headerName);
String headerValue = request.getHeader(headerName);
out.print("</em>, Header Value: <em>" + headerValue);
out.println("</em><br/>");
} }}

50
Vidhyaa Arts And Science College-Konganapuram

4.1.5 SENDING DATA TO A CLIENT AND WRITING THE HTTP


RESPONSE HEADER

HTTP Response sent by a server to the client. The response is used to provide the
client with the resource it requested. It is also used to inform the client that the action
requested has been carried out. It can also inform the client that an error occurred in
processing its request.
 An HTTP response contains the following things:
 Status Line
 Response Header Fields or a series of HTTP headers
Message Body
In the request message, each HTTP header is followed by a carriage returns line feed
(CRLF). After the last of the HTTP headers, an additional CRLF is used and then begins the
message body.
Status Line
In the response message, the status line is the first line. The status line contains three
items:
a) HTTP Version Number
It is used to show the HTTP specification to which the server has tried to make the
message comply.
Example
HTTP-Version = HTTP/1.1
b) Status Code
It is a three-digit number that indicates the result of the request. The first digit defines
the class of the response. The last two digits do not have any categorization role. There are
five values for the first digit, which are as follows:
Code and Description
1xx: Information
It shows that the request was received and continuing the process.
2xx: Success
It shows that the action was received successfully, understood, and accepted.
3xx: Redirection
It shows that further action must be taken to complete the request.
4xx: Client Error

51
Vidhyaa Arts And Science College-Konganapuram

It shows that the request contains incorrect syntax, or it cannot be fulfilled.


5xx: Server Error
It shows that the server failed to fulfil a valid request.
c) Reason Phrase
It is also known as the status text. It is a human-readable text that summarizes the
meaning of the status code.
An example of the response line is as follows:
HTTP/1.1 200 OK
Here,
HTTP/1.1 is the HTTP version.
200 is the status code.
OK is the reason phrase.
Response Header Fields
The HTTP Headers for the response of the server contain the information that a client
can use to find out more about the response, and about the server that sent it. This
information is used to assist the client with displaying the response to a user, with storing the
response for the use of future, and with making further requests to the server now or in the
future.
response-header = Accept-Ranges
o Age
o ETag
o Location
o Proxy-Authenticate
o Retry-After
o Server
o Vary
o WWW-Authenticate
The name of the Response-header field can be extended reliably only in combination
with a change in the version of the protocol.
Message Body
The response's message body may be referred to for convenience as a response body.

52
Vidhyaa Arts And Science College-Konganapuram

The body of the message is used for most responses. The exceptions are where a
server is using certain status codes and where the server is responding to a client request,
which asks for the headers but not the response body.
For a response to a successful request, the body of the message contains either some
information about the status of the action which is requested by the client or the resource
which is requested by the client. For the response to an unsuccessful request, the body of the
message might provide further information about some action the client needs to take to
complete the request successfully or about the reason for the error.

4.1.6 WORKING WITH COOKIES

A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
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.
 Non-persistent cookie
 Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the
browser.

53
Vidhyaa Arts And Science College-Konganapuram

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
 Simplest technique of maintaining the state.
 Cookies are maintained at client side.
Disadvantage of Cookies
 It will not work if cookie is disabled from the browser.
 Only textual information can be set in Cookie object.

4.2 JAVA SERVER PAGES

JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role
of a user interface for a Java web application. Web developers write JSPs as text files that
combine HTML or XHTML code, XML elements, and embedded JSP actions and
commands.
Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control
between pages, and sharing information between requests, pages etc.
Why Use JSP?
JavaServer Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But JSP offers several advantages in comparison with the
CGI.
Performance is significantly better because JSP allows embedding Dynamic Elements
in HTML Pages itself instead of having separate CGI files.
JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time the page is
requested.

54
Vidhyaa Arts And Science College-Konganapuram

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.

4.2.1 JSP OVERVIEW

JSP technology is used to create web application just like Servlet technology. It can
be thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain
than Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.
Advantages of JSP over Servlet
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of
the Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.
 Play
 Next
 Unmute
 Current TimeÂ
 0:05
 /
 DurationÂ
 18:10
 Â
 Fullscreen
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.

55
Vidhyaa Arts And Science College-Konganapuram

3) Fast Development: No need to recompile and redeploy


If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look and feel of the
application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces
the code. Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page
The JSP pages follow these phases:
 Translation of JSP Page
 Compilation of JSP Page
 Classloading (the classloader loads class file)
 Instantiation (Object of the Generated Servlet is created).
 Initialization ( the container invokes jspInit() method).
 Request processing ( the container invokes _jspService() method).
 Destroy ( the container invokes jspDestroy() method)

4.2.2 JSP INSTALLATION

56
Vidhyaa Arts And Science College-Konganapuram

A development environment is where you would develop your JSP programs, test
them and finally run them.
This tutorial will guide you to setup your JSP development environment which
involves the following steps −
Setting up Java Development Kit
This step involves downloading an implementation of the Java Software Development
Kit (SDK) and setting up the PATH environment variable appropriately.
You can download SDK from Oracle's Java site − Java SE Downloads.
Once you download your Java implementation, follow the given instructions to install
and configure the setup. Finally set the PATH and JAVA_HOME environment variables to
refer to the directory that contains java and javac, typically java_install_dir/bin and
java_install_dir respectively.
If you are running Windows and install the SDK in C:\jdk1.5.0_20, you need to add
the following line in your C:\autoexec.bat file.
set PATH = C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME = C:\jdk1.5.0_20
Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer,
select Properties, then Advanced, followed by Environment Variables. Then, you would
update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and
you use the C shell, you will put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.5.0_20
Alternatively, if you use 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.

4.2.3 JSP TAGS

JSP scripting language include several tags or scripting elements that performs
various tasks such as declaring variables and methods, writing expressions, and calling other
JSP pages. These are known as JSP scripting elements. The different types of scripting
elements are summarized in the Table.

57
Vidhyaa Arts And Science College-Konganapuram

Example code showing different types of JSP Tags:


<%-- Counter.jsp --%> <%-- Comment Tag --%>
<%@ page language="java" %> <%-- Directive Tag --%>
<%! int count = 0; %> <%-- Declaration Tag --%>
<% count++; %> <%-- Scriptlet Tag --%>
Welcome! You are visitor number
<%= count %> <%-- Expression Tag --%>

4.2.4 COMPONENTS OF A JSP PAGE

JSPs are comprised of standard HTML tags and JSP tags. The structure of JavaServer
pages are simple and easily handled by the servlet engine. In addition to HTML ,you can
categorize JSPs as following
 Directives
 Declarations
 Scriptlets

58
Vidhyaa Arts And Science College-Konganapuram

 Comments
 Expressions
Directives :
A directives tag always appears at the top of your JSP file. It is global definition sent
to the JSP engine. Directives contain special processing instructions for the web container.
You can import packages, define error handling pages or the session information of the JSP
page. Directives are defined by using <%@ and %> tags.
Syntax:
<%@ directive attribute="value" %>
Declarations:
This tag is used for defining the functions and variables to be used in the JSP. This
element of JSPs contains the java variables and methods which you can call in expression
block of JSP page. Declarations are defined by using <%! and %> tags. Whatever you declare
within these tags will be visible to the rest of the page.
Syntax
<%! declaration(s) %>
Scriptlets:
In this tag we can insert any amount of valid java code and these codes are placed in
_jspService method by the JSP engine. Scriptlets can be used anywhere in the page. Scriptlets
are defined by using <% and %> tags. Ezoic
Syntax
<% Scriptlets%>
Comments:
Comments help in understanding what is actually code doing. JSPs provides two
types of comments for putting comment in your page. First type of comment is for output
comment which is appeared in the output stream on the browser. It is written by using the
<!-- and --> tags.
Syntax
<!-- comment text -->
Second type of comment is not delivered to the browser. It is written by using the <%-- and --
%> tags.

Syntax
<%-- comment text --%>

59
Vidhyaa Arts And Science College-Konganapuram

Expressions:
Expressions in JSPs is used to output any data on the generated page. These data are
automatically converted to string and printed on the output stream. It is an instruction to the
web container for executing the code with in the expression and replace it with the resultant
output content. For writing expression in JSP, you can use <%= and %> tags.
Syntax
<%= expression %>

4.2.5 EXPRESSIONS

xpression tags are one of the most useful scripting elements of JSP. Expression tags
use special tags to print the different java expressions and output directly on the client-side.
You can also use this for displaying information on your client browser. In this chapter, you
will learn about implementing expression tags and know how to use it.
xpression tags are one of the most useful scripting elements of JSP. Expression tags
use special tags to print the different java expressions and output directly on the client-side.
You can also use this for displaying information on your client browser. In this chapter, you
will learn about implementing expression tags and know how to use it.
The expression tag is used to evaluate Java's expression within the JSP, which then
converts the result into a string and forwards the result back to the client browser via the
response object. Essentially, it is implemented for printing the result to the client (browser).
An expression tag can hold any java language expression that can be employed as an
argument to the out.print() method.
The syntax of the expression tag in JSP looks something like:
<%= expression %>
Example of JSP expression tag
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>

60
Vidhyaa Arts And Science College-Konganapuram

4.2.6 SCRIPTS

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:
 scriptlet tag
 expression tag
 declaration tag
JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name
In this example, we have created two files index.html and welcome.jsp. The
index.html file gets the username from the user and the welcome.jsp file prints the username
with the welcome message.
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

61
Vidhyaa Arts And Science College-Konganapuram

<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>

4.2.7 DIRECTIVES

The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
There are three types of directives:
 page directive
 include directive
 tag lib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>

Attributes of JSP page directive


 import
 contentType
 extends
 info
 buffer
 language
 isELIgnored

62
Vidhyaa Arts And Science College-Konganapuram

 isThreadSafe
 autoFlush
 session
 pageEncoding
 errorPage
 isErrorPage
1) import
The import attribute is used to import class,interface or all the members of a
package.It is similar to import keyword in java class or interface.
Example of import attribute
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>

2) contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension)
type of the HTTP response.The default value is "text/html;charset=ISO-8859-1".
Example of contentType attribute
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>

3) extends
The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.

63
Vidhyaa Arts And Science College-Konganapuram

4) info
This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.
Example of info attribute
<html>
<body>
<%@ page info="composed by Sonoo Jaiswal" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

The web container will create a method getServletInfo() in the resulting servlet.For example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}

5) buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the
JSP page.The default size of the buffer is 8Kb.
Example of buffer attribute
<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

6) language
The language attribute specifies the scripting language used in the JSP page. The
default value is "java".
7) isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By
default its value is false i.e. Expression Language is enabled by default. We see Expression
Language later.

64
Vidhyaa Arts And Science College-Konganapuram

<%@ page isELIgnored="true" %>//Now EL will be ignored


8) isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP
page, you can use isThreadSafe attribute of page directive.The value of isThreadSafe value is
true.If you make it false, the web container will serialize the multiple requests, i.e. it will wait
until the JSP finishes responding to a request before passing another request to it.If you make
the value of isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
The web container in such a case, will generate the servlet as:
public class SimplePage_jsp extends HttpJspBase
implements SingleThreadModel{
.......
}

9) errorPage
The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.
Example of errorPage attribute
//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>

10) isErrorPage
` The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.
Example of isErrorPage attribute
//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>

65
Vidhyaa Arts And Science College-Konganapuram

Sorry an exception occured!<br/>


The exception is: <%= exception %>
</body>
</html>

4.2.8 DECLARATION

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:
<%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration tag

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the
value of the declared field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>

Example of JSP declaration tag that declares method

66
Vidhyaa Arts And Science College-Konganapuram

In this example of JSP declaration tag, we are defining the method which returns the
cube of given number and calling this method from the jsp expression tag. But we can also
use jsp scriptlet tag to call the declared method.
index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

67
Vidhyaa Arts And Science College-Konganapuram

UNIT – V

5.1 JAR FILE FORMAT CREATION

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:

68
Vidhyaa Arts And Science College-Konganapuram

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.

69
Vidhyaa Arts And Science College-Konganapuram

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 export the source code.

70
Vidhyaa Arts And Science College-Konganapuram

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 option, or changing the default
manifest.

71
Vidhyaa Arts And Science College-Konganapuram

72
Vidhyaa Arts And Science College-Konganapuram

For now, we skip the Next and click on the Finish button.
6. 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.

5.2 INTERNATIONALIZATION

Internationalization is also abbreviated as I18N because there are total 18 characters


between the first letter 'I' and the last letter 'N'.
Internationalization is a mechanism to create such an application that can be adapted to
different languages and regions.
Internationalization is one of the powerful concept of java if you are developing an
application and want to display messages, currencies, date, time etc. according to the specific
region or language.
Internationalization Classes
Java has a set of built-in classes which help in internationalization of an application.
These classes are following:
Sr.No. Class & Description
1 Locale
Represents a language along with country/region.
2 ResourceBundle
Contains localized text or objects.
3 NumberFormat
Use to format numbers/currencies as per the locale.
4 DecimalFormat
Use to format numbers as per customized format and as per locale.
5 DateFormat
Use to format dates as per locale.
6 SimpleDateFormat

73
Vidhyaa Arts And Science College-Konganapuram

Use to format dates as per customized format and as per locale.

5.3 SWING PROGRAMMING

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

Commonly used Methods of Component class


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

74
Vidhyaa Arts And Science College-Konganapuram

Java Swing Examples


There are two ways to create a frame:
 By creating the object of Frame class (association)
 By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding it on
the JFrame object inside the main() method.
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

75
Vidhyaa Arts And Science College-Konganapuram

5.4 ADVANCED JAVA

The dictionary meaning of advance is a forward movement or a development or


improvement and the meaning of improve means thing that makes something better. All in
all, we have to improve our basic knowledge to master in that particular field.
Java is divided into two parts i.e. Core Java (J2SE) and Advanced Java (JEE). The core
Java part covers the fundamentals (data types, functions, operators, loops, thread, exception
handling, etc.) of the Java programming language. It is used to develop general purpose
applications. Whereas Advanced Java covers the standard concepts such as database
connectivity, networking, Servlet, web-services, etc. In this section, we will discuss what is
advance Java, its benefit, uses, topics of advance Java, and the difference between core Java
and advance Java.
Advance Java
It is a part of Java programming language. It is an advanced technology or advance
version of Java specially designed to develop web-based, network-centric or enterprise
applications. It includes the concepts like Servlet, JSP, JDBC, RMI, Socket programming,
etc. It is a specialization in specific domain.

76
Vidhyaa Arts And Science College-Konganapuram

Most of the applications developed using advance Java uses tow-tier architecture i.e.
Client and Server. All the applications that runs on Server can be considered as advance Java
applications.
Why advance Java?
It simplifies the complexity of a building n-tier application.
Standardizes and API between components and application sever container.
JEE application Server and Containers provides the framework services.
Benefits of Advance Java
The four major benefits of advance Java that are, network centric, process
simplification, and futuristic imaging standard.
JEE (advance Java) provides libraries to understand the concept of Client-Server
architecture for web- based applications.
We can also work with web and application servers such as Apache Tomcat and
Glassfish Using these servers, we can understand the working of HTTP protocol. It cannot be
done in core Java.
It is also important understand the advance Java if you are dealing with trading
technologies like Hadoop, cloud-native and data science.
It provides a set of services, API and protocols, that provides the functionality which
is necessary for developing multi-tiered application, web-based application.
There is a number of advance Java frameworks like, Spring, Hibernate, Struts, that
enables us to develop secure transaction-based web applications such as banking application,
inventory management application.
Difference between Core Java and Advance Java

77
Vidhyaa Arts And Science College-Konganapuram

MODEL QUESTION PAPER


VIDHYAA ARTS AND SCIENCE COLLEGE KONGANAPURAM
M.SC (Computer Science) Degree Examinations
ADVANCED JAVA PROGRAMMING
Time: 3 Hrs Maximum: 75 Marks

PART-A (15×1=15) Marks


ANSWER ALL QUESTIONS
1. Which of the following code is used to get an attribute in a HTTP Session object in
servlets?
a) session.getAttribute(String name) b) session.alterAttribute(String name)
c) session.updateAttribute(String name) d) session.setAttribute(String name)
2.. Which method is used to get three-letter abbreviation for locale’s country in servlets?
a) Request.getISO3Country() b) Locale.getISO3Country()
c) Response.getISO3Country() d) Local.retrieveISO3Country()
3.. Which of the following code retrieves the body of the request as binary data?
a) DataInputStream data = new InputStream()
b) DataInputStream data = response.getInputStream()
c) DataInputStream data = request.getInputStream()
d) DataInputStream data = request.fetchInputStream()
4. When destroy() method of a filter is called?
a) The destroy() method is called only once at the end of the life cycle of a filter
b) The destroy() method is called after the filter has executed doFilter method
c) The destroy() method is called only once at the begining of the life cycle of a filter
d) The destroyer() method is called after the filter has executed
5. Which of the following is true about servlets?
a) Servlets execute within the address space of web server
b) Servlets are platform-independent because they are written in java
c) Servlets can use the full functionality of the Java class libraries
d) Servlets execute within the address space of web server, platform independent and
uses the functionality of java class libraries

6. Which of these is a protocol for breaking and sending packets to an address across a

78
Vidhyaa Arts And Science College-Konganapuram

network?
a) TCP/IP b) DNS c) Socket d) Proxy Server
7. Which of these class is used to encapsulate IP address and DNS?
a) DatagramPacket b) URL c) InetAddress d) ContentHandle
8. Which class is message that can be sent or received. If you send multiple packet, it may
arrive in any order,Moreover, packet delivery is not guaranteed?
a) DatagramPacket b) DatagramSocket c) Both A & B d) None of the above
9. The difference between Servlets and JSP is the __________
a)translation b) compilation c) syntax d) Both A and B
10. Which of the following are the valid scopes in JSP?
a)request, page, session, application
b)request, page, session, global
c)response, page, session, application
d)request, page, context, application
11. What type of scriptlet code is better-suited to being factored forward into a servlet?
a) Code that deals with logic that is common across requests
b) Code that deals with logic that is vendor specific
c) Code that deals with logic that relates to database access
d). Code that deals with logic that relates to client scope
12. How to send data in get method?
a) We can't b) Through url c) Through payload d). None of these
13. Which of the following functional interface represents an operation that accepts a single
int-valued argument and returns no result?
a) IntConsumer b) IntFunction<R> c) IntPredicate d) IntSupplier
14. What REPL stands for?
a)Read Eval Print Loop b).Reactive Efficient Printable Live
c) Replaceable PLatform. d) .None of the above.
15.What is goal behind MultiResolutionImage Interface?
a) It supports multiple images with different resolution variants.
b) This allows a set of images with different resolution to be used as a single multi-
resolution image.
c) Both of the above d) None of the above

79
Vidhyaa Arts And Science College-Konganapuram

PART-B (2×5=10) Marks


Answer any Two questions
16, Explain about priority Queue in java
17. Explain about the Applet
18. Explain about the steps for developing an JD BC application
19. Explain Functional Interface
20. Explain resolution Image API.
PART-C (5×10=50Marks)
Answer All the Questions
21. (a) Explain about the Proxy and Command Pattern in detail (OR)
(b) Explain about the collection interfaces in java
22 .(a) Explain about the AWT (OR)
(b) Explain about the Tree and Table concept in Java
23(a).Explain about JDBC classes and interfaces (OR)
(b).Explain about Servlet Life Cycle
24(a).Explain about the Cookies (OR)
(b) Explain about the JShell
25.(a) Explain Private Interface Methods (OR)
(b) Explain resolution Image API.

VIDHYAA ARTS AND SCIENCE COLLEGE KONGANAPURAM


M.SC (Computer Science) Degree Examinations

80
Vidhyaa Arts And Science College-Konganapuram

ADVANCED JAVA PROGRAMMING


OBJECTIVE QUESTIONS
01. Which of the following is not a kind of exception that is thrown by the JDBC method?
a) DataRounding b) SQL Exception c) DataTruncation d) SQL Warning
Answer : A
02. Which of the following option leads to the portability and security of Java?
a) The applet makes the Java code secure and portable b) Bytecode is executed by JVM
c) Use of exception handling d)Dynamic binding between objects
Answer : B
03. When the ejb Remove method encounters a system problem, it should throw_______
a) javax.ejb.NoSuchEntityException b)java.ejb.RemoveException
c) java.ejb.EJBException d)javax.ejb.DuplicateKeyException
Answer : C
04. What are the major components of the JDBC?
a) DriverManager, Statement, and ResultSet
b) DriverManager, Connection, Statement, and ResultSet
c) DriverManager, Driver, Connection, and Statement
d) DriverManager, Driver, Connection, Statement, and ResultSet
Answer : D
05. Which of the following is correct about the Statement class of JDBC?
a) Statement encapsulates an SQL statement which is passed to the database to be planned
and executed
b) Statement encapsulates an SQL statement which is passed to the database to be parsed and
compiled
c) Both of the mentioned d)None of the mentioned
Answer : C
06. Which of the following is advantage of using JDBC connection pool?
a)Better performance b)Slow performance c)Using more memory d)Using less memory
Answer : A

07. The method on the result set that tests whether or not there remains at least one unfetched
tuple in the result set, is said to be

81
Vidhyaa Arts And Science College-Konganapuram

a)Fetch method b)Next method c)Current method d)Access method


Answer : B
08. To run a compiled java program the machine must have the following loaded and running
a)Java virtual machine b)Java compiler
c)Java bytecode d)A Web browser Answer : A
09. Which is responsible for getting a connection to the database?
a)Connection b)Driver
c)Statement d)ResultSet
Answer : B
10. Thin driver is also known as?
a)Type 3 Driver b)Type-2 Driver
c)Type-4 Driver d)Type-1 Driver
Answer : C

82

You might also like