0% found this document useful (0 votes)
3 views107 pages

Java

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

Java

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

Java OOPs Concepts

In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that
provides many concepts, such as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The programming paradigm
where everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for example, object,
classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It simplifies
software development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Apart from these concepts, there are some other terms which are used in Object-Oriented design:

o Coupling
o Cohesion
o Association
o Aggregation
o Composition
Object

Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard,
bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type of response returned by the
objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like
wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince the
customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't
know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example,
a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.

Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when classes
are aware of each other. If a class has the details information of another class, there is strong coupling. In
Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and
field. You can use interfaces for the weaker coupling because there is no concrete implementation.

Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A single well-
defined task is done by a highly cohesive method. The weakly cohesive method will split the task into
separate parts. The [Link] package is a highly cohesive package because it has I/O related classes and
interface. However, the [Link] package is a weakly cohesive package because it has unrelated classes
and interfaces.

Association
Association represents the relationship between the objects. Here, one object can be associated with one
object or many objects. There can be four types of association between the objects:

o One to One
o One to Many
o Many to One, and
o Many to Many

Let's understand the relationship with real-time examples. For example, One country can have one prime
minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can
have one prime minister (many to one), and many ministers can have many departments (many to many).

Association can be undirectional or bidirectional.

Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one object
contains other objects as a part of its state. It represents the weak relationship between objects. It is also
termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way
to reuse objects.

Composition
The composition is also a way to achieve Association. The composition represents the relationship where
one object contains other objects as a part of its state. There is a strong relationship between the
containing object and the dependent object. It is the state where containing objects do not have an
independent existence. If you delete the parent object, all the child objects will be deleted automatically.
Advantage of OOPs over Procedure-oriented programming
language
1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented programming
language, it is not easy to manage if code grows as project size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global data can
be accessed from anywhere.

Figure: Data Representation in Procedure-Oriented Programming

Figure: Data Representation in Object-Oriented Programming

3) OOPs provides the ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.

CHARACTERSTICKS Of Java
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important
role in the popularity of this language. The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun
Microsystem, Java language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means
we organize our software as a combination of different types of objects that incorporate both data and
behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development and


maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language. A platform
is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based
platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform that
runs on top of other hardware-based platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc.
Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-
independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere
(WORA).

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to
load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to
objects.
o Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.
Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography, etc.

Robust
The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points make Java
robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the
size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require
any implementation.

High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close"
to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi-
media, Web applications, etc.

Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

Explain the basic structure of a program in Java?

A typical structure of a Java program contains the following elements

 Package declaration
 Import statements
 Comments
 Class definition
 Class variables, Local variables
 Methods/Behaviors

Package declaration
A class in Java can be placed in different directories/packages based on the module they are used. For
all the classes that belong to a single parent source directory, a path from source directory is
considered as package declaration.

Import statements
There can be classes written in other folders/packages of our working java project and also there are
many classes written by individuals, companies, etc which can be useful in our program. To use them in
a class, we need to import the class that we intend to use. Many classes can be imported in a single
program and hence multiple import statements can be written.
Comments
The comments in Java can be used to provide information about the variable, method, class or any
other statement. It can also be used to hide the program code for a specific time.

Class Definition
A name should be given to a class in a java file. This name is used while creating an object of a class, in
other classes/programs.

Variables
The Variables are storing the values of parameters that are required during the execution of the
program. Variables declared with modifiers have different scopes, which define the life of a variable.

Main Method
Execution of a Java application starts from the main method. In other words, its an entry point for the
class or program that starts in Java Run-time.

Methods/Behaviors
A set of instructions which form a purposeful functionality that can be required to run multiple times
during the execution of a program. To not repeat the same set of instructions when the same
functionality is required, the instructions are enclosed in a method. A method’s behavior can be exploited
by passing variable values to a method.

Example
package abc; // A package declaration
import [Link].*; // declaration of an import statement
// This is a sample program to understnd basic structure of Java (Comment Section)
public class JavaProgramStructureTest { // class name
int repeat = 4; // global variable
public static void main(String args[]) { // main method
JavaProgramStructureTest test = new JavaProgramStructureTest();
[Link]("Welcome to Tutorials Point");
}
public void printMessage(String msg) { // method
Date date = new Date(); // variable local to method
for(int index = 0; index < repeat; index++) { // Here index - variable local to for loop
[Link](msg + "From" + [Link]());
}
}
}

Output
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT

Java - Abstraction
As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when
you consider the case of e-mail, complex details such as what happens as soon as you send an e-mail,
the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-mail you just need
to type the content, mention the address of the receiver, and click send.
Likewise in Object-oriented programming, abstraction is a process of hiding the implementation details
from the user, only the functionality will be provided to the user. In other words, the user will have the
information on what the object does instead of how it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.

Abstract Class
A class which contains the abstract keyword in its declaration is known as abstract class.
 Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void
get(); )
 But, if a class has at least one abstract method, then the class must be declared abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class, provide implementations to the
abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all the abstract methods in
it.
Example
This section provides you an example of the abstract class. To create an abstract class, just use
the abstract keyword before the class keyword, in the class declaration.

/* File name : [Link] */


public abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
[Link]("Constructing an Employee");
[Link] = name;
[Link] = address;
[Link] = number;
}

public double computePay() {


[Link]("Inside Employee computePay");
return 0.0;
}

public void mailCheck() {


[Link]("Mailing a check to " + [Link] + " " + [Link]);
}

public String toString() {


return name + " " + address + " " + number;
}

public String getName() {


return name;
}

public String getAddress() {


return address;
}

public void setAddress(String newAddress) {


address = newAddress;
}

public int getNumber() {


return number;
}
}

You can observe that except abstract methods the Employee class is same as normal class in Java. The
class is now abstract, but it still has three fields, seven methods, and one constructor.
Now you can try to instantiate the Employee class in the following way −

/* File name : [Link] */


public class AbstractDemo {

public static void main(String [] args) {


/* Following is not allowed and would raise error */
Employee e = new Employee("George W.", "Houston, TX", 43);
[Link]("\n Call mailCheck using Employee reference--");
[Link]();
}
}

When you compile the above class, it gives you the following error −
[Link]: Employee is abstract; cannot be instantiated
Employee e = new Employee("George W.", "Houston, TX", 43);
^

Inheriting the Abstract Class


We can inherit the properties of Employee class just like concrete class in the following way −

Example
/* File name : [Link] */
public class Salary extends Employee {
private double salary; // Annual salary

public Salary(String name, String address, int number, double salary) {


super(name, address, number);
setSalary(salary);
}

public void mailCheck() {


[Link]("Within mailCheck of Salary class ");
[Link]("Mailing check to " + getName() + " with salary " + salary);
}

public double getSalary() {


return salary;
}

public void setSalary(double newSalary) {


if(newSalary >= 0.0) {
salary = newSalary;
}
}

public double computePay() {


[Link]("Computing salary pay for " + getName());
return salary/52;
}
}

Here, you cannot instantiate the Employee class, but you can instantiate the Salary Class, and using this
instance you can access all the three fields and seven methods of Employee class as shown below.

/* File name : [Link] */


public class AbstractDemo {

public static void main(String [] args) {


Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
[Link]("Call mailCheck using Salary reference --");
[Link]();
[Link]("\n Call mailCheck using Employee reference--");
[Link]();
}
}

This produces the following result −

Output
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Abstract Methods
If you want a class to contain a particular method but you want the actual implementation of that method
to be determined by child classes, you can declare the method in the parent class as an abstract.
 abstract keyword is used to declare the method as abstract.
 You have to place the abstract keyword before the method name in the method declaration.
 An abstract method contains a method signature, but no method body.
 Instead of curly braces, an abstract method will have a semoi colon (;) at the end.
Following is an example of the abstract method.

Example
public abstract class Employee {
private String name;
private String address;
private int number;

public abstract double computePay();


// Remainder of class definition
}

Declaring a method as abstract has two consequences −


 The class containing it must be declared as abstract.
 Any class inheriting the current class must either override the abstract method or declare itself as
abstract.
Note − Eventually, a descendant class has to implement the abstract method; otherwise, you would have
a hierarchy of abstract classes that cannot be instantiated.
Suppose Salary class inherits the Employee class, then it should implement the computePay() method
as shown below −

/* File name : [Link] */


public class Salary extends Employee {
private double salary; // Annual salary

public double computePay() {


[Link]("Computing salary pay for " + getName());
return salary/52;
}
// Remainder of class definition
}

Java - Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class
implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods, an interface may also contain constants, default methods, static methods,
and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an
object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be
defined in the class.
An interface is similar to a class in the following ways −
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface matching the
name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
However, an interface is different from a class in several ways, including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface must be
declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare an interface −

Example
Following is an example of an interface −

/* File name : [Link] */


import [Link].*;
// Any number of import statements
public interface NameOfInterface {
// Any number of final, static fields
// Any number of abstract method declarations\
}

Interfaces have the following properties −


 An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an
interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
 Methods in an interface are implicitly public.
Example
/* File name : [Link] */
interface Animal {
public void eat();
public void travel();
}

Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform
the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the
class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword appears in
the class declaration following the extends portion of the declaration.

