I PG Java Notes
I PG Java Notes
I PG Java Notes
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 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
PROGRAMMING UNIT-1
BASICS OF JAVA
Java
EDITIONS OF JAVA
Each edition of Java has different capabilities. There are three editions of Java:
There are four types of Java applications that can be created using Java programming:
FEATURES OF JAVA
o Simple: Java is a simple language because its syntax is simple, clean,
and easy to understand. Complex and ambiguous concepts of C++ are
either eliminated or re- implemented in Java. For example, pointer and
operator overloading are not used in Java.
o Object-Oriented: In Java, everything is in the form of the object. It
means it has some data and behavior. A program must have at least one
class and object.
o Robust: Java makes an effort to check error at run time and compile
time. It uses a strong memory management system called garbage
collector. Exception handling and garbage collection features make it
strong.
o Secure: Java is a secure programming language because it has no
explicit pointer and programs runs in the virtual machine. Java contains a
security manager that defines the access of Java classes.
o Platform-Independent: Java provides a guarantee that code writes
once and run anywhere. This byte code is platform-independent and can
be run on any machine.
Java
Our core Java programming tutorial is designed for students and working
professionals. Java is an object-oriented, class-based, concurrent, secured and
general- purpose computer-programming language. It is a widely used robust
technology.
What is Java?
Java Example
Simple.java
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Application
According to Sun, 3 billion devices run Java. There are many devices where
Java is currently used. Some of them are as follows:
There are mainly 4 types of applications that can be created using Java programming:
1)Standalone Application
2)Web Application
An application that runs on the server side and creates a dynamic page is
called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF,
etc. technologies are used for creating web applications in Java.
3)Enterprise Application
4)Mobile Application
4)JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
REGISTRATION METHODS
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o Menu Item
o public void addActionListener(ActionListener a){}
o Text Field
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o Text Area
o public void addTextListener(TextListener a){}
o Check box
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
public void set Bounds(int xaxis, int yaxis, int width, int height); have
been used in the above example that sets the position of the component it may
be button, text field
The following figure represents the Java Architecture in which each step is
elaborate graphically.
Now let's dive deep to get more knowledge about Java Architecture. As we
know that the Java architecture is a collection of components, so we will discuss
each and every component into detail.
The main feature of Java is WORA. WORA stands for Write Once Run
Anywhere. The feature states that we can write our code once and use it
anywhere or on any operating system. Our Java program can run any of the
platforms only because of the Java Virtual Machine. It is a Java platform
component that gives us an environment to execute java programs. JVM's main
task is to convert byte code into machine code.
JVM, first of all, loads the code into memory and verifies it. After that, it
executes the code and provides a runtime environment. Java Virtual Machine
(JVM) has its own architecture, which is given below:
JVM Architecture
JVM is an abstract machine that provides the environment in which Java byte
code is executed. The falling figure represents the architecture of the JVM.
Class Loader: Class Loader is a subsystem used to load class files. Class
Loader first loads the Java code whenever we run it.
Class Method Area: In the memory, there is an area where the class data is
stored during the code's execution. Class method area holds the information of
static variables, static methods, static blocks, and instance methods.
Native Stack: It contains the information of all the native methods used in our
application.
Execution Engine: It is the central part of the JVM. Its main task is to execute
the byte code and execute the Java classes. The execution engine has three
main components used for executing Java classes.
o Interpreter: It converts the byte code into native code and executes. It
sequentially executes the code. The interpreter interprets continuously
and even the same method multiple times. This reduces the performance
of the system, and to solve this, the JIT compiler is introduced.
o JIT Compiler: JIT compiler is introduced to remove the drawback of the
interpreter. It increases the speed of execution and improves
performance.
o Garbage Collector: The garbage collector is used to manage the
memory, and it is a program written in Java. It works in two phases, i.e.,
Mark and Sweep. Mark is an area where the garbage collector identifies
the used and unused chunks of memory. The Sweep removes the
identified object from the Mark
Java Native Interface works as a mediator between Java method calls and native libraries.
It provides an environment in which Java programs are executed. JRE takes our
Java code, integrates it with the required libraries, and then starts the JVM to
execute it. To learn more about the Java Runtime Environment,
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.
o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.
Thread Model
Just like a process, a thread exists in several states. These states are as follows:
2)Running
3)Suspended
4)Blocked
5)Terminated
A thread comes in this state when at any given time, it halts its
execution immediately.
Creating Thread
o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name,
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.
ThreadExample1.java
Output:
Let's takes an example to understand how we can create, start and run the
thread using the runnable interface.
Let's takes an example to understand how we can create, start and run the
thread using the runnable interface.
Java Networking
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1)IP Address
2)Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3)Port Number
4)MAC Address
6)Socket
programming.
Java.net package
Inet4Address Inet6Address
NETWORKING FEATURES
In Java, there are several networking features that allow developers to
create networked applications. Some of the most commonly used networking
features in Java are:
Java.net package:
This package provides classes to implement network protocols, such as
TCP/IP, UDP, Sockets, and URLs. It allows developers to establish connections
and communicate with other computers over a network.
Socket programming:
Java's java.net.Socket class provides a low-level interface for
networking. It allows developers to create client-server applications using
TCP/IP or UDP protocols. Sockets can be used to send and receive data over a
network.
URL handling:
Java's java.net.URL class provides methods to handle URLs. It allows
developers to read and write data from a specified URL, such as reading a
webpage or downloading a file from the internet.
InetAddress class:
The java.net.InetAddress class is used to represent Internet Protocol (IP) addresses.
It provides methods to get the IP address of a host, resolve hostnames, and
perform IP address manipulation.
Network interfaces:
Java's java.net.NetworkInterface class provides methods to retrieve
information about network interfaces on the system. It allows developers to
determine available network interfaces, their IP addresses, and other related
information.
These are just a few of the networking features provided by Java. By utilizing
these features, developers can create robust and efficient networked
applications in Java.
MULTIMEDIA
Multimedia, by definition, is the use of text, audio, video, graphics, and animation
to convey information in an engaging and dynamic way. In other terms, multimedia
is a technological way of presenting information that combines audio, video,
images, and animations with textual data. Examples include video conferencing,
Yahoo Messenger, email, and the Multimedia Messaging Service ( MMS Service
(MMS).
COMPONENTS OF MULTIMEDIA
1) Text - Text appears in all multi-media projects to some extent. To match the
successful presentation of the multimedia program, the text may be presented in a
variety of font styles and sizes.
o Bitmap - Bitmap images are authentic pictures that can be taken using tools
like digital cameras or scanners. Bitmap pictures are often not modifiable.
Memory use for bitmap pictures is high.
o Vector Graphics - Computers can draw vector graphics because they just
need a little amount of memory. These images can be changed.
4) Audio - Speech, music, and sound effects could all be necessary for a
multimedia application. They are referred to as the audio or sound component of
multimedia. Speaking is a fantastic educational tool. Analog and digital audio are
both kinds. The initial sound signal is referred to as analog audio or sound. Digital
sound is saved on a computer. Digital audio is therefore utilized for sound in
multimedia applications.
5)Video - The term "video" describes a moving image that is supported by sound,
such as a television image. A multimedia application's video component conveys a
lot of information quickly. For displaying real-world items in multimedia
applications, digital video is helpful. If uploaded to the internet, the video really
does have the highest performance requirements for computer memory and
bandwidth. The quality of digital video files may still be preserved while being
saved on a computer, similarly to other data. A computer network allows for the
transport of digital video files. The digital video snippets are simple to modify.
3)For business purposes - There are several commercial uses for multimedia.
Multimedia and communication technologies have made it possible for information
from international work groups. Today's team members can work remotely and for
a variety of businesses. A global workplace will result from this. The following
facilities should be supported by the multimedia network:
o Office needs
o Records management
o Employee training
o Electronic mail
o Voice mail
5)For banking purposes - Another public setting where multimedia is being used
more and more recently is banks. People visit banks to open savings and current
accounts, make deposits and withdrawals, learn about the bank's various financial
plans, apply for loans, and other things. Each bank wants to notify its consumers
with a wealth of information. It can employ multimedia in a variety of ways to do
this. The bank also has a PC monitor in the clients' rest area that shows details
about its numerous programs. Online and internet banking have grown in
popularity recently. These heavily rely on multimedia. As a result, banks are using
multimedia to better serve their clients and inform them of their appealing
financing options.
Image Manipulation:
Java provides various libraries and classes for loading, manipulating, and
saving images. For example, the javax.imageio package allows developers to
read and write images in different formats, while java.awt.image package
offers classes for performing operations like scaling, cropping, and filtering on
images.
Audio Playback:
Java Sound API enables developers to play audio files of different
formats. It provides classes like Clip and AudioInputStream to load and
manipulate audio data. JavaFX also provides media classes for playing audio
files, along with advanced features such as playback controls and volume
management.
Video Playback:
JavaFX has built-in media capabilities, which allow developers to play
video files in different formats. The javafx.scene.media package provides
classes like MediaPlayer and MediaView for handling video playback. By using
these classes, you can control video playback, handle events, and even apply
visual effects to the video.
Animation:
Java provides several libraries and frameworks that support animation.
For example, JavaFX provides a powerful animation framework with classes
like Animation, Timeline, and KeyFrame. These classes allow you to create
smooth animations by specifying time-based actions and transitions.
3D Graphics:
Java 3D API provides support for creating and manipulating 3D graphics
in Java. It offers a comprehensive set of classes and utilities for constructing
and rendering 3D scenes. With Java 3D, you can create complex 3D objects,
apply textures and lighting effects, and even perform animations in three-
dimensional space.
These are just a few examples of media techniques that can be used in Java
programming. Java provides a rich ecosystem of libraries and frameworks,
making it a versatile language for handling various types of media.
Image Manipulation:
Java provides various libraries and classes for loading, manipulating, and
saving images. For example, the javax.imageio package allows developers to
read and write images in different formats, while java.awt.image package
offers classes for performing operations like scaling, cropping, and filtering on
images.
Audio Playback:
Java Sound API enables developers to play audio files of different
formats. It provides classes like Clip and AudioInputStream to load and
manipulate audio data. JavaFX also provides media classes for playing audio
files, along with advanced features such as playback controls and volume
management.
Video Playback:
JavaFX has built-in media capabilities, which allow developers to play
video files in different formats. The javafx.scene.media package provides
classes like MediaPlayer and MediaView for handling video playback. By using
these classes, you can control video playback, handle events, and even apply
visual effects to the video.
Animation:
Java provides several libraries and frameworks that support animation.
For example, JavaFX provides a powerful animation framework with classes
like Animation, Timeline, and KeyFrame. These classes allow you to create
smooth animations by specifying time-based actions and transitions.
3D Graphics:
Java 3D API provides support for creating and manipulating 3D graphics
in Java. It offers a comprehensive set of classes and utilities for constructing
and rendering 3D scenes. With Java 3D, you can create complex 3D objects,
apply textures and lighting effects, and even perform animations in three-
dimensional space.
These are just a few examples of media techniques that can be used in
Java programming. Java provides a rich ecosystem of libraries and frameworks,
making it a versatile language for handling various types of media.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. Let's
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:
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:
skeletons.
The RMI application have all these features, so it is called the distributed application.
Working of RMI
The communication between client and server is handled by using two
intermediate objects: Stub object (on client side) and Skeleton object (on
server-side) as also can be depicted from below media as follows:
The client application need 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.
For creating the remote interface, extend the Remote interface and declare the
Remote Exception 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 Remote Exception.
1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws Remote Exception;
4. }
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.
Now start the registry service by using the rmiregistry tool. If you don't
specify the port number, it uses a default port number. In this example, we are
using the port number 5000.
1. rmiregistry 5000
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 soon.
1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
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
1. import java.rmi.*;
2. public class MyClient{
3. public static void main(String args[]){
4. try{
5. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
6. System.out.println(stub.add(34,4));
7. }catch(Exception e){}
8. }
9. }
Middleware:
Middleware is a software layer that sits between the client and server
components, providing services such as message passing, data persistence,
and load balancing. It coordinates communication between different
components and facilitates interoperability.
Message-based communication:
In a distributed application, components typically communicate with
each other through messages. This can be achieved using messaging protocols
like AMQP or event- driven architectures, where components publish and
subscribe to events.
The following table lists the different forms of transparency in a distributed system −
Disadvantages
Client-Server Architecture
The client-server architecture is the most common distributed system architecture which
decomposes the system into two major subsystems or logical processes −
Client − this is the first process that issues a request to the second
process i.e. the server.
Server − this is the second process that receives the request, carries
it out, and sends a reply to the client.
Thin-client model
Thick/Fat-client model
In thick-client model, the server is only in charge for data management. The
software on the client implements the application logic and the interactions
with the system user.
Most appropriate for new C/S systems where the capabilities of the
client system are known in advance
More complex than a thin client model especially for management. New
versions of the application have to be installed on all clients.
Advantages
Presentation Tier
Presentation layer is the topmost level of the application by which users can
access directly such as webpage or Operating System GUI (Graphical User
interface). The primary function of this layer is to translate the tasks and results
to something that user can understand. It communicates with other tiers so
that it places the results to the browser/client tier and all other tiers in the
network.
Data Tier
In this layer, information is stored and retrieved from the database or file
system. The information is then passed back for processing and then back to
the user. It includes the data persistence mechanisms (database servers, file
shares, etc.) and provides API (Application Programming Interface) to the
application tier which provides methods of managing the stored data.
Advantages
Disadvantages
Client and the server do not interact with each other directly. Client
and server have a direct connection to its proxy which communicates
with the mediator- broker.
A server provides services by registering and publishing their interfaces
with the broker and clients can request the services from the broker
statically or dynamically by look-up.
CORBA (Common Object Request Broker Architecture) is a good
implementation example of the broker architecture.
The components of broker architectural style are discussed through following heads −
Broker
Stub
Stubs are generated at the static compilation time and then deployed to the
client side which is used as a proxy for the client. Client-side proxy acts as a
mediator between the client and the broker and provides additional
transparency between them and the client; a remote object appears like a
local one.
The proxy hides the IPC (inter-process communication) at protocol level and
performs marshaling of parameter values and un-marshaling of results from
the server.
Bridge
Bridges are optional component, which hides the implementation details when
two brokers interoperate and take requests and parameters in one format and
translate them to another format.
SOA Operation
Advantages
Stub/Skeleton Interfaces
This section contains the interfaces and classes used by the stubs and
skeletons generated by the rmic stub compiler.
package java.rmi.server;
Clients interact with stub (surrogate) objects that have exactly the same set of
remote interfaces defined by the remote object's class; the stub class does not
include the non- remote portions of the class hierarchy that constitutes the
object's type graph. This is because the stub class is generated from the most
refined implementation class that implements one or more remote interfaces.
For example, if C extends B and B extends A, but only B implements a remote
interface, then a stub is generated from B, not C.
The following methods are declared final in the java.lang.Object class and
therefore cannot be overridden by any implementation:
getClass
notify
notifyAll
wait
The default implementation for getClass is appropriate for all objects written
in the Java programming language, local or remote; so, the method needs no
special implementation for remote objects. When used on a remote stub, the
getClass method reports the exact type of the stub object, generated by rmic.
Note that stub type reflects only the remote interfaces implemented by the
remote object, not that object's local interfaces.
The wait and notify methods of java.lang.Object deal with waiting and
notification in the context of the Java programming language's threading
model. While use of these methods for remote stubs does not break the
threading model, these methods do not have the same semantics as they do
for local objects written in the Java programming language. Specifically, these
methods operate on the client's local reference to the remote object (the
stub), not the actual object at the remote site.
package
java.rmi.server;
import java.io.*;
The method getOutputStream returns the output stream into which either the
stub marshals arguments or the skeleton marshals results.
The method getInputStream returns the InputStream from which the stub
unmarshals results or the skeleton unmarshals parameters.
The method releaseInputStream releases the input stream. This will allow some
transports to release the input side of a connection early.
the call. The method done allows cleanup after the remote
The interface RemoteRef represents the handle for a remote object. Each stub
contains an instance of RemoteRef that contains the concrete representation of
a reference. This remote reference is used to carry out remote calls on the
remote object for which it is a reference.
package java.rmi.server;
This method either returns the result of the method invocation on the
remote object which resides on the remote host or throws a RemoteException
if the call failed or an application-level exception if the remote invocation
throws an exception. Note that the operation number, opnum, represents a
hash of the method signature and may be used to encode the method for
transmission.
The method hash to be used for the opnum parameter is a 64-bit (long)
integer computed from the first two 32-bit values of the message digest of a
particular byte stream using the National Institute of Standards and
Technology (NIST) Secure Hash Algorithm (SHA-1).
The interface ServerRef represents the server-side handle for a remote object
implementation.
package java.rmi.server;
The method exportObject finds or creates a client stub object for the supplied
Remote object implementation obj.The parameter data contains information
necessary to export the object (such as port number).
The method getClientHost returns the host name of the current client. When
called from a thread actively handling a remote method invocation, the host
name of the client invoking the call is returned. If a remote method call is not
currently being service, then ServerNotActiveException is called.
package java.rmi.server;
{
void dispatch(Remote obj, RemoteCall call, int opnum, long hash)
throws Exception;
Operation[]
getOperations();
}
The dispatch method unmarshals any arguments from the input stream
obtained from the call object, invokes the method (indicated by the operation
number opnum) on the actual remote object implementation obj, and
marshals the return value or throws an exception if one occurs during the
invocation. The get Operations method returns an array containing the
operation descriptors for the remote object's methods.
package
java.rmi.server;
public class
Operation {
public Operation(String op) {...}
public String getOperation()
{...} public String toString()
{...}
}
The method getOperation returns the contents of the operation descriptor (the
value with which it was initialized).
The method toString also returns the string representation of the operation
descriptor (typically the method signature).
Now that you have a basic idea of how Java RMI works, we can explore the
details of creating and using distributed objects with RMI. As I mentioned
earlier, defining a remote RMI object involves specifying a remote interface for
the object, then providing a class that implements this interface. The remote
interface and implementation class are then used by RMI to generate a client
stub and server skeleton for your remote object. The communication between
local objects and remote objects is handled using these client stubs and server
skeletons. The relationships among stubs, skeletons, and the objects that use
them are shown
Interface:
Remote objects define interfaces that specify the methods and
attributes that can be accessed remotely. The interface acts as a contract
between the client and the remote object, ensuring that both parties
understand how to interact with each other.
Marshaling:
Remote objects utilize marshaling or serialization techniques to convert
method calls, argument values, and return values into a format that can be
transmitted over the network. This ensures that the objects can be properly
transported across different machines and platforms.
Location transparency:
Remote objects enable transparent access to their methods and
properties, hiding the complexities of the underlying network and
communication protocols. This allows clients to invoke remote methods as if
they were invoking local methods, simplifying the development and
maintenance of distributed systems.
Remote Object
Remote Server
Activatable
You may notice that while the client code is included, it is not discussed in a
step-by-step manner, like the implementation and setup classes. The reason
for this omission, is that the client code for activatable objects is no different
than the RMI client code for accessing non-activatable remote objects.
Activation is strictly a server-side implementation decision.
Step 1:
Make the appropriate imports in the implementation class
import java.rmi.*;
import java.rmi.activation.*;
Step 4:
Implement the remote interface method(s)
The job of the "setup" class is to create all the information necessary for the
activatable class, without necessarily creating an instance of the remote
object. For this example the setup class will be examples.activation.Setup.
The setup class passes the information about the activatable class to rmid,
registers a remote reference (an instance of the activatable class's stub class)
and an identifier (name) with the rmiregistry, and then the setup class may
exit. There are seven steps to create a setup class:
import java.rmi.*;
import
java.rmi.activation.*
import
java.util.Properties;
Step 2:
Install a SecurityManager
System.setSecurityManager(new RMISecurityManager());
Step 3:
Create an ActivationGroup instance
Note: In this example, for simplicity, we will use a policy file that gives global
permission to anyone from anywhere. Do not use this policy file in a
production environment. For more information on how to properly open up
permissions using
a java.security.policy file, please refer to to the following
In the setup application, the job of the activation group descriptor is to provide
all the information that rmid will require to contact the appropriate existing JVM
or spawn a new JVM for the activatable object.
Note: ln order to run this code on your system, you'll need to change the policy
file location to be the absolute path to where you've installed the example
policy file that came with the source code.
Step 4:
Create an ActivationDesc instance
The job of the activation descriptor is to provide all the information that rmid
will require to create a new instance of the implementation class.
Note: ln order to run this code on your system, you'll need to change the file
URL location to be the location of the directory on your system, where you've
installed the example source code.
Step 5:
Declare an instance of your remote interface and register the
activation descriptor with rmid
Naming.rebind("ActivatableImplementation", mri);
System.out.println("Exported
ActivatableImplementation");
Step 7:
Quit the setup application
System.exit(0);
Step 1:
Compile the remote interface, implementation, client and setup classes
% javac -d . MyRemoteInterface.java
% javac -d . ActivatableImplementation.java
% javac -d . Client.java
% javac -d . Setup.java
Step 2:
% rmic -d . examples.activation.ActivatableImplementation
Step 3:
Start the rmiregistry
% rmiregistry &
lf you start the rmiregistry, and it can find your stub classes in its CLASSPATH, it
will ignore the server's java.rmi.server.codebase property, and as a result, your
client(s) will not be able to download the stub code for your remote object.
Note: By default, rmid now requires a security policy file, that is used to verify
whether or not the information in each ActivationGroupDescriptor is allowed to
be used to launch a JVM for an activation group. For complete details, please
refer to the rmid man page for the Solaris operating environment and the rmid
man page for the Microsoft Windows platform.
Step 5:
Run the setup program
Run the setup, setting the codebase property to be the location of the
implementation stubs. There are four things that need to go on the same
command line:
There should be one space just after the word "java", one between the two
properties, and a third one just before the word "examples" (which is very hard
to see when you view this as text, in a browser, or on paper).
% java -Djava.security.policy=/home/rmi_tutorial/activation/policy -
Djava.rmi.server.codebase=file:/home/rmi_tutorial/activation/
examples.activation.Setup
The codebase property will be resolved to a URL, so it must have the form of
"http://aHost/somesource/" or "file:/myDirectory/location/" or, due to the
requirements of some operating systems, "file:///myDirectory/location/" (three
slashes after the "file:").
While a file: URL is sometimes easier to use for running example code, using
the file: URL will mean that the only clients that will be able to access the
server are those that can access the same files system as the server (either by
virtue of running on the same machine as the server or by using a shared
filesystem, such as NFS)..
Step 6:
Run the client
% java -Djava.security.policy=/home/rmi_tutorial/activation/policy
examples.activation.Client vector
*As used on this web site, the terms "Java virtual machine" or "JVM"
mean a virtual machine for the Java platform.
We must have to implement the Serializable interface for serializing the object.
It is mainly used to travel object's state on the network (that is known as marshalling).
The String class and all the wrapper classes implement the java.io.Serializable
interface by default.
Student.java
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
The ObjectOutputStream class is used to write primitive data types, and Java
objects to an OutputStream. Only objects that support the java.io.Serializable
interface can be written to streams.
Constructor
Important Methods
Method Description
3) public void close() throws IOException {} It closes the current output stream.
ObjectInputStream class
Constructor
Important Methods
Method Description
In this example, we are going to serialize the object of Student class from
above code. The writeObject() method of ObjectOutputStream class provides
the functionality to serialize the object. We are saving the state of the object in
the file named f.txt.
Persist.java
1. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
Output:
success
Both the read() and take() methods have variants: readIfExists() and
takeIfExists(). If they are called with a zero timeout, then they are equivalent to
their counterpart. The timeout parameter comes into effect only when a
transaction is used.
Each operation has parameters that are entries. Some are templates,
which are a kind of entry. The write() operation is a store operation. The read()
and take() operations are a combination of search and fetch operations. The
notify method sets up repeated search operations as entries are written to the
space. If a take() or read() operation doesn't find an object, the process can
wait until an object arrives.
There are two look-up operations: read() and take(). The read() method returns
either an entry that matches the template or an indication that no match was
found.
The take() method operates like read(), but if a match is found, the entry
is removed from the space. Distributed events can be used by requesting a
Java Spaces service to notify you when an entry that matches the specified
template is written into the space.
Note that each entry in the space can be taken at most once, but two or
more entries may have the exact same values.
As you can see, a client can interact with as many JavaSpaces services as
needed. Clients perform operations that map entries to templates onto
JavaSpaces services. Such operations can be singleton or contained in a
transaction so that all or none of the operations take place. Notifications go to
event catches, which can be either clients or proxies for clients.
You can implement such a multiuser chat system in RMI by creating remote
interfaces for the interactions discussed. But by using JavaSpaces technology,
you need only one interface.
public MessageEntry() {
}
Entries written in a space are governed by a renewable lease. If you like, you
can change the lease (when the write() operation is invoked) to one hour as
space.write(msg, null, 60 * 60 *
Once the 1000);
entry write()Lease
exists in the space, any process with access to the space can
perform
a read() on it. To read an entry, a template is used, which is an entry that may
have one or more of its fields set to null. An entry matches a template if (a) the
entry has the same type as or is a subtype of the template and (b) if for every
specified non- null field in the template, their fields match exactly. The null
fields act as wildcards and match any value. The following code segment
shows how to create a template and perform a read() on the space:
MessageEntry template = new MessageEntry();
MessageEntry output = (MessageEntry) space.read(template,
null, Long.MAX_VALUE);
null MessageEntry Long.MAX_VALUE read() take() readIfExists()
DATABASE
JAVA IN DATABASES:
Hibernate:
It is an object-relational mapping (ORM) framework for Java. Hibernate
simplifies the process of mapping Java objects to relational database tables
and provides an abstraction layer for database operations.
Apache Cassandra:
It is a highly scalable NoSQL database. Java drivers are available to
interact with Cassandra and perform operations like inserting, updating, and
querying data.
MongoDB:
MongoDB is a popular document-based NoSQL database. MongoDB
provides a Java driver that allows Java applications to interact with MongoDB
and perform CRUD operations.
These are just a few examples, and there are many more databases and
corresponding Java libraries available. The choice of library or framework
depends on the specific database and requirements of the application.
JDBC (Java Database Connectivity): Java provides a robust API called JDBC,
which allows developers to connect to various databases, execute SQL
queries, and retrieve or update data. JDBC offers a standardized way to
interact with databases using Java.
Stored procedures: Java can be used to write and execute stored procedures
in databases. Stored procedures are pre-compiled database queries that are
stored on the database server. They improve performance and security by
reducing network traffic and allowing developers to encapsulate business logic
within the database.
Data access layer: Java can be used to create a data access layer, which serves
as an abstraction between the application and the database. This layer handles
all the interactions with the database, allowing developers to focus on business
logic without worrying about low-level database operations.
Overall, Java's strength lies in its versatility and ability to integrate with various
databases and database technologies, making it a popular choice for
developing database-driven applications.
JDBC (Java Database Connectivity) is a Java API that allows Java applications
to interact with databases. It follows certain principles:
Driver Manager: The JDBC Driver Manager is responsible for managing the
drivers for the different databases. It loads and unloads drivers dynamically
at runtime.
Result Set: The Result Set interface represents the result of a database query.
It provides methods for accessing and manipulating the data retrieved from
the database.
Batch Processing: JDBC supports batch processing, which allows multiple SQL
statements to be submitted as a single unit. This improves performance by
reducing the number of round trips to the database.
There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1. Class.forName("oracle.jdbc.driver.OracleDriver");
step. 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.
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.
Pre-Requisite
Before moving further, you need to have a good understanding of the following two
subjects −
Database JDBC
Architecture
The JDBC API supports both two-tier and three-tier processing models for
database access but in general, JDBC Architecture consists of two layers −
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each
data source. The driver manager is capable of supporting multiple concurrent
drivers connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager
with respect to the JDBC drivers and the Java application −
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.
Result Set − 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.
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the
latest JDBC version at the time of writing this tutorial. It offers the main
classes for interacting with your data sources.
The new features in these packages include changes in the following areas −
Driver :
A driver is nothing but an engine, which especially drives for the data.
Type – 1 :
This driver is also called a JDBC –ODBC bridge driver .using this driver, we can
access the ODBC drivers installed on each machine. ODBC requires the
configuration of a system a Data Source name, that represents the target
database
The architecture of this driver is shown below
Type – 3 :
This type of driver is called JDBC-.Net pure Java. Here a three-tier
approach is used for accessing the databases. This JDBC uses the standard
client sockets for transferring the data into a middleware.
Then, this data will be accessed by the end user. The greatest
advantage of this type of driver, no code is required for accessing the data.
Moreover, a single driver can give access to multiple databases
My dear readers, I hope you got a clarity regarding the types of drivers sued in
JDBC connection. Moreover, I hope you got an idea regarding how do JAVA and
SQL interact with each other.
Recommended Audience:
Software developers
Project Managers
Team leaders
Pre requisites:
Procedure:
1. Import the database-syntax for importingthe sql
database in java is- import java.sql.* ;
2. Load and register drivers-syntax for registering drivers after the loading
of driver class is
forName(com.mysql.jdbc.xyz) ;
4. Create a connection: Open any IDE where the java executable file can be
generated following the standard methods. Creating a package further
creating the class. Inside the package, open a new java file and type the
below code for JDBC connectivity and save the filename with
connection.java.
4.3 : We check if rs.next() is not null, then we display the details of that particular
customer present in “cuslogin” table
4.4 : Open a new java file (here, its result.java) inside the same package
and type the full code (shown below) for searching the details of the customer
whose id is 1, from table “cuslogin”.
Note: both the file viz result.java and connection.java should be inside the same
package,
else the program won’t give desired output!!
Java
// Importing required
classes import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.SQLException;
= "jdbc:mysql://localhost:3306/testDB?useSSL=false";
// Database credentials
// 1. Root
// 2. Password to fetch
"Imei@123";
exceptions try {
Class.forName("com.mysql.cj.jdbc.Driver");
PASS);
occurs e.printStackTrace();
catch (ClassNotFoundException e) {
e.printStackTrace();
return con;
App/Main Class where the program is compiled and run calling the above
connection class object
Java
import java.sql.*;
// Main class
connectionDB();
PreparedStatement p = null;
con =
connection.connectDB();
exceptions try {
// Step 4: Write a
p=
con.prepareStatement(sql);
rs = p.executeQuery();
tpassword");
// in the
object if
(rs.next()) {
int id = rs.getInt("id");
String name =
rs.getString("name"); String
email = rs.getString("email");
name
+ password);
catch (SQLException e) {
System.out.println(e);
5. Queries and retrieval –For multimedia data like images, video, audio
accessing data through query opens up many issues like efficient query
formulation, query execution and optimization which need to be worked
upon.
Java Persistence API (JPA): JPA is a specification that defines a standard way
to map Java objects to relational databases. It is a part of the Java EE
(Enterprise Edition) platform and provides a set of interfaces and annotations
to simplify database operations. JPA implementations, such as Hibernate and
Eclipse Link, offer ORM capabilities along with JPA compliance.
Spring Data: Spring Data is a module within the Spring Framework that
provides easy database access and manipulation. It offers a set of high-level
abstractions for working with databases and offers consistent APIs across
different data storage technologies, such as relational databases, No SQL
databases, and more.
These are just a few examples of how Java web applications can be supported
by databases. The choice of database support depends on the specific
requirements and preferences of the project.
The aim of this article is to provide basic details of different components in Web
Application and how can we use Servlet and JSP to create our first java web
application.
Web Server is a software that can process the client request and send the
response back to the client. For example, Apache is one of the most widely
used web servers. Web Server runs on some physical machine and listens to
client request on a specific port.
When we request something from the server (through URL), the web
client takes care of creating a request and sending it to the server and then
parsing the server response and present it to the user.
Web Server and Web Client are two separate softwares, so there should be
some common language for communication. HTML is the common language
between server and client and stands for HyperText Markup Language. Web
server and client needs a common communication protocol, HTTP (HyperText
Transfer Protocol) is the communication protocol between server and client.
HTTP runs on top of TCP/IP communication protocol. Some of the important
parts of the HTTP Request are:
GET /FirstServletProject/jsps/hello.jsp
HTTP/1.1 Host: localhost:8080
Cache-Control: no-cache
Status Code - an integer to indicate whether the request was success or not.
Some of the well-known status codes are 200 for success, 404 for Not Found
and 403 for Access Forbidden.
Content Type - text, html, image, pdf etc. Also known as MIME type
Content - actual data that is rendered by client and shown
to user. Sample HTTP Response:
200 OK
Date: Wed, 07 Aug 2013 19:55:50 GMT
Server: Apache-
Coyote/1.1 Content-
Length: 309
Content-Type: text/html;charset=US-ASCII
Web servers are good for static contents HTML pages but they don’t know
how to generate dynamic content or how to save data into databases, so we
need another tool that we can use to generate dynamic content.
Provide the apache tomcat directory location and JRE information to add
the runtime environment. Now go to the Servers view and create a new server
like below image pointing to the above-added runtime environment.
Note: If Servers tab is not visible, then you can select Window > Show
View > Servers so that it will be visible in Eclipse window.
Try stopping and starting the server to make sure it’s working fine. If
you have already started the server from the terminal, then you will have to
stop it from the terminal and then start it from Eclipse else it won’t work
perfectly. Now we are ready with our setup to create the first servlet and run it
on tomcat server.
import
java.io.IOException;
import
java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import
javax.servlet.annotation.WebInitParam;
import
javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FirstServlet
*/
@WebServlet(description = "My First Servlet", urlPatterns = { "/FirstServlet" ,
"/FirstServlet.do"}, initParams =
{@WebInitParam(name="id",value="1"),@WebInitParam(name="name",value
="pankaj")}) public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String
HTML_START="<html><body>"; public static final
String HTML_END="</body></html>";
/**
* @see HttpServlet#HttpServlet()
*/
public FirstServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
Downloaded by 215 Logavani BK ([email protected])
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
page.
You can refresh it to check that Date is dynamic and keeps on changing, you can
open it outside of Eclipse also in any other browser. So servlet is used to
generate HTML and send it in response, if you will look into the doGet()
implementation, we are actually creating an HTML document as writing it in
response PrintWriter object and we are adding dynamic information where we
need it. It’s good for a start but if the response is huge with a lot of dynamic
data, it’s error-prone and hard to read and maintain. This is the primary reason
for the introduction of JSPs. JSP is also server-side technology and it’s like
HTML with additional features to add dynamic content where we need it. JSPs
are good for presentation because it’s easy to write because it’s like HTML.
Here is our first JSP program that does the same thing as the above servlet.
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html;
charset=US-ASCII" pageEncoding="US-ASCII"%>
< DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Hello</title>
</head>
<body>
<h2>Hi There </h2>
<br>
<h3>Date=<%= new Date() %>
</h3>
</body>
</html>
We will look into Servlets and JSPs in more detail in future posts but before
concluding this post, we should have a good understanding of some of the
aspects of Java web applications.
Web Container
Tomcat is a web container, when a request is made from Client to web server,
it passes the request to web container and it’s web container job to find the
correct resource to handle the request (servlet or JSP) and then use the
response from the resource to generate the response and provide it to web
server. Then the webserver sends the response back to the client. When web
container gets the request and if it’s for servlet then container creates two
Objects HTTPServletRequest and HTTPServletResponse. Then it finds the
correct servlet based on the URL and creates a thread for the request. Then it
invokes the servlet service () method and based on the HTTP method service ()
method invokes do Get () or do Post () methods. Servlet methods generate the
dynamic page and write it to the response. Once servlet thread is complete,
the container converts the response to HTTP response and send it back to the
client. Some of the important work done by web container are:
Deployment Descriptor
Web.xml file is the deployment descriptor of the web application and
contains a mapping for servlets (prior to 3.0), welcome pages, security
configurations, session timeout settings, etc.
SERVLETS
JAVA SERVLETS:
There are many interfaces and classes in the Servlet API such as Servlet,
Generic Servlet, Http Servlet, Servlet Request, Servlet Response, etc.
Servlet
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
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start
processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
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:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
4. Secure: because it uses java language.
CGI is created with the help of wireframe models. The features like reflection
and illumination can be assigned to the wireframes. These features can be
modified as per the requirement of the image and video in order to make them
look real. The quality of the visual effects produced by CGI is higher and
controllable as compared to physical ones, such as creating miniatures for
shots, hiring extras for crowd scenes, etc.
The CGI was used for the first in a movie in 1973; Michael Crichton's "West
world". After a few years, it was used in the movie "Star Wars." In 1993, it was
used in the movie "Jurassic Park". There are many other movies that make good
use of CGI, such as Avatar, Lord of the Rings, Inception, Finding Nemo, The
Matrix, and more.
History
Even though Alfred may have started things off early with some 2D trickery, it
was not until Edwin Cat mull and Fred Parke's 1972 computer-animated short
film A Computer Animated Hand that 3D computer graphics were officially
exposed to the world. To do this, Edwin drew 350 triangles and polygons in ink
on his hand, which were then transformed to digital form and laboriously
animated utilizing information in a 3D animation programme that Catmull
himself developed.
A few years later, with Hollywood's support, CGI made yet another
advancement. West world flexed its biceps in 1973 by releasing the first 2D CGI
scene showcasing "Gunslinger vision," a theory of how robots could see. A
sequel was produced since the first film was so popular.
CGI works
The browser sends a URL that causes the AOL server to use CGI to run a
program. The browser runs on a client machine and exchanges information with
a Web server using the Hyper Text Transfer Protocol or HTTP.
Depending on the type of request from the browser, the web server may
provide a document from its own document directory or executes a CGI
program which means it passes the input from the reader (browser) to the
program and output from the program back to the reader (browser). Thus, CGI
works as a gateway between the AOL server and the program you write.
Benefits of CGI:
o Currently, CGI is easier to use than Java for performing complex operations.
o Using pre-written code is usually simpler than writing your own.
o As long as they adhere to the definition, CGI allows programmes to be
created in any language and on any platform.
o There are many CGI-based counters and CGI programmes that can carry
out basic functions.
Disadvantages of CGI
o Because programmers must be loaded into memory for each page load in
Common Gateway Interface, overhead is incurred.
o In general, it is difficult to cache data in memory between page loads.
o A substantial amount of existing code is written in Perl.
o Processing time for CGI is high.
}
This class defines a new servlet called MyServlet.
Step 3 – Override the doGet() or doPost() method
The doGet() and doPost() methods are the two main methods used by
servlets to handle HTTP requests. To create a basic servlet program,
you’ll need to override one or both of these methods in your servlet
class.
Here’s an example of a basic doGet() method that sends a simple HTTP
response:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello, World ");
}
package javax.servlet;
public ServletConfig
getServletInfo();
throws ServletException;
ServletResponse response)
throws java.io.IOException
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(
"jdbc:odbc:usingjsp");
getServletContext().log(
Sometimes, the servlet engine decides that it doesn't need to keep your
servlet loaded anymore. This could happen automatically, or as the result of
you deactivating the servlet from an administration tool. Before the servlet
engine unloads your servlet, it calls
the destroy method to enable the servlet to perform any necessary cleanup.
The cleanup usually involves closing database connections, open files, and
network connections.
Listing 3.4 shows the destroy method that is a companion to the init method in
Listing 3.3.
Listing 3.4 destroy Method from JDBCServlet.java
try
API getServletContext().log(
The getServletConfig method returns the ServletConfig object that was passed
to the servlet in the init method. Unless you are keeping track of the config
object yourself, your best bet is to leave this method alone and let the
superclass handle it.
Example:
Here we are taking example of getParameter(). form.jsp is our jsp page in
which we are designing form having two fields name and location.
In servlet GetParameterExample.java we are getting name and
location by using getParameter() method.
form.jsp -
<html>
<body>
<form method="get" action="getParameterExample">
<table align="center">
<tr>
<td>Name : </td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Location : </td>
<td><input type="text" name="location"/></td>
</tr>
<tr>
GetParameterExample.java -
package net.roseindia;
import java.io.*;
import
javax.servlet.*;
import javax.servlet.http.*;
}
}
web.xml -
<welcome-file-list>
<welcome-file>form.jsp</welcome-file>
</welcome-file-list>
</web-app>
Output :
When you click on submit you will get following result page.
Rather than looking up one particular header, you can use the get Header
Names to get an Enumeration of all header names received on this particular
request.
Finally, in addition to looking up the request headers, you can get information
on the main request line itself. The get Method method returns the main
request method (normally GET or POST, but things like HEAD, PUT, and
DELETE are possible).
The get Request URI method returns the URI (the part of the URL that came
after the host and port, but before the form data). The get Request Protocol
returns the third part of the request line, which is generally "HTTP/1.0" or
"HTTP/1.1".
Here's a servlet that simply creates a table of all the headers it receives, along
with their associated values. It also prints out the three components of the
main request line (method, URI, and protocol).
package hall;
import
java.io.*;
import javax.servlet.*;
import
javax.servlet.http.*;
import java.util.*;
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.
1. Status Line
2. Response Header Fields or a series of HTTP headers
3. 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:
It is used to show the HTTP specification to which the server has tried to make
the message comply.
Example
1. 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
3xx: Redirection
c)Reason Phrase
1. HTTP/1.1 200 OK
Here,
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.
1. response-header = Accept-Ranges
2. I Age
3. I E Tag
4. I Location
5. I Proxy-Authenticate
6. I Retry-After
7. I Server
8. I Vary
9. I WWW-Authenticate
Message Body
The response's message body may be referred to for convenience as a response body.
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.
Cookies in Servlet
Cookie works
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session. It is not removed each time when user closes
the browser. It is removed only if user logout or sign out.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Cookie class
There are given some commonly used methods of the Cookie class.
Create a Cookie
Delete a Cookie
Let's see the simple code to delete cookie. It is mainly used to logout or signout the
use
r.
1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing
name and value of cookie
4. }
In this example, we are storing the name of the user in the cookie object and
accessing it in another servlet. As we know well that session corresponds to the
particular user. So if you access it from too many browsers with different
values, you will get the different value.
index.html
1. <form action="servlet1" method="post">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends
HttpServlet { 7.
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends
nse) HttpServlet { 6.
{
7. public void doPost(HttpServletRequest request, HttpServletResponse respo
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out =
response.getWriter(); 12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
Outp 21. </servlet-mapping>
ut 22.
23. </web-app>
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.
There are many advantages of JSP over the Servlet. They are as follows:
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, which makes JSP
development easy.
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.
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.
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.
To create the first JSP page, write some HTML code as given below, and save it
by .jsp extension. We have saved this file as index.jsp. Put it in a folder and
paste the folder in the web-apps directory in apache tomcat to run the JSP page.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put
Java code in the JSP page. We will learn scriptlet tag later.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
No, there is no need of directory structure if you don't have class files or TLD
files. For example, put JSP files in a folder directly and deploy that folder. It will
be running fine. However, if you are using Bean class, Servlet or TLD file, the
directory structure is required.
The directory structure of JSP page is same as Servlet. We contain the JSP page
outside the WEB-INF folder or in any directory.
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's
see what are the scripting elements first.
The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
In this example, we have created two files index.html and welcome.jsp. The
index.html file gets the username from the user and the welcome.jsp file prints
the username with the welcome message.
File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
Directives
Declarations
Script lets
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 %>
Scriptlets:
In this tag we can insert any amount of valid java code and these codes are
placed in _jsp Service method by the JSP engine. Scriptlets can be used
anywhere in the page. Scriptlets are defined by using <% and %> tags.
Syntax -
<% Scriptlets%>
The code placed within JSP expression tag is written to the output stream of
the response. So you need not write out.print() to write data. It is mainly used to
print the values of variable or method.
In this example of jsp expression tag, we are simply displaying a welcome message.
1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>
6.
Note: Do not end your statement with semicolon in case of expression tag.
To display the current time, we have used the getTime() method of Calendar
class. The getTime() is an instance method of Calendar class, so we have called
it after getting the instance of Calendar class by the getInstance() method.
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
In this example, we are printing the username using the expression tag. The
index.html file gets the username and sends the request to the welcome.jsp
file, which displays the username.
File: index.jsp
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's
see what are the scripting elements first.
The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
In this example, we have created two files index.html and welcome.jsp. The
index.html file gets the username from the user and the welcome.jsp file prints
the username with the welcome message.
File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
JSP DIRECTIVES
The jsp directives are messages that tells the web container how to translate
a JSP page into the corresponding servlet.
o page directive
o include directive
o tag lib directive
The page directive defines attributes that apply to an entire JSP page.
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.
2)Content Type
3)Extends
The extends attribute defines the parent class that will be inherited by the
generated servlet.It is rarely used.
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
The web container will create a method getServletInfo() in the resulting servlet.For
example:
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.
6)Language
The language attribute specifies the scripting language used in the JSP page.
The default value is "java".
8)IsThreadSafe
Servlet and JSP both are multi-threaded. If you want to control this behavior 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:
The web container in such a case, will generate the servlet as:
9)Error Page
The error Page attribute is used to define the error page, if exception occurs in
the current page, it will be redirected to the error page.
10) IsErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
The code written inside the jsp declaration tag is placed outside the service()
method of auto generated servlet.
The jsp scriptlet tag can only declare The jsp declaration tag can declare variables
variables not methods. as well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.
In this example of JSP declaration tag, we are declaring the field and printing
the value of the declared field using the jsp expression tag.
index.jsp
1. <html>
2. <body>
3. <% int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
In this example of JSP declaration tag, we are defining the method which
returns the cube of given number and calling this method from the jsp
expression tag. But we can also use jsp scriptlet tag to call the declared
method.
index.jsp
1. <html>
2. <body>
3. <%
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>
------------------------------------
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:
3. 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.
5. 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.
6.
For now, we skip the Next and click on the Finish button.
Before starting the internationalization, Let's first understand what are the
information’s
that differ from one region to another. There is the list of culturally dependent data:
o Messages
o Dates
o Times
o Numbers
o Currencies
o Measurements
o Phone Numbers
o Postal Addresses
o Labels on GUI components etc
1. Locale(String language)
2. Locale(String language, String country)
3. Locale(String language, String country, String variant)
Example of Local class that prints the information’s of the default locale
In this example, we are displaying the information’s of the default locale. If you
want to get the information’s about any specific locale, comment the first line
statement and uncomment the second line statement in the main method.
1. import java.util.*;
2. public class LocaleExample {
3. public static void main(String[] args) {
4. Locale locale=Locale.getDefault();
5. //Locale locale=new Locale("fr","fr");//for the
specific locale 6.
7. System.out.println(locale.getDisplayCountry());
8. System.out.println(locale.getDisplayLanguage());
9. System.out.println(locale.getDisplayName());
10. System.out.println(locale.getISO3Country());
11. System.out.println(locale.getISO3Language());
12. System.out.println(locale.getLanguage());
13. System.out.println(locale.getCountry());
14.
15. }
16. }
17.
Output:United States
English
English (United
States) USA
en
g
en
US
1. import java.util.*;
2. public class LocaleExample2 {
3. public static void main(String[] args) {
4. Locale enLocale = new Locale("en", "US");
5. Locale frLocale = new Locale("fr", "FR");
6. Locale esLocale = new Locale("es", "ES");
7. System.out.println("English language name (default): " +
8. enLocale.getDisplayLanguage());
9.
10. System.out.println("English language name in French: " +
11. enLocale.getDisplayLanguage(frLocale));
12. System.out.println("English language name in spanish: " +
13. enLocale.getDisplayLanguage(esLocale));
14. }
15.
16. }
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.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables,
lists, scroll panes, color chooser,
tabbed pane etc.
JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
The methods of Component class are widely used in java swing that are given below.
Method Description
We can write the code of swing inside the main (), constructor or any other method.
Let's see a simple swing example where we are creating one button and
adding it on the JFrame object inside the main () method.
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of
JFrame 5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis,
width, height 8.
9. f.add(b);//adding button in
JFrame 10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
We can also write all the codes of creating JFrame, JButton and method call
inside the java constructor.
File: Simple.java
1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of
JFrame 6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in
JFrame 11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above
example that sets the position of the button.
We can also inherit the JFrame class, so there is no need to create the instance
of JFrame class explicitly.
File: Simple2.java
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
Advance Java
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.
The four major benefits of advance Java that are, network centric, process
simplification, and futuristic imaging standard.
3.Servlets
4.Session Management
5.JSPs
6.JSP Elements
o Scriptlets
o Expressions
o Declarations
o Significance of above elements and fitment into the JSP Lifecycle
o Page Directive
o Include Directives
o Tag lib Directive
1.Basics of MVC
2.Struts 2 Architecture
4.Struts 2 Interceptors
o Responsibilities of an Interceptor
o Mechanism of Interceptor calling in Struts 2
o Defining Interceptors
o Defining Interceptor stacks
o Defining Custom Interceptors
o ORM implementations
2.Hibernate Architecture
o Introduction to Hibernate
o Hibernate Architecture
3.Hibernate CRUD
1.Introduction to spring
3.Setting up spring
4.Dependency Injection
1.Introduction
2.Creating Project
o Spring Initialize
o Download & Install STS IDE
o Spring Boot Example
o Spring Boot CLI
o Spring Boot Example-STS
3.Project Components
o Annotations
o Dependency Management
o Application Properties
o Starters
o Starter Parent
o Starter Web
o Starter Data JPA
o Starter Actuator
o Starter Test
o Devtools
o Multi Module Project
o Packaging
o Auto-Configuration
o JPA
o JDBC
o H2 Database
o Crud Operations
o Cache Provider
o EhCaching