I MSC Cs Advanced Java Programming
I MSC Cs Advanced Java Programming
KONGANAPURAM
Prepared By
Mr.V.RASAGOUNDAN M.C.A.,M.Phil.,
SYLLABUS
ADVANCED JAVA PROGRAMMING
Unit:1 BASICS OF JAVA
Java Basics Review: Components and event handling – Threading concepts – Networking
features – Media techniques
Unit:3 DATABASE
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
Text Books
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
3 Deitel and Deitel, “Java How to Program”, Third Edition, PHI/Pearson Education Asia.
Vidhyaa Arts And Science College-Konganapuram
UNIT-I
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.
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.
3
Vidhyaa Arts And Science College-Konganapuram
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
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:
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)
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:
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
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.
12
Vidhyaa Arts And Science College-Konganapuram
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
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
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.
18
Vidhyaa Arts And Science College-Konganapuram
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.
20
Vidhyaa Arts And Science College-Konganapuram
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);}
}
}
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){}
}
}
23
Vidhyaa Arts And Science College-Konganapuram
24
Vidhyaa Arts And Science College-Konganapuram
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 {
}
26
Vidhyaa Arts And Science College-Konganapuram
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();
}
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;
}
}
29
Vidhyaa Arts And Science College-Konganapuram
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.
32
Vidhyaa Arts And Science College-Konganapuram
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
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.
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
35
Vidhyaa Arts And Science College-Konganapuram
36
Vidhyaa Arts And Science College-Konganapuram
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();
}
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
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.
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
UNIT – IV
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.
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.
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
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>");
}
}
47
Vidhyaa Arts And Science College-Konganapuram
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
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
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
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.
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.
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.
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
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.
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
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" %>
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
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
4.2.8 DECLARATION
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
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
73
Vidhyaa Arts And Science College-Konganapuram
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.
74
Vidhyaa Arts And Science College-Konganapuram
75
Vidhyaa Arts And Science College-Konganapuram
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
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
80
Vidhyaa Arts And Science College-Konganapuram
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
82