Example
/* File name : [Link] */
public class MammalInt implements Animal {

public void eat() {


[Link]("Mammal eats");
}

public void travel() {


[Link]("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
[Link]();
[Link]();
}
}
This will produce the following result −

Output
Mammal eats
Mammal travels
When overriding methods defined in interfaces, there are several rules to be followed −
 Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.
 The signature of the interface method and the same return type or subtype should be maintained
when overriding the methods.
 An implementation class itself can be abstract and if so, interface methods need not be
implemented.
When implementation interfaces, there are several rules −
 A class can implement more than one interface at a time.
 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend another class.

Extending Interfaces
An interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods of the
parent interface.
The following Sports interface is extended by Hockey and Football interfaces.

Example
// Filename: [Link]
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

// Filename: [Link]
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

// Filename: [Link]
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define
the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not
classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as −

Example
public interface Hockey extends Sports, Event

Tagging Interfaces
The most common use of extending interfaces occurs when the parent interface does not contain any
methods. For example, the MouseListener interface in the [Link] package extended
[Link], which is defined as −

Example
package [Link];
public interface EventListener
{}

An interface with no methods in it is referred to as a tagging interface. There are two basic design
purposes of tagging interfaces −
Creates a common parent − As with the EventListener interface, which is extended by dozens of other
interfaces in the Java API, you can use a tagging interface to create a common parent among a group of
interfaces. For example, when an interface extends EventListener, the JVM knows that this particular
interface is going to be used in an event delegation scenario.
Adds a data type to a class − This situation is where the term, tagging comes from. A class that
implements a tagging interface does not need to define any methods (since the interface does not have
any), but the class becomes an interface type through polymorphism.

Java Methods
A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.

Create a Method
A method must be declared within a class. It is defined with the name of the method, followed
by parentheses (). Java provides some pre-defined methods, such as [Link](), but
you can also create your own methods to perform certain actions:

ExampleGet your own Java Server


Create a method inside Main:

public class Main {

static void myMethod() {

// code to be executed

Example Explained
 myMethod() is the name of the method
 static means that the method belongs to the Main class and not an object of the Main
class. You will learn more about objects and how to access methods through objects
later in this tutorial.
 void means that this method does not have a return value. You will learn more about
return values later in this chapter

Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;

In the following example, myMethod() is used to print a text (the action), when it is called:

Example
Inside main, call the myMethod() method:

public class Main {

static void myMethod() {

[Link]("I just got executed!");


}

public static void main(String[] args) {

myMethod();

// Outputs "I just got executed!"

Try it Yourself »

A method can also be called multiple times:

Example
public class Main {

static void myMethod() {

[Link]("I just got executed!");

public static void main(String[] args) {

myMethod();

myMethod();

myMethod();

// I just got executed!

// I just got executed!

// I just got executed!


Java Inheritance

Java Inheritance (Subclass and Superclass)


In Java, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:

 subclass (child) - the class that inherits from another class


 superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):

ExampleGet your own Java Server


class Vehicle {

protected String brand = "Ford"; // Vehicle attribute

public void honk() { // Vehicle method

[Link]("Tuut, tuut!");

class Car extends Vehicle {

private String modelName = "Mustang"; // Car attribute

public static void main(String[] args) {

// Create a myCar object

Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar object

[Link]();

// Display the value of the brand attribute (from the Vehicle class) and the value
of the modelName from the Car class
[Link]([Link] + " " + [Link]);

Did you notice the protected modifier in Vehicle?

We set the brand attribute in Vehicle to a protected access modifier. If it was set to private,
the Car class would not be able to access it.

Why And When To Use "Inheritance"?


- It is useful for code reusability: reuse attributes and methods of an existing class when you
create a new class.

Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods to
perform different tasks.

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

final class Vehicle {

...

class Car extends Vehicle {

...

The output will be something like this:

[Link]: error: cannot inherit from final Vehicle


class Main extends Vehicle {
^
1 error)

Difference between method overloading and method


overriding in java
There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:
No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide the specific
readability of the program. implementation of the method that is already
provided by its super class.

2) Method overloading is performed within class. Method overriding occurs in two classes that have
IS-A (inheritance) relationship.

3) In case of method overloading, parameter must be In case of method overriding, parameter must be
different. same.

4) Method overloading is the example of compile Method overriding is the example of run time
time polymorphism. polymorphism.

5) In java, method overloading can't be performed by Return type must be same or covariant in method
changing return type of the method only. Return overriding.
type can be same or different in method
overloading. But you must have to change the
parameter.

Java Method Overloading example


1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }

Java Method Overriding example


1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){[Link]("eating bread...");}
6. }

Java Packages

Java Packages & API


A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better maintainable code. Packages
are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.

The library contains components for managing input, database programming, and much much
more. The complete list can be found at Oracles
website: [Link]

The library is divided into packages and classes. Meaning you can either import a single
class (along with its methods and attributes), or a whole package that contain all the classes
that belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:

SyntaxGet your own Java Server


import [Link]; // Import a single class

import [Link].*; // Import the whole package

Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:

Example
import [Link];

In the example above, [Link] is a package, while Scanner is a class of the [Link] package.

To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read a complete line:

Example
Using the Scanner class to get user input:

import [Link];
class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]);

[Link]("Enter username");

String userName = [Link]();

[Link]("Username is: " + userName);

Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class
from the [Link] package. This package also contains date and time facilities, random-
number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (*). The following example
will import ALL the classes in the [Link] package:

Example
import [Link].*;

User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to
store them. Just like folders on your computer:

Example
└── root
└── mypack
└── [Link]

To create a package, use the package keyword:

[Link]
package mypack;

class MyPackageClass {

public static void main(String[] args) {


[Link]("This is my package!");

Save the file as [Link], and compile it:

C:\Users\Your Name>javac [Link]

Then compile the package:

C:\Users\Your Name>javac -d . [Link]

This forces the compiler to create the "mypack" package.

The -d keyword specifies the destination for where to save the class file. You can use any
directory name, like c:/user (windows), or, if you want to keep the package within the same
directory, you can use the dot sign ".", like in the example above.

Note: The package name should be written in lower case to avoid conflict with class names.

When we compiled the package in the example above, a new folder was created, called
"mypack".

To run the [Link] file, write the following:

C:\Users\Your Name>java [Link]

The output will be:

This is my package!

Java Exceptions - Try...Catch


Java Exceptions
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).

Java try and catch


The try statement allows you to define a block of code to be tested for errors while it is being
executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.
The try and catch keywords come in pairs:

SyntaxGet your own Java Server


try {

// Block of code to try

catch(Exception e) {

// Block of code to handle errors

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {

public static void main(String[ ] args) {

int[] myNumbers = {1, 2, 3};

[Link](myNumbers[10]); // error!

The output will be something like this:

Exception in thread "main" [Link]: 10


at [Link]([Link])

If an error occurs, we can use try...catch to catch the error and execute some code to
handle it:

Example
public class Main {

public static void main(String[ ] args) {

try {

int[] myNumbers = {1, 2, 3};

[Link](myNumbers[10]);

} catch (Exception e) {

[Link]("Something went wrong.");

}
}

The output will be:

Something went wrong.

Finally
The finally statement lets you execute code, after try...catch, regardless of the result:

Example
public class Main {

public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

[Link](myNumbers[10]);

} catch (Exception e) {

[Link]("Something went wrong.");

} finally {

[Link]("The 'try catch' is finished.");

The output will be:

Something went wrong.


The 'try catch' is finished.

The throw keyword


The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many exception
types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, Secu
rityException, etc:

Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":

public class Main {

static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Access denied - You must be at least 18 years


old.");

else {

[Link]("Access granted - You are old enough!");

public static void main(String[] args) {

checkAge(15); // Set age to 15 (which is below 18...)

The output will be:

Exception in thread "main" [Link]: Access denied - You


must be at least 18 years old.
at [Link]([Link])
at [Link]([Link])

If age was 20, you would not get an exception:

Example
checkAge(20);

The output will be:

Access granted - You are old enough!


Java Threads
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the same
time.

Threads can be used to perform complicated tasks in the background without interrupting the
main program.

Creating a Thread
There are two ways to create a thread.

It can be created by extending the Thread class and overriding its run() method:

Extend SyntaxGet your own Java Server


public class Main extends Thread {

public void run() {

[Link]("This code is running in a thread");

Another way to create a thread is to implement the Runnable interface:

Implement Syntax
public class Main implements Runnable {

public void run() {

[Link]("This code is running in a thread");

Running Threads
If the class extends the Thread class, the thread can be run by creating an instance of the
class and call its start() method:
Extend Example
public class Main extends Thread {

public static void main(String[] args) {

Main thread = new Main();

[Link]();

[Link]("This code is outside of the thread");

public void run() {

[Link]("This code is running in a thread");

If the class implements the Runnable interface, the thread can be run by passing an instance
of the class to a Thread object's constructor and then calling the thread's start() method:

Implement Example
public class Main implements Runnable {

public static void main(String[] args) {

Main obj = new Main();

Thread thread = new Thread(obj);

[Link]();

[Link]("This code is outside of the thread");

public void run() {

[Link]("This code is running in a thread");

Differences between "extending" and "implementing" Threads

The major difference is that when a class extends the Thread class, you cannot extend any
other class, but by implementing the Runnable interface, it is possible to extend from another
class as well, like: class MyClass extends OtherClass implements Runnable.
Concurrency Problems
Because threads run at the same time as other parts of the program, there is no way to know
in which order the code will run. When the threads and main program are reading and writing
the same variables, the values are unpredictable. The problems that result from this are called
concurrency problems.

Example
A code example where the value of the variable amount is unpredictable:

public class Main extends Thread {

public static int amount = 0;

public static void main(String[] args) {

Main thread = new Main();

[Link]();

[Link](amount);

amount++;

[Link](amount);

public void run() {

amount++;

To avoid concurrency problems, it is best to share as few attributes between threads as


possible. If attributes need to be shared, one possible solution is to use the isAlive() method
of the thread to check whether the thread has finished running before using any attributes
that the thread can change.

Example
Use isAlive() to prevent concurrency problems:

public class Main extends Thread {

public static int amount = 0;

public static void main(String[] args) {


Main thread = new Main();

[Link]();

// Wait for the thread to finish

while([Link]()) {

[Link]("Waiting...");

// Update amount and print its value

[Link]("Main: " + amount);

amount++;

[Link]("Main: " + amount);

public void run() {

amount++;

}
Java EE
The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is currently known
as Jakarta EE. It is a set of specifications wrapping around Java SE (Standard Edition). The Java EE provides
a platform for developers with enterprise features such as distributed computing and web services. Java
EE applications are usually run on reference run times such as microservers or application servers.
Examples of some contexts where Java EE is used are e-commerce, accounting, banking information
systems.

Specifications of Java EE
Java EE has several specifications which are useful in making web pages, reading and writing from
database in a transactional way, managing distributed queues. The Java EE contains several APIs which
have the functionalities of base Java SE APIs such as Enterprise JavaBeans, connectors, Servlets, Java
Server Pages and several web service technologies.

1. Web Specifications of Java EE

o Servlet- This specification defines how you can manage HTTP requests either in a synchronous or
asynchronous way. It is low level, and other specifications depend on it

o WebSocket- WebSocket is a computer communication protocol, and this API provides a set of APIs
to facilitate WebSocket connections.

o Java Server Faces- It is a service which helps in building GUI out of components.

o Unified Expression Language- It is a simple language which was designed to facilitate web
application developers.
2. Web Service Specifications of Java EE

o Java API for RESTful Web Services- It helps in providing services having Representational State
Transfer schema.
o Java API for JSON Processing- It is a set of specifications to manage the information provided in
JSON format. o Java API for JSON Binding- It is a set of specifications provide for binding or parsing
a JSON file into Java classes.

o Java Architecture for XML Binding- It allows binding of xml into Java objects.

o Java API for XML Web Services- SOAP is an xml based protocol to access web services over http.

This API allows you to create SOAP web services.

3. Enterprise Specifications of Java EE

o Contexts and Dependency Injection- It provides a container to inject dependencies as in Swing.

o Enterprise JavaBean- It is a set of lightweight APIs that an object container possesses in order to
provide transactions, remote procedure calls, and concurrency control.

o Java Persistence API- These are the specifications of object-relational mapping between relational
database tables and Java classes.

o Java Transaction API- It contains the interfaces and annotations to establish interaction between
transaction support offered by Java EE. The APIs in this abstract from low-level details and the
interfaces are also considered low-level. o Java Message Service- It provides a common way to Java
program to create, send and read enterprise messaging system's messages.

4. Other Specifications of Java EE

o Validation- This package contains various interfaces and annotations for declarative validation
support offered by Bean Validation API.

o Batch applications- It provides the means to run long running background tasks which involve a
large volume of data and which need to be periodically executed.

o Java EE Connector Architecture- This is a Java-based technological solution for connecting Java
servers to Enterprise Information System.
J2EE Architecture
Introduction to J2EE Architecture
J2EE can be expanded as Java 2 Enterprise Edition, which offers a development environment for

enterprise application creation and implementation. J2EE Architecture is made up of three tiers, such as

the client tier is used as an interactive medium for the end user or the client & consists of web clients

and application clients; the middle tier is used for defining logical functioning units & consists of web

components and EJB components, and the enterprise data tier that is used for storage purposes in the

form of relational database & consists of containers, components, and services.

J2EE Uses Three Tiers:

• Client Tier: The client tier consists of user programs that interact with the user for requests and

responses.

• Middle Tier: Middle tier usually contains enterprise beans and web services that distribute business logic

for the applications.

• Enterprise Data Tier: Enterprise data is stored in a relational database. This tier contains containers,

components, and services.

Graphical Representation of J2EE Architecture


Usually, J2EE architecture consists of four tiers Client Tier, Web Tier, Enterprise JavaBean Tier, and

Enterprise Information Tier. The middle tier consists of the Web Tier+EJB tier.

1. Client Tier
The client tier consists of programs or applications that interact with the user. Usually, they are located

on a different machine from the server. Client tier prompts the user inputs into user requests, then

forwarded to the J2EE server, then processed result returned to the client. A client can be a web

browser, standalone application, or server on a different machine.

Clients can be classified as Web Clients and Application Clients.

Web Clients:
Web client consists of dynamic web pages of various mark-up languages generated by web

components running in web tier or web browser, which renders pages received from the server. Web

clients are also called thin clients that usually do not perform things like query databases or execute

business rules. Thin clients offload heavy operations to enterprise beans that execute within the J2EE

server.

Applets: Web pages received from the web tier embedded in an Applet. These run on a web browser.

Web components are APIs for creating a web client program. Web components enable the user to
design cleaner and more modular applications. They provide a way to separate application

programming.

Application Clients:
The application client runs on the client machine and handles the tasks that give richer user interfaces.

Typically the GUI is created by Swings or AWT. Application clients can access EJBs running in the

business tier using an HTTP connection.

2. Middle Tier (Web tier & EJB Tier)


Below are the components of the Middle Tier:

Web Tier /Web Component:


Web components can be servlets or JSP pages. Servlets can dynamically process the request and

generate the responses. Compared to JSP and servlets – servlets are dynamic pages to some extent,

but JSP pages are static.

The Client’s Static HTML programs and applet codes are bundled in the web tier/ Web Component

during the application assembly process. These HTML and applets are not considered elements of web

components. Server-side utility classes are bundled with web components but are not considered web

components themselves.
The web tier might include EJB components for processing user inputs and sending the input to

Enterprise Bean running in the business tier.

EJB Tier /EJB Component:


Enterprise components usually handle business code that is logic to solve particular business domains

such as banking or finance handled by enterprise bean running in the business tier.

If necessary, Enterprise Container receives data from client processes and sends it to the enterprise

information system for storage. Enterprise Bean also retrieves data from storage, processes it, and

sends it back to the client.

Three kinds of beans:

• Session Bean: The client uses a Session Bean for a conversation. Once the client finishes the execution,

the session bean destroys.

• Entity Bean: Holds the particular data stored in a database. Once the server shuts down or the client

finishes its execution, the data of the entity bean is preserved.

• Message Driven Bean: Message Bean combines the properties of Session Bean and JMS. Which benefits

the business component to receive messages asynchronously.

3. Enterprise Information System


This tier comprises database servers, enterprise resource planning systems, and other data sources.

Resources are typically located on a separate machine from the J2EE Server and accessed by

components on the business tier.

Technologies used in EIS Tier:

• Java Database Connectivity API (JDBC).

• Java Persistence API.

• Java Connector Architecture.

• Java Transaction API.

Containers in J2EE Architecture


Given below are containers in J2EE Architecture:

1. Application Client Container


The container includes a set of classes, libraries, and other files required to execute client programs in

their own JVM. Manages the execution of client components. It also provides services that enable Java

client programs to execute. This container is specific to the EJB container. Compared to other containers

in J2EE, this container is lightweight.

Features:
• Security: Responsible for collecting authentication Data such as User Name and Password and sending data

over RMI/IIOP to the server. The server then processes the data using the JAAS module. Even though the

client container provides authentication techniques, these are not under the control of the application

client.

• Naming: Allows the application clients to use Java Naming and Directory Interface (JNDI).

2. Web Container
A web Container is a web server component that interacts with Java servlets. A web container is

responsible for managing the servlet lifecycle and mapping [Link] container handles a request from

Servlets, JSP files, and other files, including server-side code.

Web container implements a web component contract of the J2EE architecture. This provides a runtime

environment for additional web components’ security, transaction, deployment, etc.

3. EJB Container
Enterprise Java bean container consists of server components that contain business logic. Provides local and

remote access to enterprise [Link] container is responsible for creating enterprise bean and binding

enterprise bean to the naming services.

Installing more than one module within a single EJB container is possible. It performs transactional

actions like – Start Transaction, Commits or Rollback transactions, manages various connection pools
for database resources, and synchronizes bean instance variables with corresponding data items

stored in the database.

4. Applet Container
The container where the client’s Applet programs run may be in a web browser or other applications that

support applet programming. Applets are subject to more restrictions due to the sandbox security

model, which limits access to the client machine. Web servers download normal web pages and execute

them on the client browser.

J2EE APIs
Java EE, which was previously called J2EE, is no longer in active development as of 2018. The current standard for
enterprise Java development is Jakarta EE, which is the result of the transfer of the Java EE specification to the
Eclipse Foundation. Jakarta EE includes several APIs that provide different capabilities for building enterprise
applications. Some of the latest Jakarta EE APIs and their versions are:

• Jakarta Servlet API 5.0


• Jakarta Persistence API 3.1
• Jakarta Messaging API 3.0
• Jakarta Batch API 2.0
• Jakarta WebSocket API 2.0
• Jakarta Security API 2.1
• Jakarta Concurrency API 2.0

Introduction to J2EE web applications


You can review overview of the Java™ 2 Platform, Enterprise Edition (J2EE) and how it is used to deploy Web
applications.

Web applications
A J2EE Web application is built to conform to a J2EE specification. You add Web components to a J2EE servlet
container in a package called a Web application archive (WAR) file. A WAR file is a JAR (Java archive) file
compressed file.
A WAR file usually contains other resources besides Web components, including:

• Server-side utility classes


• Static web resources (configuration files, HTML pages, image and sound files, and so on) Client-side classes (applets
and utility classes)

The directory and file structure of a Web application deployed as a WAR file conforms to a precise structure. A
WAR file has a specific hierarchical directory structure. The top-level directory of a WAR file is the document root
of the application. The document root is the directory under which JSP pages, client-side classes and archives, and
static Web resources are stored. The document root contains a subdirectory called WEB-INF/, which contains the
following files and directories:

• [Link]: the Web application deployment descriptor. It describes the structure of the Web application.
• Tag library descriptor files.
• classes/: a directory that contains server-side classes: servlet, utility classes, and Java Beans components.
• lib/: a directory that contains JAR archives of libraries (tag libraries and any utility libraries called by server-side classes).

Web Application Three Tier Architecture Layers


Web application architectural patterns are separated into many different layers or tiers which is called
Multi- or Three-Tier Architecture. You can easily replace and upgrade each layer independently.
Presentation Layer: This layer is accessible to the client via a browser and it includes user interface
components and UI process components. As we have already discussed that these UI components
are built with HTML, CSS, and JavaScript (and its frameworks or library) where each of them plays a
different role in building the user interface.
Business Layer: It is also referred to as a Business Logic or Domain Logic or Application Layer. It
accepts the user’s request from the browser, processes it, and regulates the routes through which the
data will be accessed. The whole workflow is encoded in this layer. You can take the example of
booking a hotel on a website. A traveler will go through a sequence of events to book the hotel room
and the whole workflow will be taken care of by the business logic.
Persistence Layer: It is also referred to as a storage or data access layer. This layer collects all the
data calls and provides access to the persistent storage of an application. The business layer is closely
attached to the persistence layer, so the logic knows which database to talk to and the process of
retrieving data becomes more optimized. A server and a database management system software exist
in data storage infrastructure which is used to communicate with the database itself, applications, and
user interfaces to retrieve data and parse it. You can store the data in hardware servers or in the cloud.
Some other parts of the web application which is separated from the main layers that exist in the
architecture are…
 Cross-cutting code: This part handles communications, operational management, and security. It
affects all parts of the system but should never mix with them.
 Third-party integrations: Using third-party APIs we can integrate payment gateways, social logins,
GDSs in travel websites, etc.

Challenges In Web Application Development


We have been listening to our clients and have understood some of the problems being faced in developing
Web Applications-

1. User Interface and User Experience

Think a decade ago, the web was a completely different place. Smartphones don’t exist. Simpler and
customer oriented web application are highly expected now. Sometimes it’s the small UI elements that
make the biggest impact. In the era of Smartphones, websites should be responsive enough on the
smaller screens. If your web applications frustrate or confuse users, then it is difficult to maintain your
customer’s loyalty for your website. Website navigation is another part often neglected by developers.
Intuitive navigation creates a better user experience for the website visitor. Intuitive navigation is leading
your audience to the information they are looking without a learning curve. And when the navigation is
intuitive, visitors can find out information without any pain, creating a flawless experience preventing
them from visiting the competitors.

2. Scalability
Scalability is neither performance nor it’s about making good use of computing power and bandwidth.
It’s about load balancing between the servers, hence, when the load increases (i.e. more traffic on the
page) additional servers can be added to balance it. You should not just throw all the load on a single
server but you should design the software such that it can work on a cluster of servers. Serviceoriented
architecture (SOA) can help in improving scalability when more and more servers are added. SOA gives
you the flexibility to change easily. Service oriented architecture is a design where application
components provide services to other components through the communication protocol, basically over a
network.

3. Performance
Generally, it is accepted that website speed has the major importance for a successful website. When
your business is online every second counts. Slow web applications are a failure. As a result, customers
abscond your website thus, damaging your revenue as well as reputation. It is said that think about
performance first before developing the web application. Some of the performance issues are Poorly
written code, Un-Optimized Databases, Unmanaged Growth of data, Traffic spikes, Poor load
distribution, Default configuration, Troublesome third party services, etc. A content distribution network
(CDN) is globally distributed network of proxy servers deployed in multiple data centres. It means
instead of using a single web server for the website, use a network of servers. Some of the benefits of
CDN are that the requests on the server will be routed to different servers balancing the traffic, the files
are divided on different CDNs so there will be no queuing and wait for downloading different files like
images, videos, text, etc.

4. Knowledge of Framework and Platforms

Frameworks are the kick start for development languages: they boost performance, offer libraries of
coding and extend capabilities, so developers need not do hand-coding web applications from the
ground up. Frameworks offer features like models, APIs, snippets of code and other elements to
develop dynamic web applications. Some of the frameworks have a rigid approach to development and
some are flexible. Common examples of web frameworks are PHP, [Link], Ruby on Rails and J2EE.
Web platforms provide client libraries build on existing frameworks required to develop a web
application or website. A new functionality can be added via external API. Developers and small
business owners should have a clear understanding of their company needs related to website and
application development. Information delivery and online presence would require a simple web platform
such as WordPress or Squarespace but a selling product requires an e-commerce platform such as
Magento, Shopify. WooCommerce or BigCommerce). While choosing the perfect platform one should
also consider technical skills, learning curve, pricing, customization options and analytics.

5. Security

In the midst of design and user experience, web app security is often neglected. But security should be
considered throughout the software development life cycle, especially when the application is dealing
with the vital information such as payment details, contact information, and confidential data. There are
many things to consider when it comes to web application security such as denial of service attacks, the
safety of user data, database malfunctioning, unauthorized access to restricted parts of the website, etc.
Some of the security threats are Cross-Site Scripting, Phishing, Cross-Site Request Forgery, Shell
Injection, Session Hijacking, SQL Injection, Buffer Overflow, etc. The website should be carefully coded
to be safe against these security concerns.
Web development can be deliberately difficult as it involves achieving a final product which should be
pleasing, builds the brand and is technically up to date with sound visuals.

At Maruti Techlabs, our expert team provides top-notch web application development services tailored
to your business needs. As a leading web application development company, we specialize in creating
custom web apps that are scalable, secure, and intuitive. Let us help you elevate your online presence
with our cutting-edge technology and personalized approach to development.

Life Cycle of a Servlet (Servlet Life Cycle)


The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

1. Servlet class is loaded.

2. Servlet instance is created.

3. init method is invoked.

4. service method is invoked.

5. destroy method is invoked.


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 initiali
life cycle method of the [Link] interface. Syntax of the init method is given below:
1. public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If servlet is
not initialized, it follows the first three steps as described above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service
method of the Servlet interface is given below:

1. public void service(ServletRequest request, ServletResponse response)

2. throws ServletException, IOException

5) destroy method is invoked

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

1. public void destroy()

Developing Servlets Application Steps

to Create Servlets Application

A web server is required to develop a servlet application. We are using Apache Tomcat server to
develop servlet application.

Following are the steps to develop a servlet application:


1. Create directory structure
2. Create a servlet
3. Compile the servlet
4. Create a deployment descriptor
5. Start the server and deploy the application

1. Create directory structure

There is a unique directory structure that must be followed to create Servlet application. This
structure tells where to put the different types of files.

2. Create a Servlet

//[Link]

import [Link].*;
import [Link].*; import
[Link].*;

public class ServletDemo extends HttpServlet


{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<html><body>");
[Link]("First Program of Servlet");
[Link]("</body></html>"); [Link]();

}}

3. Compile the Servlet program

Assuming the classpath and environment is setup properly, run the above Java program.

C:\javac [Link]

After compiling the Java file, paste the class file of servlet in WEB-INF/classes directory.

4. Create a deployment descriptor

The deployment descriptor is an xml file. It is used to map URL to servlet class, defining error
page.

//[Link]

<web-app>
<servlet>
<servlet-name>World</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web-app>

Note:

• Copy the ServletDemoclass into <Tomcat-installationdirectory>/webapps/ROOT/WEB-


INF/classes.
• Save the [Link] file in <Tomcat-installation directoryt>/webapps/ROOT/WEB-INF/

5. Start the server and deploy the application

Now start the Tomcat server by using

<Tomcat installation-direcory>\bin\[Link]

Open browser and type

[Link]

ServletRequest Interface
1. ServletRequest Interface

2. Methods of ServletRequest interface

3. Example of ServletRequest interface

4. Displaying all the header information

An object of ServletRequest is used to provide the client request information to a servlet such as content type,
content length, parameter names and values, header informations, attributes etc.

Methods of ServletRequest interface

There are many methods defined in the ServletRequest interface. Some of them are as follows:

Method Description

public String getParameter(String name) is used to obtain the value of a parameter by name.
public String[] getParameterValues(String
returns an array of String containing all values of given
name)
parameter name. It is mainly used to obtain values of a Multi
select list box.

returns an enumeration of all of the request parameter names.


[Link]
getParameterNames()

public int getContentLength() Returns the size of the request entity data, or -1 if not known.

public String getCharacterEncoding() Returns the character set encoding for the input of this
request.

public String getContentType() Returns the Internet Media Type of the request entity data, or
null if not known.

public ServletInputStream Returns an input stream for reading binary data in the request
getInputStream() throws IOException body.

public abstract String getServerName() Returns the host name of the server that received the request.

public int getServerPort() Returns the port number on which this request was received.

What is Servlet Chaining?


All servlet programs that participate in a servlet chaining will use the same request and response objects
because they process the same request that is given by the client.
To perform servlet chaining we need the RequestDispatcher object. RequestDispatcher object means it is the
object of a container supplied java class implementing [Link] interface.

Servlet – Session Tracking


Servlets are the Java programs that run on the Java-enabled web server or application server. They
are used to handle the request obtained from the webserver, process the request, produce the
response, then send a response back to the webserver
HTTP is a “stateless” protocol, which means that each time a client requests a Web page, the client
establishes a new connection with the Web server, and the server does not retain track of prior
requests.

• The conversion of a user over a period of time is referred to as a session. In general, it refers to
a certain period of time.
• The recording of the object in session is known as tracking.
• Session tracking is the process of remembering and documenting customer conversions over
time. Session management is another name for it.
• The term “stateful web application” refers to a web application that is capable of
remembering and recording client conversions over time.
Why is Session Tracking Required?
• Because the HTTP protocol is stateless, we require Session Tracking to make the client-server
relationship stateful.
• Session tracking is important for tracking conversions in online shopping, mailing applications,
and E-Commerce applications.
• The HTTP protocol is stateless, which implies that each request is treated as a new one. As you
can see in the image below.
Deleting Session Data
We have numerous alternatives once you’ve finished processing a user’s session data.

1. Remove a specific attribute You can delete the value associated with a specific key by calling
the public void removeAttribute(String name) function.
2. Delete your whole session. To delete an entire session, use the public void invalidate() function.
3. Setting Session Timeout You may set the timeout for a session separately by calling the public
void setMaxInactiveInterval(int interval) function.
4. Log the user out On servers that support servlets 2.4, you may use the logout method to log
the client out of the Web server and invalidate all of the users’ sessions.
5. [Link] Configuration If you’re using Tomcat, you may set the session timeout in the [Link]
file, in addition to the ways listed above.
<session-config>
<session-timeout>20</session-timeout>
</session-config>
The timeout is specified in minutes and overrides Tomcat’s default timeout of 30 minutes.

In a servlet, the getMaxInactiveInterval() function delivers the session’s timeout period in seconds.
GetMaxInactiveInterval() returns 900 if your session is set to 20 minutes in [Link].
Session Tracking employs Four Different techniques
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
A. Cookies
Cookies are little pieces of data delivered by the web server in the response header and kept by the
browser. Each web client can be assigned a unique session ID by a web server. Cookies are used to
keep the session going. Cookies can be turned off by the client.

B. Hidden Form Field


The information is inserted into the web pages via the hidden form field, which is then transferred
to the server. These fields are hidden from the user’s view.

Illustration:
<input type = hidden' name = 'session' value = '12345' >

C. URL Rewriting
With each request and return, append some more data via URL as request parameters. URL
rewriting is a better technique to keep session management and browser operations in sync.

D. HttpSession
A user session is represented by the HttpSession object. A session is established between an HTTP
client and an HTTP server using the HttpSession interface. A user session is a collection of data
about a user that spans many HTTP requests.
Java JDBC Tutorial
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the
database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the
database. There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We have discussed the above four drivers in the next chapter.

We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API,
we can save, update, delete and fetch data from the database. It is like Open Database Connectivity
(ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the
X/Open SQL Call Level Interface. The [Link] package contains classes and interfaces for JDBC API. A list
of popular interfaces of JDBC API are given below:

o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

A list of popular classes of JDBC API are given below:

o DriverManager class
o Blob class
o Clob class
o Types class

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and execute the query with the database. But,
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That
is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of J
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JD
the ODBC function calls. This is now discouraged because of thin driver.

In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC
drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:

o easy to use.
o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native
API. It is not written entirely in java.

Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:

o No client side library is required because of application server that can perform many tasks like auditing,
load balancing, logging etc.

Disadvantages:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be
done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin d
in Java language.
Advantage:

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage:

o Drivers depend on the Database.

Java Database Connectivity with 5 Steps


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) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to dynamically load the d

Syntax of forName() method


1. public static void forName(String className)throws ClassNotFoundException

2) Create the connection object


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

Syntax of getConnection() method

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


2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object of statement is responsi
with the database.

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. This method returns th
that can be used to get all the records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close() method of Connectio
close the connection.

Syntax of close() method

1. public void close()throws SQLException

It avoids explicit connection closing step.

SQL statements with JDBC


Establishing a Connection

To process SQL statements first of all you need to establish connection with the desired DBMS or, file
System or, other data sources.
 To do so, Register the JDBC driver class, corresponding to the DataSource you need to the
DriverManager using the registerDriver() method.
Driver myDriver = new [Link]();
[Link](myDriver);
This method accepts an object of the Driver class; it registers the specified Driver with the DriverManager.
You can also register the driver using the forName() method. This method loads the specified class in
to the memory and it automatically gets registered.

[Link]("[Link]");

 After registering the Driver class, get the Connection object using the getConnection() method.
This method accepts a database URL (an address that points to your database), Username and,
password and, returns a connection object.
String url = "jdbc:mysql://localhost/";
String user = "user_name";
String passwd = "password";
Connection conn = [Link](url, user_name, password);

Creating a Statement

The Statement interface represents an SQL statement and JDBC provides 3 kinds of Statements
 Statement: A general purpose statement which does not accept any parameters.
 PreparedStatement: A precompiled SQL statement which accepts input parameters.
 Callable Statement: This is used to call the stored procedures.
The Connection interface provides methods named createStatement(), prepareStatement() and,
prepareCall() to create Statement, prepared statement and, CallableStatement respectively. You need to
create any of these statements using the respective method.

[Link]();
[Link](query);
[Link](query);

Executing the Statements

After creating the statement objects, you need to execute them. To execute the statements, the
Statement interface provides three methods namely, execute(), executeUpdate() and, executeQuery().
 execute(): Used to execute SQL DDL statements, it returns a boolean value specifying whether the
ResultSet object can be retrieved.
 executeUpdate(): Used to execute statements such as insert, update, delete. It returns an integer
value representing the number of rows affected.
 executeQuery(): Used to execute statements that returns tabular data (example select). It returns
an object of the class ResultSet.
Execute the created statement using one of these methods.

[Link](query);
[Link](query);
[Link](query);

ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before
the first row.

By default, ResultSet object can be moved forward only and it is not updatable.

But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we
can make this object as updatable by:

1. Statement stmt = [Link](ResultSet.TYPE_SCROLL_INSENSITIVE,


2. ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface

1) public boolean next(): is used to move the cursor to the one row next from the current
position.

2) public boolean previous(): is used to move the cursor to the one row previous from the current
position.

3) public boolean first(): is used to move the cursor to the first row in result set object.

4) public boolean last(): is used to move the cursor to the last row in result set object.

5) public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet
object.

6) public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet
object, it may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of the current row
columnIndex): as int.

8) public int getInt(String is used to return the data of specified column name of the current row
columnName): as int.

9) public String getString(int is used to return the data of specified column index of the current row
columnIndex): as String.

10) public String getString(String is used to return the data of specified column name of the current row
columnName): as String.

Java ResultSetMetaData Interface


The metadata means data about data i.e. we can get further information from the data.

If you have to get metadata of a table like total number of column, column name, column type etc. ,
ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet
object.

Commonly used methods of ResultSetMetaData interface


Method Description

public int getColumnCount()throws SQLException it returns the total number of columns in the
ResultSet object.

public String getColumnName(int index)throws it returns the column name of the specified column
SQLException index.

public String getColumnTypeName(int index)throws it returns the column type name for the specified
SQLException index.

public String getTableName(int index)throws it returns the table name for the specified column
SQLException index.

Java DatabaseMetaData interface


DatabaseMetaData interface provides methods to get meta data of a database such as database product
name, database product version, driver name, name of total number of tables, name of total number of
views etc.
Commonly used methods of DatabaseMetaData interface
o public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
o public String getDriverVersion()throws SQLException: it returns the version number of the JDBC driver.
o public String getUserName()throws SQLException: it returns the username of the database.
o public String getDatabaseProductName()throws SQLException: it returns the product name of the
database.
o public String getDatabaseProductVersion()throws SQLException: it returns the product version of the
database.
o public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[]
types)throws SQLException: it returns the description of the tables of the specified catalog. The table type
can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
JSP Tutorial

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.

Advertisement

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.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code needs to
be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code. Moreover,
we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page


The JSP pages follow these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator. The
JSP translator is a part of the web server which is responsible for translating the JSP page into Servlet.
After that, Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all
the processes that happen in Servlet are performed on JSP later like initialization, committing response
to the browser and destroy.

JSP Scriptlet tag (Scripting elements)


In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the scripting
elements first.
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are three types of
scripting elements:

o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

1. <% java source code %>

Example of JSP scriptlet tag


In this example, we are displaying a welcome message.

1. <html>
2. <body>
3. <% [Link]("welcome to jsp"); %>
4. </body>
5. </html>

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files [Link] and [Link]. The [Link] file gets the
username from the user and the [Link] file prints the username with the welcome message.

File: [Link]

1. <html>
2. <body>
3. <form action="[Link]">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>

File: [Link]

1. <html>
2. <body>
3. <%
4. String name=[Link]("uname");
5. [Link]("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response. So you need
not write [Link]() to write data. It is mainly used to print the values of variable or method.

Syntax of JSP expression tag

1. <%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.

1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>

Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints current time


To display the current time, we have used the getTime() method of Calendar class. The getTime() is an
instance method of Calendar class, so we have called it after getting the instance of Calendar class by the
getInstance() method.

[Link]

1. <html>
2. <body>
3. Current Time: <%= [Link]().getTime() %>
4. </body>
5. </html>
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The [Link] file gets the
username and sends the request to the [Link] file, which displays the username.

File: [Link]

1. <html>
2. <body>
3. <form action="[Link]">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>

File: [Link]

1. <html>
2. <body>
3. <%= "Welcome "+[Link]("uname") %>
4. </body>
5. </html>

JSP Declaration Tag


The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.

So it doesn't get memory at each request.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

1. <%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as well
not methods. as methods.
The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed
the _jspService() method. outside the _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the declared
field using the jsp expression tag.

[Link]

1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of given
number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to call
the declared method.

[Link]

1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>

JSP Implicit Objects


There are 9 jsp implicit objects. These objects are created by the web container that are available to all
the jsp pages.

The available implicit objects are out, request, config, session, application etc.
A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

1. JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the object of JspWriter.
In case of servlet you need to write:

1. PrintWriter out=[Link]();

But in JSP, you don't need to write this code.

2. JSP request implicit object

The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request by the
web container. It can be used to get request information such as parameter, header information, remote
address, server name, server port, content type, character encoding etc.

It can also be used to set, get and remove attributes from the jsp request scope.

3. JSP response implicit object

In JSP, response is an implicit object of type HttpServletResponse. The instance of HttpServletResponse


is created by the web container for each jsp request.

It can be used to add or manipulate response such as redirect response to another resource, send error
etc.

4. JSP config implicit object

In JSP, config is an implicit object of type ServletConfig. This object can be used to get initialization
parameter for a particular JSP page. The config object is created by the web container for each jsp page.
Generally, it is used to get initialization parameter from the [Link] file.

5. JSP application implicit object

In JSP, application is an implicit object of type ServletContext.

The instance of ServletContext is created only once by the web container when application or project is
deployed on the server.

This object can be used to get initialization parameter from configuaration file ([Link]). It can also be
used to get, set or remove attribute from the application scope.

This initialization parameter can be used by all jsp pages.

6. session implicit object

In JSP, session is an implicit object of type [Link] Java developer can use this object to set,get or remove
attribute or to get session information.

7. pageContext implicit object

In JSP, pageContext is an implicit object of type PageContext [Link] pageContext object can be used
to set,get or remove attribute from one of the following scopes:
o page
o request
o session
o application

In JSP, page scope is the default scope.

8. page implicit object:

In JSP, page is an implicit object of type Object [Link] object is assigned to the reference of auto
generated servlet class. It is written as:
Object page=this;
For using this object it must be cast to Servlet [Link] example:
<% (HttpServlet)[Link]("message"); %>
Since, it is of type Object it is less used because you can use this object directly in [Link] example:
<% [Link]("message"); %>

9. exception implicit object

In JSP, exception is an implicit object of type [Link] class. This object can be used to print
the exception. But it can only be used in error [Link] is better to learn it after page directive.
JSP 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:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive

1. <%@ directive attribute="value" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

1. <%@ page attribute="value" %>

Attributes of JSP page directive

o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage

1)import
The import attribute is used to import class,interface or all the members of a [Link] is similar to import keyword in

2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP
[Link] default value is "text/html;charset=ISO-8859-1".

3)extends
The extends attribute defines the parent class that will be inherited by the generated [Link] is rarely
used.

4)info
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 [Link] example:

1. public String getServletInfo() {


2. return "composed by Sonoo Jaiswal";
3. }

5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP [Link]
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".

7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is false i.e. Expression
by default. We see Expression Language later.

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


8)isThreadSafe
Servlet and JSP both are [Link] you want to control this behaviour of JSP page, you can use isThreadS
[Link] value of isThreadSafe value is [Link] you make it false, the web container will serialize the multiple reques
the JSP finishes responding to a request before passing another request to [Link] you make the value of isThreadSafe att

<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

1. public class SimplePage_jsp extends HttpJspBase


2. implements SingleThreadModel{
3. .......
4. }

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.

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.

Jsp Include Directive


The include directive is used to include the contents of any resource it may be jsp file, html file or text
file. The include directive includes the original content of the included resource at page translation time
(the jsp page is translated only once so it will be better to include static resource).

Advantage of Include directive


Code Reusability

Syntax of include directive

1. <%@ include file="resourceName" %>

Example of include directive


In this example, we are including the content of the [Link] file. To run this example you must create
an [Link] file.

1. <html>
2. <body>
3.
4. <%@ include file="[Link]" %>
5.
6. Today is: <%= [Link]().getTime() %>
7.
8. </body>
9. </html>

Note: The include directive includes the original content, so the actual page size grows at runtime.

JSP Taglib directive


The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library
Descriptor) file to define the tags. In the custom tag section we will use this tag so it will be better to learn
it in custom tag.

Syntax JSP Taglib directive

1. <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive


In this example, we are using our tag named currentDate. To use this tag we must specify the taglib
directive so the container may get information about the tag.

1. <html>
2. <body>
3.
4. <%@ taglib uri="[Link] prefix="mytag" %>
5.
6. <mytag:currentDate/>
7.
8. </body>
9. </html>

JSP - Standard Tag Library (JSTL) Tutorial

In this chapter, we will understand the different tags in JSP. The JavaServer Pages Standard Tag Library
(JSTL) is a collection of useful JSP tags which encapsulates the core functionality common to many JSP
applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating
XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating the
existing custom tags with the JSTL tags.

Install JSTL Library


To begin working with JSP tages you need to first install the JSTL library. If you are using the Apache
Tomcat container, then follow these two steps −
Step 1 − Download the binary distribution from Apache Standard Taglib and unpack the compressed file.
Step 2 − To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR files in
the distribution's 'lib' directory to your application's webapps\ROOT\WEB-INF\lib directory.
To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses the
library.

Classification of The JSTL Tags


The JSTL tags can be classified, according to their functions, into the following JSTL tag library groups
that can be used when creating a JSP page −
 Core Tags
 Formatting tags
 SQL tags
 XML tags
 JSTL Functions

Core Tags
The core group of tags are the most commonly used JSTL tags. Following is the syntax to include the JSTL
Core library in your JSP −
<%@ taglib prefix = "c" uri = "[Link] %>
Following table lists out the core JSTL Tags −

[Link]. Tag & Description

<c:out>
1
Like <%= ... >, but for expressions.

<c:set >
2
Sets the result of an expression evaluation in a 'scope'

<c:remove >
3
Removes a scoped variable (from a particular scope, if specified).

<c:catch>
4
Catches any Throwable that occurs in its body and optionally exposes it.
<c:if>
5
Simple conditional tag which evalutes its body if the supplied condition is true.

<c:choose>
6 Simple conditional tag that establishes a context for mutually exclusive conditional operations,
marked by <when> and <otherwise>.

<c:when>
7
Subtag of <choose> that includes its body if its condition evalutes to 'true'.

<c:otherwise >
8 Subtag of <choose> that follows the <when> tags and runs only if all of the prior conditions
evaluated to 'false'.

<c:import>
9 Retrieves an absolute or relative URL and exposes its contents to either the page, a String
in 'var', or a Reader in 'varReader'.

<c:forEach >
10 The basic iteration tag, accepting many different collection types and supporting subsetting
and other functionality .

<c:forTokens>
11
Iterates over tokens, separated by the supplied delimeters.

<c:param>
12
Adds a parameter to a containing 'import' tag's URL.

<c:redirect >
13
Redirects to a new URL.

<c:url>
14
Creates a URL with optional query parameters

Formatting Tags
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Websites. Following is the syntax to include Formatting library in your JSP −
<%@ taglib prefix = "fmt" uri = "[Link] %>
Following table lists out the Formatting JSTL Tags −

[Link]. Tag & Description

<fmt:formatNumber>
1
To render numerical value with specific precision or format.

<fmt:parseNumber>
2
Parses the string representation of a number, currency, or percentage.

<fmt:formatDate>
3
Formats a date and/or time using the supplied styles and pattern.

<fmt:parseDate>
4
Parses the string representation of a date and/or time

<fmt:bundle>
5
Loads a resource bundle to be used by its tag body.

<fmt:setLocale>
6
Stores the given locale in the locale configuration variable.

<fmt:setBundle>
7 Loads a resource bundle and stores it in the named scoped variable or the bundle configuration
variable.

<fmt:timeZone>
8
Specifies the time zone for any time formatting or parsing actions nested in its body.

<fmt:setTimeZone>
9
Stores the given time zone in the time zone configuration variable

<fmt:message>
10
Displays an internationalized message.

<fmt:requestEncoding>
11
Sets the request character encoding
SQL Tags
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle,
mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP −
<%@ taglib prefix = "sql" uri = "[Link] %>
Following table lists out the SQL JSTL Tags −

[Link]. Tag & Description

<sql:setDataSource>
1
Creates a simple DataSource suitable only for prototyping

<sql:query>
2
Executes the SQL query defined in its body or through the sql attribute.

<sql:update>
3
Executes the SQL update defined in its body or through the sql attribute.

<sql:param>
4
Sets a parameter in an SQL statement to the specified value.

<sql:dateParam>
5
Sets a parameter in an SQL statement to the specified [Link] value.

<sql:transaction >
6 Provides nested database action elements with a shared Connection, set up to execute all
statements as one transaction.

XML tags
The JSTL XML tags provide a JSP-centric way of creating and manipulating the XML documents. Following
is the syntax to include the JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with the XML data. This includes parsing the
XML, transforming the XML data, and the flow control based on the XPath expressions.
<%@ taglib prefix = "x"
uri = "[Link] %>
Before you proceed with the examples, you will need to copy the following two XML and XPath related
libraries into your <Tomcat Installation Directory>\lib −
 [Link] − Download it from [Link]
 [Link] − Download it from [Link]
Following is the list of XML JSTL Tags −

[Link]. Tag & Description

<x:out>
1
Like <%= ... >, but for XPath expressions.

<x:parse>
2
Used to parse the XML data specified either via an attribute or in the tag body.

<x:set >
3
Sets a variable to the value of an XPath expression.

<x:if >
4 Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is
false, the body is ignored.

<x:forEach>
5
To loop over nodes in an XML document.

<x:choose>
6 Simple conditional tag that establishes a context for mutually exclusive conditional operations,
marked by <when> and <otherwise> tags.

<x:when >
7
Subtag of <choose> that includes its body if its expression evalutes to 'true'.

<x:otherwise >
8 Subtag of <choose> that follows the <when> tags and runs only if all of the prior conditions
evaluates to 'false'.

<x:transform >
9
Applies an XSL transformation on a XML document

<x:param >
10
Used along with the transform tag to set a parameter in the XSLT stylesheet
JSTL Functions
JSTL includes a number of standard functions, most of which are common string manipulation functions.
Following is the syntax to include JSTL Functions library in your JSP −
<%@ taglib prefix = "fn"
uri = "[Link] %>
Following table lists out the various JSTL Functions −

[Link]. Function & Description

fn:contains()
1
Tests if an input string contains the specified substring.

fn:containsIgnoreCase()
2
Tests if an input string contains the specified substring in a case insensitive way.

fn:endsWith()
3
Tests if an input string ends with the specified suffix.

fn:escapeXml()
4
Escapes characters that can be interpreted as XML markup.

fn:indexOf()
5
Returns the index withing a string of the first occurrence of a specified substring.

fn:join()
6
Joins all elements of an array into a string.

fn:length()
7
Returns the number of items in a collection, or the number of characters in a string.

fn:replace()
8
Returns a string resulting from replacing in an input string all occurrences with a given string.

fn:split()
9
Splits a string into an array of substrings.

fn:startsWith()
10
Tests if an input string starts with the specified prefix.
fn:substring()
11
Returns a subset of a string.

fn:substringAfter()
12
Returns a subset of a string following a specific substring.

fn:substringBefore()
13
Returns a subset of a string before a specific substring.

fn:toLowerCase()
14
Converts all of the characters of a string to lower case.

fn:toUpperCase()
15
Converts all of the characters of a string to upper case.

fn:trim()
16
Removes white spaces from both ends of a string.

JSP - Database Access

In this chapter, we will discuss how to access database with JSP. We assume you have good understanding
on how JDBC application works. Before starting with database access through a JSP, make sure you have
proper JDBC environment setup along with a database.
For more detail on how to access database using JDBC and its environment setup you can go through
our JDBC Tutorial.
To start with basic concept, let us create a table and create a few records in that table as follows −

Create Table
To create the Employees table in the EMP database, use the following steps −

Step 1
Open a Command Prompt and change to the installation directory as follows −

C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>
Step 3
Create the Employee table in the TEST database as follows − −

mysql> use TEST;


mysql> create table Employees
(
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>

Create Data Records


Let us now create a few records in the Employee table as follows − −
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');


Query OK, 1 row affected (0.00 sec)

mysql>

SELECT Operation
we can execute the SQL SELECT statement using JTSL in JSP programming
<sql:query dataSource = "${snapshot}" var = "result">
SELECT * from Employees;
</sql:query>

INSERT Operation
we can execute the SQL INSERT statement using JTSL in JSP programming
<sql:update dataSource = "${snapshot}" var = "result">
INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');
</sql:update>
DELETE Operation
we can execute the SQL DELETE statement using JTSL in JSP programming –
<sql:update dataSource = "${snapshot}" var = "count">
DELETE FROM Employees WHERE Id = ?
<sql:param value = "${empId}" />
</sql:update>

UPDATE Operation
we can execute the SQL UPDATE statement using JTSL in JSP programming –
<sql:update dataSource = "${snapshot}" var = "count">
UPDATE Employees SET WHERE last = 'Ali'
<sql:param value = "${empId}" />
</sql:update>

Uploading file to the server using JSP


There are many ways to upload the file to the server. One of the way is by the MultipartRequest class. For
using this class you need to have the [Link] file. In this example, we are providing the [Link] file alongwith
the code.

MultipartRequest class
It is a utility class to handle the multipart/form-data request. There are many constructors defined in the MultipartRequ

Commonly used Constructors of MultipartRequest class

o MultipartRequest(HttpServletRequest request, String saveDirectory) uploads the file upto 1MB.


o MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize) uploads the file
upto specified post size.
o MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, String
encoding) uploads the file upto specified post size with given encoding.

Example of File Upload in JSP


In this example, we are creating two files only, [Link] and [Link].

[Link]

To upload the file to the server, there are two requirements:

1. You must use the post request.


2. encodeType should be multipart/form-data that gives information to the server that you are going to
upload the file.

1. <form action="[Link]" method="post" enctype="multipart/form-data">


2. Select File:<input type="file" name="fname"/><br/>
3. <input type="image" src="[Link]"/>
4. </form>

[Link]

We are uploading the incoming file to the location d:/new, you can specify your location here.

1. <%@ page import="[Link]" %>


2. <%
3. MultipartRequest m = new MultipartRequest(request, "d:/new");
4. [Link]("successfully uploaded");
5.
6. %>

If size of the file is greater than 1MB, you should specify the post size.
Spring Framework - Overview
Spring is the most popular application development framework for enterprise Java. Millions of developers
around the world use Spring Framework to create high performing, easily testable, and reusable code.
Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first
released under the Apache 2.0 license in June 2003.
Spring is lightweight when it comes to size and transparency. The basic version of Spring framework is
around 2MB.
The core features of the Spring Framework can be used in developing any Java application, but there are
extensions for building web applications on top of the Java EE platform. Spring framework targets to
make J2EE development easier to use and promotes good programming practices by enabling a POJO-
based programming model.

Benefits of Using the Spring Framework


Following is the list of few of the great benefits of using Spring Framework −
 Spring enables developers to develop enterprise-class applications using POJOs. The benefit of
using only POJOs is that you do not need an EJB container product such as an application server
but you have the option of using only a robust servlet container such as Tomcat or some
commercial product.
 Spring is organized in a modular fashion. Even though the number of packages and classes are
substantial, you have to worry only about the ones you need and ignore the rest.
 Spring does not reinvent the wheel, instead it truly makes use of some of the existing technologies
like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and other view
technologies.
 Testing an application written with Spring is simple because environment-dependent code is
moved into this framework. Furthermore, by using JavaBeanstyle POJOs, it becomes easier to use
dependency injection for injecting test data.
 Spring's web framework is a well-designed web MVC framework, which provides a great alternative
to web frameworks such as Struts or other over-engineered or less popular web frameworks.
 Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC,
Hibernate, or JDO, for example) into consistent, unchecked exceptions.
 Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for
example. This is beneficial for developing and deploying applications on computers with limited
memory and CPU resources.
 Spring provides a consistent transaction management interface that can scale down to a local
transaction (using a single database, for example) and scale up to global transactions (using JTA,
for example).

Dependency Injection (DI)


The technology that Spring is most identified with is the Dependency Injection (DI) flavor of Inversion
of Control. The Inversion of Control (IoC) is a general concept, and it can be expressed in many different
ways. Dependency Injection is merely one concrete example of Inversion of Control.
When writing a complex Java application, application classes should be as independent as possible of
other Java classes to increase the possibility to reuse these classes and to test them independently of
other classes while unit testing. Dependency Injection helps in gluing these classes together and at the
same time keeping them independent.
What is dependency injection exactly? Let's look at these two words separately. Here the dependency
part translates into an association between two classes. For example, class A is dependent of class B. Now,
let's look at the second part, injection. All this means is, class B will get injected into class A by the IoC.
Dependency injection can happen in the way of passing parameters to the constructor or by post-
construction using setter methods. As Dependency Injection is the heart of Spring Framework, we will
explain this concept in a separate chapter with relevant example.

Aspect Oriented Programming (AOP)


One of the key components of Spring is the Aspect Oriented Programming (AOP) framework. The
functions that span multiple points of an application are called cross-cutting concerns and these cross-
cutting concerns are conceptually separate from the application's business logic. There are various
common good examples of aspects including logging, declarative transactions, security, caching, etc.
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. DI
helps you decouple your application objects from each other, while AOP helps you decouple cross-cutting
concerns from the objects that they affect.
The AOP module of Spring Framework provides an aspect-oriented programming implementation
allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements
functionality that should be separated. We will discuss more about Spring AOP concepts in a separate
chapter.

Spring MVC Architecture


The following diagram shows the spring MVC architecture starting from the point of user sending a
request to HTTP server till the response is returned back to user.
Spring MVC Architecture flow

Below steps explains the request and response flow:

1. DispatcherServlet receives the request.

2. DispatcherServlet dispatches the task of selecting an appropriate controller to

HandlerMapping. HandlerMapping selects the controller which is mapped to the incoming

request URL and returns the (selected Handler) Controller to DispatcherServlet.

3. DispatcherServlet dispatches the task of executing of business logic of Controller to

HandlerAdapter.

4. HandlerAdapter calls the business logic process of Controller.

5. Controller executes the business logic, sets the processing result in Model and returns the

logical name (or directly the name of the JSP) to HandlerAdapter.

6. DispatcherServlet dispatches the task of resolving the view (JSP/ Velocity/ FreeMarker etc.

or implementation of View interface) corresponding to the View name to ViewResolver which

returns the view (JSP/implementation of View interface) mapped to View name.

7. DispatcherServlet dispatches the rendering process to returned view (JSP/

implementation of View interface)

8. View (JSP/ implementation of View interface) renders Model data and returns the

response.

Spring BeanFactory Container


This is the simplest container providing the basic support for DI and defined by the
[Link] interface. The BeanFactory and related interfaces, such
as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of
backward compatibility with a large number of third-party frameworks that integrate with Spring.
There are a number of implementations of the BeanFactory interface that are come straight out-of-the-
box with Spring. The most commonly used BeanFactory implementation is the XmlBeanFactory class.
This container reads the configuration metadata from an XML file and uses it to create a fully configured
system or application.
The BeanFactory is usually preferred where the resources are limited like mobile devices or applet-based
applications. Thus, use an ApplicationContext unless you have a good reason for not doing so.

Example
Let us take a look at a working Eclipse IDE in place and take the following steps to create a Spring
application −
Steps Description

1 Create a project with a name SpringExample and create a [Link] under


the src folder in the created project.

2 Add the required Spring libraries using Add External JARs option as explained in the Spring Hello
World Example chapter.

3 Create Java classes HelloWorld and MainApp under the [Link].

4 Create Beans configuration file [Link] under the src folder.

5 The final step is to create the content of all the Java files and Bean Configuration file. Finally, run
the application as explained below.

Here is the content of [Link] file −

package [Link];

public class HelloWorld {


private String message;

public void setMessage(String message){


[Link] = message;
}
public void getMessage(){
[Link]("Your Message : " + message);
}
}

Following is the content of the second file [Link]

package [Link];

import [Link];
import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("[Link]"));
HelloWorld obj = (HelloWorld) [Link]("helloWorld");
[Link]();
}
}

Following two important points should be noted about the main program −
 The first step is to create a factory object where we used the framework APIXmlBeanFactory() to
create the factory bean andClassPathResource() API to load the bean configuration file available in
CLASSPATH. The XmlBeanFactory() API takes care of creating and initializing all the objects, i.e.
beans mentioned in the configuration file.
 The second step is used to get the required bean using getBean() method of the created bean
factory object. This method uses bean ID to return a generic object, which finally can be casted to
the actual object. Once you have the object, you can use this object to call any class method.
Following is the content of the bean configuration file [Link]

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "[Link]


xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<bean id = "helloWorld" class = "[Link]">


<property name = "message" value = "Hello World!"/>
</bean>

</beans>

Once you are done with creating the source and the bean configuration files, let us run the application. If
everything is fine with your application, it will print the following message −
Your Message : Hello World!

Spring ApplicationContext Container


The Application Context is Spring's advanced container. Similar to BeanFactory, it can load bean
definitions, wire beans together, and dispense beans upon request. Additionally, it adds more enterprise-
specific functionality such as the ability to resolve textual messages from a properties file and the ability
to publish application events to interested event listeners. This container is defined
by [Link] interface.
The ApplicationContext includes all functionality of the BeanFactory, It is generally recommended over
BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-
based applications.
The most commonly used ApplicationContext implementations are −
 FileSystemXmlApplicationContext − This container loads the definitions of the beans from an
XML file. Here you need to provide the full path of the XML bean configuration file to the
constructor.
 ClassPathXmlApplicationContext − This container loads the definitions of the beans from an
XML file. Here you do not need to provide the full path of the XML file but you need to set
CLASSPATH properly because this container will look like bean configuration XML file in
CLASSPATH.
 WebXmlApplicationContext − This container loads the XML file with definitions of all beans from
within a web application.
We already have seen an example on ClassPathXmlApplicationContext container in Spring Hello World
Example, and we will talk more about XmlWebApplicationContext in a separate chapter when we will
discuss web-based Spring applications. So let us see one example on FileSystemXmlApplicationContext.
Example
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −

Steps Description

1 Create a project with a name SpringExample and create a package [Link] under
the src folder in the created project.

2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello
World Example chapter.

3 Create Java classes HelloWorld and MainApp under the [Link] package.

4 Create Beans configuration file [Link] under the src folder.

5 The final step is to create the content of all the Java files and Bean Configuration file and run the
application as explained below.

Here is the content of [Link] file −

package [Link];

public class HelloWorld {


private String message;

public void setMessage(String message){


[Link] = message;
}
public void getMessage(){
[Link]("Your Message : " + message);
}
}

Following is the content of the second file [Link] −

package [Link];

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext
("C:/Users/ZARA/workspace/HelloSpring/src/[Link]");

HelloWorld obj = (HelloWorld) [Link]("helloWorld");


[Link]();
}
}

Following two important points should be noted about the main program −
 The first step is to create factory object where we used framework
APIFileSystemXmlApplicationContext to create the factory bean after loading the bean
configuration file from the given path. TheFileSystemXmlApplicationContext() API takes care of
creating and initializing all the objects ie. beans mentioned in the XML bean configuration file.
 The second step is used to get the required bean using getBean() method of the created context.
This method uses bean ID to return a generic object, which finally can be casted to the actual
object. Once you have an object, you can use this object to call any class method.
Following is the content of the bean configuration file [Link]

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "[Link]


xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<bean id = "helloWorld" class = "[Link]">


<property name = "message" value = "Hello World!"/>
</bean>

</beans>

Once you are done with creating the source and bean configuration files, let us run the application. If
everything is fine with your application, it will print the following message −
Your Message : Hello World!

Spring Bean Lifecycle Overview


This Figure shows two parts of the Spring bean lifecycle:
Part 1: Shows the different stages a bean goes through after instantiation until it is ready for
use.
Part 2: Shows what happens to a bean once the Spring IoC container shuts down.

As you can see in Part 1 of the preceding figure, the container instantiates a bean by calling
its constructor and then populates its properties.

This is followed by several calls to the bean until the bean is in the ready state.

Similarly, as shown in Part 2, when the container shuts down, the container calls the bean to
enable it to perform any required tasks before the bean is destroyed.

Constructor-based Dependency Injection

Constructor-based DI is accomplished when the container invokes a class constructor with a number of
arguments, each representing a dependency on the other class.

Example
The following example shows a class TextEditor that can only be dependency-injected with constructor
injection.
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −

Steps Description

1 Create a project with a name SpringExample and create a package [Link] under
the src folder in the created project.

2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello
World Example chapter.

3 Create Java classes TextEditor, SpellChecker and MainApp under the [Link] package.

4 Create Beans configuration file [Link] under the src folder.

5 The final step is to create the content of all the Java files and Bean Configuration file and run the
application as explained below.

Here is the content of [Link] file −

package [Link];

public class TextEditor {


private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) {
[Link]("Inside TextEditor constructor." );
[Link] = spellChecker;
}
public void spellCheck() {
[Link]();
}
}

Following is the content of another dependent class file [Link]

package [Link];

public class SpellChecker {


public SpellChecker(){
[Link]("Inside SpellChecker constructor." );
}
public void checkSpelling() {
[Link]("Inside checkSpelling." );
}
}

Following is the content of the [Link] file

package [Link];

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("[Link]");

TextEditor te = (TextEditor) [Link]("textEditor");


[Link]();
}
}

Following is the configuration file [Link] which has configuration for the constructor-based injection

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "[Link]


xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<!-- Definition for textEditor bean -->


<bean id = "textEditor" class = "[Link]">
<constructor-arg ref = "spellChecker"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "[Link]"></bean>

</beans>

Once you are done creating the source and bean configuration files, let us run the application. If
everything is fine with your application, it will print the following message −
Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.

Spring Setter-based Dependency Injection


Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a
no-argument constructor or no-argument static factory method to instantiate your bean.

Example
The following example shows a class TextEditor that can only be dependency-injected using pure setter-
based injection.
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −

Steps Description

1 Create a project with a name SpringExample and create a package [Link] under
the src folder in the created project.

2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World
Example chapter.

3 Create Java classes TextEditor, SpellChecker and MainApp under the [Link] package.

4 Create Beans configuration file [Link] under the src folder.

5 The final step is to create the content of all the Java files and Bean Configuration file and run the
application as explained below.

Here is the content of [Link] file −


package [Link];

public class TextEditor {


private SpellChecker spellChecker;

// a setter method to inject the dependency.


public void setSpellChecker(SpellChecker spellChecker) {
[Link]("Inside setSpellChecker." );
[Link] = spellChecker;
}
// a getter method to return spellChecker
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
[Link]();
}
}

Here you need to check the naming convention of the setter methods. To set a variable spellChecker we
are using setSpellChecker() method which is very similar to Java POJO classes. Let us create the content
of another dependent class file [Link] −
package [Link];

public class SpellChecker {


public SpellChecker(){
[Link]("Inside SpellChecker constructor." );
}
public void checkSpelling() {
[Link]("Inside checkSpelling." );
}
}

Following is the content of the [Link] file −


package [Link];

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("[Link]");

TextEditor te = (TextEditor) [Link]("textEditor");


[Link]();
}
}

Following is the configuration file [Link] which has configuration for the setter-based injection −
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "[Link]


xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<!-- Definition for textEditor bean -->


<bean id = "textEditor" class = "[Link]">
<property name = "spellChecker" ref = "spellChecker"/>
</bean>

<!-- Definition for spellChecker bean -->


<bean id = "spellChecker" class = "[Link]"></bean>

</beans>
You should note the difference in [Link] file defined in the constructor-based injection and the setter-
based injection. The only difference is inside the <bean> element where we have used <constructor-arg>
tags for constructor-based injection and <property> tags for setter-based injection.
The second important point to note is that in case you are passing a reference to an object, you need to
use ref attribute of <property> tag and if you are passing a value directly then you should use value
attribute.
Once you are done creating the source and bean configuration files, let us run the application. If
everything is fine with your application, this will print the following message −
Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.

XML Configuration using p-namespace


If you have many setter methods, then it is convenient to use p-namespace in the XML configuration file.
Let us check the difference −
Let us consider the example of a standard XML configuration file with <property> tags −
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "[Link]


xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<bean id = "john-classic" class = "[Link]">


<property name = "name" value = "John Doe"/>
<property name = "spouse" ref = "jane"/>
</bean>

<bean name = "jane" class = "[Link]">


<property name = "name" value = "John Doe"/>
</bean>

</beans>

The above XML configuration can be re-written in a cleaner way using p-namespace as follows −
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "[Link]


xmlns:xsi = "[Link]
xmlns:p = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<bean id = "john-classic" class = "[Link]"


p:name = "John Doe"
p:spouse-ref = "jane"/>
</bean>

<bean name =" jane" class = "[Link]"


p:name = "John Doe"/>
</bean>
</beans>

Here, you should note the difference in specifying primitive values and object references with p-
namespace. The -ref part indicates that this is not a straight value but rather a reference to another bean.

Listening to Context Events


To listen to a context event, a bean should implement the ApplicationListener interface which has just one
method onApplicationEvent(). So let us write an example to see how the events propagates and how
you can put your code to do required task based on certain events.
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −

Step Description

1 Create a project with a name SpringExample and create a package [Link] under
the src folder in the created project.

2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World
Example chapter.

3 Create Java classes HelloWorld, CStartEventHandler, CStopEventHandler and MainApp under


the [Link] package.

4 Create Beans configuration file [Link] under the src folder.

5 The final step is to create the content of all the Java files and Bean Configuration file and run the
application as explained below.

Custom Events in Spring

There are number of steps to be taken to write and publish your own custom events. Follow the
instructions given in this chapter to write, publish and handle Custom Spring Events.

Steps Description

1 Create a project with a name SpringExample and create a package [Link] under
the src folder in the created project. All the classes will be created under this package.

2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello
World Example chapter.
3 Create an event class, CustomEvent by extending ApplicationEvent. This class must define a
default constructor which should inherit constructor from ApplicationEvent class.

4 Once your event class is defined, you can publish it from any class, let us
say EventClassPublisher which implements ApplicationEventPublisherAware. You will also need to
declare this class in XML configuration file as a bean so that the container can identify the bean as
an event publisher because it implements the ApplicationEventPublisherAware interface.

5 A published event can be handled in a class, let us say EventClassHandler which


implements ApplicationListener interface and implements onApplicationEvent method for the
custom event.

6 Create beans configuration file [Link] under the src folder and a MainApp class which will
work as Spring application.

7 The final step is to create the content of all the Java files and Bean Configuration file and run the
application as explained below.

Here is the content of [Link] file

package [Link];

import [Link];

public class CustomEvent extends ApplicationEvent{


public CustomEvent(Object source) {
super(source);
}
public String toString(){
return "My Custom Event";
}
}

Following is the content of the [Link] file

package [Link];

import [Link];
import [Link];

public class CustomEventPublisher implements ApplicationEventPublisherAware {


private ApplicationEventPublisher publisher;

public void setApplicationEventPublisher (ApplicationEventPublisher publisher) {


[Link] = publisher;
}
public void publish() {
CustomEvent ce = new CustomEvent(this);
[Link](ce);
}
}

SPRING MVC Layering

Understanding Spring MVC Flow Diagram


1. Request
The first step in the MVC flow is when a request is received by the Dispatcher Servlet.

2. Dispatcher Servlet

Now, the Dispatcher Servlet will with the help of Handler Mapping understand the
Controller class name associated with the received request. Once the Dispatcher Servlet
knows which Controller will be able to handle the request, it will transfer the request to it.

3. Controller

The Controller will process the request based on appropriate methods and will return it to
Model Data and View Name.
4. Model and View

It will return the processed data to the Dispatcher Servlet.

5. View Resolver

Once Model and View receive the data, Dispatcher Servlet will transfer it to the View
Resolver to get the actual view page.

6. View

Finally, the Dispatcher Servlet will pass the Model object (results) to the view page. This is
the final step of the flow where the results will be displayed.

The DispatcherServlet

The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that
handles all the HTTP requests and responses. The request processing workflow of the Spring Web
MVC DispatcherServlet is illustrated in the following diagram −

Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −


 After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the
appropriate Controller.
 The Controller takes the request and calls the appropriate service methods based on used GET or
POST method. The service method will set model data based on defined business logic and returns
view name to the DispatcherServlet.
 The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request.
 Once view is finalized, The DispatcherServlet passes the model data to the view which is finally
rendered on the browser.
Defining a Controller

The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it.
The @Controller annotation indicates that a particular class serves the role of a controller.
The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler
method.

@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(method = [Link])
public String printHello(ModelMap model) {
[Link]("message", "Hello Spring MVC Framework!");
return "hello";
}
}

The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage
of @RequestMapping indicates that all handling methods on this controller are relative to
the /hello path. Next annotation @RequestMapping(method = [Link]) is used to
declare the printHello() method as the controller's default service method to handle HTTP GET request.
You can define another method to handle any POST request at the same URL.

According to the underlying technologies, the spring will translate according to their native
exceptions.

Data Access Object (DAO)

DAO stands for Data Access Object, which is commonly used for database interaction. DAOs exist to
provide a means to read and write data to the database and they should expose this functionality through
an interface by which the rest of the application will access them.
The DAO support in Spring makes it easy to work with data access technologies like JDBC, Hibernate, JPA,
or JDO in a consistent way.

Spring Configuration File


Spring bean configuration file contains spring bean configurations, dependent value configurations,

and other miscellaneous configurations. Any name can be given to Spring Bean configuration file with

.xml extension. <beans> tag is the root element., this encloses all the spring definitions. <bean> tag

defines spring bean i.e. a java class to be initialized and managed by spring core container. Every spring
bean class must be configured in spring configuration file, and then only spring container recognizes

that class. Every Spring Bean will be identified through its Bean id, which is a value given in id attribute

of <bean>. Placing DOCTYPE statements or schema statements (namespace) at the top of the spring

configuration file is mandatory. For each module in spring we have to use separate DOCTYPE

statements or schema statements (namespace)


1. DOCTYPE statements for dtd rules

2. Schema statements(namespace) for xsd rules

We can use any one either DOCTYPE statements or schema statements (namespace). XML Schema-

based configuration introduced in Spring 2.0. It is most used in spring apps.

Spring Configuration File example

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "[Link]


<beans>
<bean id="studentbean" class="[Link]">
<property name="name" value="Manu_Manjunatha"></property>
</bean>
</beans>

Event Handling in Spring


You have seen in all the chapters that the core of Spring is the ApplicationContext, which manages the
complete life cycle of the beans. The ApplicationContext publishes certain types of events when loading the
beans. For example, a ContextStartedEvent is published when the context is started and ContextStoppedEvent is
published when the context is stopped.

Event handling in the ApplicationContext is provided through the ApplicationEvent class


and ApplicationListener interface. Hence, if a bean implements the ApplicationListener, then every time
an ApplicationEvent gets published to the ApplicationContext, that bean is notified.
Spring provides the following standard events −

[Link]. Spring Built-in Events & Description

1
ContextRefreshedEvent
This event is published when the ApplicationContext is either initialized or refreshed. This can
also be raised using the refresh() method on the ConfigurableApplicationContext interface.

2
ContextStartedEvent
This event is published when the ApplicationContext is started using the start() method on
the ConfigurableApplicationContext interface. You can poll your database or you can restart
any stopped application after receiving this event.

3
ContextStoppedEvent
This event is published when the ApplicationContext is stopped using the stop() method on
the ConfigurableApplicationContext interface. You can do required housekeep work after
receiving this event.

4
ContextClosedEvent
This event is published when the ApplicationContext is closed using the close() method on
the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot
be refreshed or restarted.

5
RequestHandledEvent
This is a web-specific event telling all beans that an HTTP request has been serviced.

Spring's event handling is single-threaded so if an event is published, until and unless all the receivers
get the message, the processes are blocked and the flow will not continue. Hence, care should be taken
when designing your application if the event handling is to be used.

You might also like