0% found this document useful (0 votes)
78 views

MCS 220

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)
78 views

MCS 220

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
You are on page 1/ 397

UNIT 1 INTRODUCTION TO J2EE

ARCHITECTURE AND DESIGN


PATTERN
Structure
1.0 Introduction
1.1 Objectives
1.2 Web Server and Web Container
1.3 Introduction to J2EE
1.4 Design Patterns
1.4.1 MVC
1.4.2 Repository Design Pattern
1.4.3 Singleton
1.4.4 Factory
1.5 Building Java Application JAR and WAR and deployment in Tomcat
1.6 Summary
1.7 Solutions/Answer to Check Your Progress
1.8 References/Further Reading

1.0 INTRODUCTION

You are well aware of the java programming language, which is an object oriented
programming language. Java technology provides the specific environment in which
Java programming language applications run. The J2EE platform provides runtime
environment for developing and running large-scale, multi-tiered online/web and
internet applications. This unit will give you an introduction of J2EE and its
architecture. Also in this unit you will be introduced to some well-known design
patterns. Design patterns give readymade explanations/solutions or templates to
commonly occurring problems in the programming language. Design patterns are the
best solutions that are tested and verified prototypes that can speed up your
development process. There are many design patterns but it is not possible to cover all
patterns in this course. This unit covers MVC, Repository, Singleton, Factory design
patterns and some important terms, including Web server and Web Container. This
unit will also provide you with the skill and process to package Java Application
project to JAR/WAR and deploy your application in Tomcat.

The next Unit 2 and 3 of this block will give you detailed discussions on Servlet
programming and session management in web applications. Unit 4 of this block will
provide you with a basic understanding of Java Server Pages ( JSP) components that
make an entire JSP page, Java Bean, Custom tag, and many other concepts used in
JSP. After studying this block, you will be able to use design patterns and build your
java application using data retrieval and data storage in Servlets/JSP programming
and their deployment in Tomcat.

1.1 OBJECTIVES

After going through this unit, you should be able to:

• differentiate between web server and web container,


• know about design patterns and different types of design patterns,

1
Introduction to J2EE
Architecture and Design
• explain where and why singleton pattern is used,
Pattern
• explain factory method design pattern and how to implement it,
• know the difference between jar and war files and packaging of java
application to JAR/WAR file, and
• deploy java application as war file.

1.2 WEB SERVER AND WEB CONTAINER

You are well aware about web applications and you have opened many web
applications on the internet. Assume that you have filled a form on this and received a
response from them. This communication between you and web application are
fulfilled using HTTP request and HTTP response with HTTP Protocol and method
(You can study much more about these in the next Unit of this Block). When you
write your programme in a programming language such as Servlet and JSP (this will
be covered in detail in Unit 2, 3 and Unit 4 of this Block), you will be using some
other terms like Web Server and Web Container in addition to HTTP request and
response. This section describes you about the Web Server and Web Container.
Web Server is a server software that handles HTTP requests and responses to deliver
web pages or web content to clients (i.e. web browser) using HTTP protocol. Web
browser communicates with web server using the Hypertext Transfer Protocol
(HTTP). Hypertext Transfer Protocol (HTTP) is specially meant to communicate
between Client and Server using Web (or Internet). To successfully execute web
application, the number of server side technologies (such as JSP, Servlets and PHP)
and their libraries are installed on the web server. Without these libraries, a web server
cannot execute those server technologies based applications. In other words, we may
say that the web server creates an execution infrastructure for the server technologies.
An example of web server is Apache HTTP Server.
Web Container is a web server component that handles Servlets, Java Server Pages
(JSP) files, and other Web-tier components. Web container is also called a Servlet
Container or Servlet Engine. It is the responsibility of the Web container to map a
URL to a particular servlet. Also, Web container ensures that the mapped URL
requester has the correct access rights. It means that it provides the run time
environment to web applications. The most common web containers are Glassfish,
Eclipse, JBOSS, Apache Tomcat, WebSphere and Web Logic.
For deployment and running the JSPs/Servlets we need a compatible web server with
a servlet container.
You can know more about the Java 2 Enterprise Edition (J2EE) and its uses in java
programming in the next section.

1.3 INTRODUCTION TO J2EE

In the previous section, you have learned about the two most important terms web
server and web container which are required for Java programming. Through this
section you know about the Java 2 Enterprise Edition (J2EE).
You are well aware about core java or Java Standard Edition (Java SE). Java SE
provides all core functionalities of java programming language. Java technology is
used as a programming language as well as a platform. A Java platform provides a
specific environment in which Java applications run. The Java Enterprise Edition
platform resides on top of the Java Standard Edition platform.
2
The J2EE platform is a set of services, application programming interfaces (APIs) and Web Application
Development using J2EE
protocols. J2EE is used to develop and deploy multi-tier web-based enterprise
applications using a series of protocols and application programming interfaces
(APIs). J2EE contains several APIs such as Java Servlets, Java Server Pages (JSP),
Enterprise Java Beans (EJB), Java Database Connectivity (JDBC), Java Message
Service (JMS), Java Naming and Directory Interface (JNDI) and so on.
The J2EE application model divides applications into three basic parts like
components, containers and connectors. The application developers works on the
components part, whereas system vendors are responsible for implementing
containers and connectors. Containers act as a mediator between clients and
components by providing services like transaction support and resource pooling.
Connectors provide bidirectional communication between J2EE components and
enterprise systems. Below in figure 1, you can depict the functioning of J2EE model:

Presentation Layer Business Layer Databas


e Layer

Client Web Business Persistence


L Logic Layer Layer

Web Java EE Container


Browser Web Container EJB Container JPA Persistence
Engine
Enterprise
Servlet Bean Relationa
Java
App.
l
Enterprise Database
Client JSP Page Entity
Bean
Client machine
App. Client
Controller

Figure 1: J2EE Architecture

A J2EE application contains four components or tiers: Presentation, Application,


Business, and Resource adapter components. The presentation component is the client
side component that is visible to the client and runs on the client’s server. The
Application component is web side layer that runs on the J2EE server. The business
component is the business layer which includes server-side business logic such as
JavaBeans, and it is also run on the J2EE server. The resource adaptor component
comprises an enterprise information system.
When you develop J2EE application, you may find J2EE clients such as a web client,
an application client, wireless clients or Java Web Start-enabled clients. For running
J2EE application, you need a J2EE container which is a server platform, Java
component can be run on this container using APIs provided through the Web
container and EJB container. The EJB container is a server platform used for
controlling the execution of Enterprise Bean. Also, the EJB container job is to provide
local and remote access to enterprise beans.
For creating complex applications, you can use J2EE frameworks like Struts, Spring
and Hibernate, which will you read in block-2 of this course.

3
Introduction to J2EE
Architecture and Design ☞ Check Your Progress 1
Pattern
1. What is a web server, and how does it differ from a web container? Also,
name any four web containers.

2. What is J2EE? What are the components of J2EE applications? What


technologies are included in the J2EE platform?

3. Define the term module in J2EE. What are the four specific modules used in
J2EE applications?

1.4 DESIGN PATTERNS

The previous section has given you an introductory lesson on the Java 2 Enterprise
Edition (J2EE). This section gives a detailed description of the Design Patterns and
their types and uses in Java.
Design patterns are the best solutions that are tested, verified developed prototypes
that can speed up your development process. When you may face problems during
software development, the design patterns gives you explanations for those problems.
Experienced developers have developed these explanations to provide the finest
solutions to the problems. It is also beneficial for un-experienced software developers
to learn software design in a simpler manner. The concept of design pattern has been
initiated by four authors collectively known as GOF (Gang of Four), and they have
published a book (Design Patterns - Elements of Reusable Object-Oriented Software)
on this concept. Design Patterns provides a general reusable solution to commonly
occurring problems. It is not a complete design that can be directly mapped into your

4
code and solve your purpose. It is just like a template or explanation for how to solve Web Application
Development using J2EE
your problems. It offers a common platform for all software developers.
There are 23 classic design patterns and they are categorized into three groups:
Creational, Structural and Behavioral. The Creational design patterns deal with the
creation of an object. Structural design patterns deal with the class structure, and the
behavioral design patterns define the interaction between objects.
Creational design patterns
The Creational design patterns provide a way to deal with the creation of an object
and define 5 design patterns such as Abstract Factory, Builder, Factory, Prototype and
Singleton pattern from which two like Singleton and Factory design pattern are to be
discussed below. The Abstract Factory design pattern allows to create families of
related objects. This pattern permits us to create a Factory for factory classes. The
Builder design pattern provides a valuable solution to many object creation problems
in object-oriented programming. The objective of this pattern is to separate the
creation of a complex object from its representation. The Prototype design pattern
allows us to produce new objects by cloning an existing object using
a clone() method. This pattern is useful when a particular resource is costly to create
or when the abstract factory pattern is not preferred.
Structural design patterns
The Structural design patterns are related to the creation of class and object structure.
These patterns define seven design patterns: Adapter, Bridge, Composite, Decorator,
Façade, flyweight, and Proxy. The Adapter design pattern provides a way to work as
a link between two unrelated interfaces. The object that links these incompatible or
unrelated interfaces is called an Adapter. So, the adapter design pattern permits the
interface of an existing class to be used as another interface. The adapter pattern is
generally used to make available the existing classes for others without changing their
source code. The objective of the Bridge design pattern is to decouple an
abstraction from its im plem entation so that the tw o can perform
independently. The bridge uses object oriented program m ing principles
such as encapsulation,aggregation and inheritance to separate duties into
different classes.This pattern is usefulw hen the class and its functionality
vary a lot.The Composite design pattern defines a pool of objects that are to be
treated as a single object. The Decorator design pattern is used to change the
functionality of an object at runtime. The Façade design pattern is used to generating
wrapper interfaces on top of existing interfaces, and it hides the complications of the
system and arranges a simpler interface to the client application. The Flyweight
design pattern moderates the cost of generating and controlling a large number of
related objects. The Proxy design pattern is used as a procurator or placeholder for
another object to regulate the access and reduce cost as well as reduce complexity.
Behavioral design patterns
The third design patterns category is Behavioral, which defines 11 design patterns:
Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento,
Observer, State, Strategy, Template Method, and Visitor. They are specifically
concerned with the interaction between objects. As the name recommends, the chain
of responsibility design pattern builds a chain of receiver objects for a request. This
pattern is used where the request sender is disassociated from its receiver based on the
type of request. The Command design pattern is used to create objects containing
information about an action, such as method name, owner of the method, and
Parameter values necessary to be produced later. As the name suggests, the
Interpreter design pattern provides an interpreter to deal with language grammar and
it is used to interpret sentences in a language. The Iterator design pattern provides a
way to access the collection object without revealing its underlying representation.

5
Introduction to J2EE
Architecture and Design
This pattern is frequently used in Java and .Net programming languages. Mediator
Pattern design pattern provides a communication medium or a mediator class that handles all
the communications between different classes. The capability of Memento design
pattern is used to restore an object to its earlier state. The Observer design pattern is
beneficial when an object is changed; then, you can get notified about the state of the
object through this pattern. The State design pattern permits an object to modify its
behaviour when its inner state is modified. The Strategy pattern or policy design
pattern allows selecting an algorithm during runtime. The Template Method design
pattern provides a way to create a superclass template method and permit its child
classes to provide concrete behaviour. The Visitor design pattern gives a way to
separate an operation from the object structure on which it operates. The basic
purpose of this pattern is to define a new operation without modifying the original
classes.
Besides these design patterns some more design patterns are also available. The MVC,
Repository, Singleton and Factory design patterns are discussed below:
1.4.1 MVC Design Pattern
Model View Controller (MVC) design pattern is an architectural pattern for web
applications. It can be used across many frameworks with many programming
languages such as Java, PHP, Python, Ruby, etc. This design pattern is extensively
used to design enterprise web applications and mobile applications. The MVC design
pattern comprises three layers such as data, presentation and control information. This
pattern requires each of these layers to act independently.
The MVC design pattern described three layers such as Model, View and Controller.
In MVC pattern, M (Model) denotes only the pure application data and does not
contain any logic for representing data to a user, whereas V (View) is responsible for
presenting data to the user. The C (Controller) comes between the view and the model
layer and it is responsible for accepting a request from the user, performs interactions
on the data model objects, and sends it back to the view layer.
The UML diagram of MVC design pattern is depicted in figure 2. The following
example demonstrates to you how MVC design pattern will work. The example
contains total of four java files, from which three java files for MVC layers and one
java file containing the main() method. For defining the MVC pattern, the first java
file is created as ‘UniversityModel’, which acts as a model, ‘univView’ as a view that
can display university details and ‘UnivController’ file is responsible for storing the
data in univ object and updateView() method updates the data in a ‘univView’ class
method. The ‘MVCExample’ file will use ‘UnivController’ file to illustrate the MVC
pattern.

Figure 2: UML class diagram of MVC design pattern is

6
Web Application
Development using J2EE
All files of MVC pattern example containing java source code are listed below.
1. You can create a UniversityModel.java file using the following code:
// UniversityModel.java
public class UniversityModel
{
private String name;
private String loc;

public String getName()


{return name; }

public void setName(String name)


{this.name = name; }

public String getLoc()


{return loc; }

public void setLoc(String loc)


{this.loc = loc; }
}

2. You can create a univView.java file using the following code:


// univView.java
public class univView
{
public void display(String univName, String univLoc)
{
System.out.println("University Details: ");
System.out.println("Name: " + univName);
System.out.println("Location: " + univLoc);
}
}

3. You can create a UnivController.java file using the following code:

// UnivController.java
public class UnivController
{
private UniversityModel model;
private univView view;

public UnivController(UniversityModel model, univView view)


{
this.model = model;
this.view = view;
}
public void setUnivName(String name)
{
model.setName(name);
}
public String getUnivName()
{
return model.getName();
7
Introoduction to J2E
EE
Archhitecture and Design
D
}
Patteern public void
v setUnivL
Loc(String locc)
{
mod del.setLoc(locc);
}
public String
S getLoc()
{
retuurn model.getLoc();
}
public void
v updateViiew()
{
vieww.display(moodel.getName(), model.getL
Loc());
}
}

4. Now, create
c a MVC
CExample.javaa file using thhe following code
c
//MVCExam mple.java
public class MVCExampple
{
public static void maain(String[] arrgs)
{
UniveersityModel m model = retriivedata();

//Creaate a view : too write studennt details on console


univV
View view = new n univView w();
UnivCController conntroller = new w UnivControoller(model, view);
v
controoller.updateVView();
}
private static UniverssityModel reetrivedata()
{
UniveersityModel uuniv = new UnniversityModdel();
univ.ssetName("IGN NOU");
univ.ssetLoc("Maiddan Garhi");
returnn univ;
}
}

5. Now, compile
c all thhe files using javac commaand and run MVCExample
M e file with
java as shown in figgure-3:

Figuree 2: Output Screeen for MVC paattern Examplee


8
Web Applicaation
1.4.22 Repository Design
n Pattern Developmen
nt using J2EE

In pllain words, repository meeans somethinng is deposited in storagee. The repository


mean ning is same as in terms of design patteern, it is relatted to the dataa. The repository
desiggn pattern is used in data--centric appliications. The Repository pattern
p is used to
isolaate the busineess logic layeer and the daata source layyers in your application. The
repossitory layer comes
c betweeen the domaiin and data m mapping layeers. As shownn in
figurre 4, the repository residess in the mid of
o the client bbusiness logicc and data souurce
layerr. At the data source layer, a database caan be kept/useed.

Figure 4: Block diagram


d for Repository
R Dessign Pattern
Supppose client buusiness logic wishes a qu uery from datta source then n it first goees to
repossitory layer thereafter
t rep
pository will send the queery to the daatabase, and tthen
t data to the business enntity. Similarlly, when client business loogic
repossitory maps the
base, data willl not directly go to the dataabase but willl go
wantts to save dataa in the datab
throu
ugh the reposiitory layer.
Whille using repository pattern
n, your appliccation’s businness logic layyer need not hhave

F
Figure 5: UML
L diagram forr Course Repoository

any knowledge
k on data persistence, it meaans the reposiitory layer prrovides a wayy to
hide the internall implementaation of how w data persisstence happens. This waay it
empo owers you to replace your data source without
w changging your bussiness logic. T
This
patteern is useful when
w you havve several en
ntities, and coomplex queriees are appliedd on
thosee entities.
This pattern is onne of the mostt popular Javva persistencee patterns. This pattern is uused
with JPA and other framework ks. A JPA (Jaava Persistencce API) is a java specificaation
and defined
d in javvax.persistennce package. JPA is used to access and d manage perrsist
data between Javva object andd relational database.
d JPA
A can act ass a link betw ween
objecct-oriented domain
d modeels and relaational databaase systems.. Various O ORM
(Object Relationaal Mapping) tools
t such as Hibernate, Sppring are used by the JPA A for
implementing dataa persistence..
Assuume that youu want to deevelop a couurse repository for a uniiversity databbase
appliication. For thhis, you needd persistent daata storage foor courses whhere you may add
and remove
r coursses and searchh for them. Fo or using repoository designn pattern, you can
creatte an interfacee that definess read and wrrite operations for a speciffic entity and this
9
Introoduction to J2E
EE
Archhitecture and Design
D
interface is implementedd by data stoore related classes. The UML
U diagram
m for such
Patteern repository iss as follows:
In the UML L diagram, youu have seen thhat there are ffour methods in ‘CourseReepository’
interface thaat you can usse to find a coourse by codee and name; save and deleete course
entity. You can create a course repossitory interfacce like the foollowing codee and then
write a classs for implem menting ‘Cou urseRepositorry’ interface. If you are using
u any
framework such as Sprinng Data JPA and Apache DeltaSpike Data D then youu can only
define the repository interfaces, and a these frrameworks canc generate standard
repository immplementatioons for you. Also,
A you cann write your own
o implemeentation as
per the requuirements of tthe implemenntation compllexity of yourr problem. Foor running
this pattern, you need database
d connnectivity withh J2EE framework. The repository
r
design patteern is strongeer to you whhen you will read J2EE frrameworks inn the next
Block-2 of this
t course.
public interrface CourseeRepository
{
Course getCourseByC
g Code(String code);
c
Course getCourseByN
g Name(String name);
n
Course saveCourse(C Course c);
void deleeteCourse(Coourse c);
}

1.4.3 Sin
ngleton Dessign Pattern
The singletoon pattern is a simplest sofftware design pattern amonngst the 23 weell-known
"Gang of Four"
F design patterns andd it comes uunder the creeational desiggn pattern
category, which
w deals wiith the creatioon of an object. As the namme suggests, Singleton
design patteern is used to create only one instance oof a class, andd all other classses of the
application can use thiss instance. Th his type of pattern
p is moostly used inn database
connection and multi-thhreaded appliications. Singgleton patterrn is used inn logging,
caching, thrread pools, configuration settings etc. You can usee Singleton pattern p in
other designn patterns likke Abstract Factory,
F Buillder, Facade, Prototype etc.,
e while
developing your own sollutions to a sppecific problem m.
The UML class diagram of Singleton pattern is as uunder:

Figuree 3: UML classs diagram of S


Singleton patttern

An implem mentation of this patternn must ensurre that only one instancce of the
singleton cllass will exisst and that innstance provides global acccess to otheers. While
implementin ng singletonn pattern, coonstructors oof the class must be deeclared as
private, andd method is defined
d as puublic static that returns thee instance of the class.
The instancce is typicallly stored as a private staatic variable. The static variable
v is
initialized at
a some point before the sttatic method iis first calledd.
Java core libbraries providde many classses which aree written usinng singleton pattern.
p A
few of them
m are listed below:

• Javaa.lang.Runtim
me with getRu
untime() methhod

10
Web Applicaation
• Java.awt.T
Toolkit with getDefaultTo
g oolkit()
Developmen
nt using J2EE
• Java.awt.D
Desktop with
h getDesktop()

A sample implem
mentation of Singleton
S design pattern inn Java is as fo
ollows:
publlic final classs Singleton
{
//A
A singleton cllass should haave public visibility
//sttatic instancee of class globbally accessibble
priivate static finnal Singletonn instance = new
n Singletonn();
priivate Singleto on()
{
/*
/ private connstructor, so that
t class can
nnot be instanntiated from outside
o this cclass
*/
}
pub blic static Sinngleton getIn
nstance()
{
/*declaration
/ of the methood as public static, so that instance can be used by
other
o classes */
return
r instancce;
}
}

The following exaample illustraates to you ho


ow the Singleeton design paattern works. For
this example,
e UM
ML class diagrram is as show wn in figure 77:

This Singleton Deesign Pattern example conntains two claasses. One is ‘SingletonClaass’,
whicch behaves ass Singleton cllass. This class have privaate constructo
or and providdes a
staticc method too get its staatic instance to other cllasses. The second classs is
‘SinggletonExamplle’, which use
u an instaance of the ‘SingletonCllass’ class. The
implementation off this example is underneaath.

11
Introoduction to J2E
EE
Archhitecture and Design
D
• First, yo
ou can createe a Singleton Class as the name of ‘SinngletonClass’ using the
Patteern followinng source codde:

// SingletonC Class.java
public class SingletonClaass
{
//create ann object of SinngletonClass
privvate static SinngletonClass instance
i = new
w SingletonC
Class();
privvate SingletonnClass(){}
pubblic static SinggletonClass getInstance()
g
{
retuurn instance;
}
pubblic void displlay()
{
System.out.println("Hello Stuudents in SOC CIS, IGNOU"");
}
}

• Create another
a class called ‘SinglletonExamplee’ to get the only instancee from the
singletoon class. The ccode of this class
c is listed below:
b
// SinglletonExamplee.java
public class SingletoonExample
{
pubblic static voidd main(String
g[] args)
{
//G
Get the instannce created byy Singleton cllass
SiingletonClasss instance = SingletonClas
S s.getInstance();
in
nstance.displaay(); //disp play data
}
}

• Now
w compile thee both classess and run the ‘SingleExam
mple’. The outtput of the
thiss example is ddisplayed in following figgure-8:

Figu
ure 4: Output Screen for Singleton examp
ple

1.4.4 Facctory Desiggn Pattern


In the prevvious sectionn, the Singleeton design pattern has been explaiined. The
Singleton deesign pattern belongs to thhe Creationall pattern categgory. As you know, the

12
creattional pattern is related to the creation of
o the object. In this sectio
on, you will leearn Web Applicaation
Developmen
nt using J2EE
one more
m design pattern
p namedd Factory, whhich also com
mes in the sam me category.
A Faactory Design n Pattern or Factory
F Methhod Pattern iss one of the most
m used design
patteern in java. Itt is a creationnal design paattern which deals with thhe creation of an
objecct. As per thee GOF, this pattern
p defines an interfacee or abstract class
c for creaating
an ob bject, but subbclasses are responsible forf creating tthe instance of o the class. The
advaantage of Facctory Pattern is that it alloows the sub-cclasses to chhoose the typee of
objeccts to create. In other words, this patterrn is used to create an objject where obbject
creattion logic is hidden
h to thee client and refers
r to the newly createed object usinng a
comm mon interfacee. This designn pattern is alsso known as ‘‘Virtual Consstructor’.
To immplement thee Factory Dessign Pattern, first,
f you defiine a factory method
m insidee an
interface or abstrract class and bclass use thhe above facttory method and
d let the sub
decidde which objeect to create.
Facttory Design Pattern
P impleementation

The following exxample demo


onstrates to you
y how to w
work Factoryy Design Patttern.
Assuume that IGN
NOU wants to send annouuncement dettails of new courses to users
u

Fig
gure 5: UML diagram for Factory
F Design
n Pattern

throuugh Facebookk, Email and SMS.


S Let’s immplement thiss example with the help off the
Factoory design paattern. For implementing
i g this, first, yyou can design a UML class
c
diagrram, and thhen you cann transform this class diagram in nto source ccode
implementation. UML
U class diagram for thiis example ussing the Facto
ory design patttern
is sho
own in figuree 9.
For implementinng the abov ve class diag gram, you can create an interfacee as
Anno ouncement annd three conncrete classess such as Faacebook.java,, Email.java and
SMS S.java. These three classees can impleement ‘Annouuncement’ innterface. Besides
thesee, you can also
a create two
t more cllasses. Youu can create a factory class
c
‘AnnnouncementFaactory.java’ to get ann Announceement objecct. Creation of
‘AnnnouncementIGGNOU.java’ class is to useu factory cclass and gett an object ofo a
concrete class.

13
Introduction to J2EE
Architecture and Design
Now you can follow the steps for the creation and running the example of Factory
Pattern design pattern:
• First, you can create Announcement interface.

public interface Announcement


{
void sendMSG();
}

• Now, you can create all three classes implementing the same interface as per the
following codes:

//Facebook.java
public class Facebook implements Announcement
{
public void sendMSG()
{
System.out.println("Sending announcement through Facebook");
}
}

//Email.java
public class Email implements Announcement
{
public void sendMSG()
{
System.out.println("Sending announcement as an e-mail");
}
}

//SMS.java
public class SMS implements Announcement
{
public void sendMSG()
{
System.out.println("Sending announcement as an SMS");
}
}

• Now, you can create a Factory Class ‘AnnouncementFactory.java’ as code listed


below:

// AnnouncementFactory.java
public class AnnouncementFactory
{
public Announcement createAnnouncement(String media)
{
if (media == null || media.isEmpty())
return null;
if ("Facebook".equals(media))
{
return new Facebook();
}
else if ("EMAIL".equals(media))
{
14
return new Email();
E Web Applicaation
Developmen
nt using J2EE
}
else
e if ("SMS".equals(meddia))
{
return new SMS();
}
return
r null;
}
}

• You
Y can creeate ‘Announ
ncementIGNO
OU.java’. Ussing this file, you can use
‘Announceme
‘ entFactory’ class to createe and get an oobject of conncrete class. Here
H
you
y are passinng some inforrmation as “F
Facebook”.
// Announcem mentIGNOU.jjava
public class Announcemen
A ntIGNOU
{
public static void main((String[] args))
{
Announ ncementFacto ory anFactoryy = new AnnoouncementFacctory()
Announ ncement annoouncement =
anFactoory.createAnnnouncement(""Facebook");
announcement.sendM MSG();
}
}
• Now, you caan compile alll the java filees and run ‘A
AnnouncemenntIGNOU’ as per
the following
g figure 10. This
T figure is also
a shown ouutput at the coommand prom
mpt.

Figure 6:
6 Compiling and
a output scrreen for Factoory pattern exxample

Up to now, you have


h learned about the dessign patterns,, including MVC,
M Reposittory,
Singleton and Facctory, and hoow to implemment these pattterns. In the next section,, we
will learn
l about th
he building an
nd deploymennt of java/J2E
EE applicationns

15
Introduction to J2EE
Architecture and Design ☞ Check Your Progress 2
Pattern
1. What do you mean by Design Patterns? Can you name some of the design
patterns used in JDK core libraries?

2. What is Singleton pattern? Name one singleton class in Java. How can you
create Singleton class in java? Can we create a clone of a singleton object? If
yes, then how to prevent cloning of a singleton object?

3. Explain the benefits of Factory pattern.

1.5 BUILDING JAVA APPLICATION JAR AND


WAR AND DEPLOYMENT IN TOMCAT

This section will help you to understand about building java applications to JAR and
WAR files and deployment in Tomcat. The following sections described to you how
to create WAR file, how to deploy WAR file and how to extract WAR file. You will
find more about the installation process of Apache’s Tomcat and running and
deployment of your Servlets and JSP programs in section 2.7 of Unit 2 of this Block-
1. Before an understanding of this description, you will know about the JAR and
WAR packaging in Java.
JAR Packaging
The JAR (Java Archive) is a package file format. The file extension of JAR files
is .jar and may contain libraries, resources, and metadata files. Basically, it is a zipped
file containing the compressed versions of .class files, compiled Java libraries and
applications. You can create a JAR file using the jar command like the following. You

16
can also
a create JA AR files usingg IDEs. You can
c learn morre about jar files in ‘Refereence Web Applicaation
Developmen
nt using J2EE
Sectiion’ of this Unit.
U

jar cf nam
me-jar-file inp
put-file(s)

Where c option iss used to creaate a JAR file, f option speecifies the outtputs which ggo to
a filee. You can deefine any fileename for a JAR
J file. Usinng the input--file(s) argumment,
you can
c specify a space-separaated list of onne or more filles that you wishes
w to incllude
in yo
our JAR file.

WA
AR Packagiing
WAR
R (Web Archive) is used too package weeb applicationns. You can deeploy on any
Servlet/JSP contaainer. It may contain
c JSP, Servlet, XML L, images, HTTML pages, CSS
C
files and other reesources.WAR R package co ombines all the
t files into a single uniit. It
takess a smaller amount
a of timme while traansferring file from cliennt to server. The
extennsion of WAR R files is .warr needs a servver to executee a WAR file..
The following
f secctions describbe to you how
w to create, depploy and extrract WAR filee.

Creeate WAR file


f
You can create war file using jar j tool of JD
DK or IDEs. YYou can use -c option of jaar to
creatte the war fille. For creatiing war file, you can go inside the prroject applicaation
direcctory (outside the WEB-IN NF folder), theen write comm
mand like the following:
jar -cvf prrojectname.w
war *

Where -c option is used to crreate file, -v to generate the verbose output and -f - to
speciify the archiv T * (asterissk) symbol indicates that all
ve file name. The a the files off this
direcctory (includinng sub directoory).
The following
f figuure-11 is dispplayed creatio
on process of WAR file:

Figure 7: Command
C proompt showing creation proccess of WAR file
f

ploy the WA
Dep AR file
You can deploy war
w file by placing the waar file in a sppecific folderr of the serveer. If

Figu
ure 7: UML cllass diagram for
f Singleton Design
D Pattern
n Example

17
Introoduction to J2E
EE
Archhitecture and Design
D
you are usiing the tomcat server andd want to deeploy this file manually, go to the
Patteern ‘webapps’ directory
d of aapache tomcaat and paste tthe war file. The
T server will
w extract
the war file internally. Now, you are able
a to access the web project through a browser.
• Supposse, you are ddeploying projject.war file. First go to tomcat
t webappps folder
and passte it.
• Go to tomcat->bin
t f
folder and starrt tomcat by cclicking startuup.bat file
• Now, you
y can accesss your appliication from tthe browser. Open the broowser and
write inn the address bar as localho
ost:port/projeectname eg. lo
ocalhost:80800/project
Extract war
w file man
nually
If you wish to extract thee war file man
nually, then you
y need to useu -x switch of jar tool
of JDK. Thee following coommand is ussed to extractt the war file.

jar -xvf
- projectnaame.war

The following figure-12 shows you ex


xtraction proccess of WAR file:

Figure 12: S
Screen showin
ng extraction process
p of WA
AR file

The figure-13 shows youu the file struucture after extraction


e of WAR file. Now,
N you
have learned about how to create, deeploy and exttract WAR fiiles. The nextt unit will
w to create serrvlet and deplloy in Tomcaat.
tell you how

Figure 13:: File structurre after extraction process of


o WAR file

18
Web Application
☞ Check Your Progress 3 Development using J2EE

1. What is the difference between JAR and WAR files?

2. Describe the process of creation, deployment and extraction of WAR files.

1.6 SUMMARY

This unit focussed on the J2EE, Architecture and Design Patterns. You have learned
about the J2EE and its architecture. By the services of Java 2 Enterprise Edition, you
can develop large scale, component based, distributed, multi-tier applications. J2EE
provides many APIs that can be used to build applications. This unit also covered 23
well-known design patterns which are categorized into three groups such as
Creational, Structural and Behavioral. The design pattern has given you prior
developed descriptions or template as solutions to commonly occurring problems in
programming language. Design patterns are the best solutions that are tested, verified
prototypes that can speed up your software development process. You have learned
about the MVC, Singleton, Factory and Repository design patterns with examples.
The MVC pattern described three layers such as Model, View and Controller. These
three layers have separate functions like Model represent data, View presents data to
user and Controller accepts the request from the user performs interactions on the data
model objects and send it back to the view layer. The repository design pattern is used
in data-centric applications. The repository design pattern provides a way to hide the
internal implementation of how data persistence happens, and it empowers you to
replace your data source without changing your business logic.
The singleton pattern deals with the creation of an object and is used to create only
one instance of a class and all other classes of the application can use this instance. A
Factory Design Pattern or Factory Method Pattern deals with creating an object and
defines an interface or abstract class for creating an object, but subclasses are
responsible for creating the instance of the class. At the end of this unit, you have
learned about how java application can be built as a war file and their deployment in
tomcat.

19
Introduction to J2EE
Architecture and Design
Pattern 1.7 SOLUTIONS/ANSWERS TO CHECK YOUR
PROGRESS
Check your Progress 1
1) Web Server is server software that handles HTTP requests and responses to
deliver web pages or web content to clients (i.e. web browser) using HTTP
protocol. Web server creates an execution infrastructure for the server
technologies. An example of web server is Apache HTTP Server. A compatible
web server with a servlet container is always necessary for deployment and
running the JSPs/Servlets.
Web Container is the web server component that handles Servlets, Java Server
Pages (JSP) files, and other Web-tier components. Web container is also called as
Servlet Container or Servlet Engine. It is the responsibility of Web container to
map a URL to a particular servlet and ensure that the URL requester has the
correct access rights. It means that it provides the run time environment to web
applications.
The most common web containers are Glassfish, Eclipse, JBOSS, Apache
Tomcat, Websphere and Web Logic.

2) J2EE is used to develop and deploy multi-tier web-based enterprise applications


using a series of protocols and application programming interfaces (APIs). J2EE
contains many APIs such Java Servlets, Java Server Pages (JSP), Enterprise
JavaBeans (EJB), Java Database Connectivity (JDBC), Java Message Service
(JMS), Java Naming and Directory Interface (JNDI) and so on. The J2EE
platform consist of set of services, application programming interfaces (APIs),
and protocols.
A J2EE application comprises four components or tiers such as Presentation,
Application, Business and Resource adapter components. The presentation
component is the client side component which is visible to the client and runs on
the client’s server. The Application component is a web side layer that runs on
the J2EE server. The business component is the business layer which includes
server-side business logic such as JavaBeans, and it also runs on the J2EE server.
The resource adaptor component includes enterprise information system.
J2EE contains several API technologies such Java Servlets, Java Server Pages
(JSP), Enterprise Java Beans (EJB), Java Database Connectivity (JDBC), Java
Message Service (JMS), Java Transaction API (JTA), Java Naming and
Directory Interface (JNDI), JDBC data access API and so on. The J2EE platform
is a set of services, application programming interfaces (APIs) and protocols.
3) A module in J2EE is a group of one or more components of the same container
type and one component deployment descriptor of the same type. There are four
different modules used in J2EE: application client module, web, EJB, and
resource adapter module. The Application Client module is bundled as a JAR file
which contains class files and client deployment descriptor (web.xml) file. The
WEB module is bundled as a JAR file that comprises class files (servlets), web
deployment descriptor file, JSP pages, images, and HTML files. The Enterprise
Java Beans (EJB) module is wrapped as a JAR file, collections of class files (ejb)
and EJB deployment descriptor. The fourth module is Resource Adapter which is
packaged as a JAR file consisting of classes, a resource adapter deployment
descriptor, Java interfaces and native libraries.

20
Web Application
Check your Progress 2 Development using J2EE
1) Design patterns are the best solutions that are tested, verified developed
prototypes that can speed up your development process. When you may face
problems during software development, the design patterns give you
explanations for those problems. Experienced developers have developed
these explanations to offer the finest solutions to the problems. It is also
beneficial for inexperienced software developers to learn software design in a
simpler manner.
The name of the design patterns used in JDK core libraries are Decorator
pattern (BufferedInputStream can decorate other streams such as
FilterInputStream), Singleton pattern (which is used by Runtime, Calendar
classes), Factory pattern (used by Wrapper class like Integer.valueOf) and
Observer pattern (used by event handling frameworks like swing).
2) The singleton pattern is a simplest software design pattern amongst the 23
well-known "Gang of Four" design patterns. It comes under the creational
design pattern category which deals with the creation of an object. Singleton
design pattern is used to create only one instance of a class and all other
classes of the application can use this instance. This type of pattern is mostly
used in database connection and multi-threaded applications.
The name of singleton class in JDK is java.lang.Runtime. The implementation
of Singleton design pattern is as under:

public final class Singleton


{
//A singleton class should have public visibility
//static instance of class globally accessible
private static final Singleton instance = new Singleton();
private Singleton()
{
/* private constructor, so that class cannot be instantiated from outside
this class */
}
public static Singleton getInstance()
{
/*declaration of method as public static, so that instance can be used
by other classes */
return instance;
}
}

You can create a clone of a singleton object. Java provide clone() method of
Object class for cloning. This method is protected method. In java, by default,
every class extends Object class, the object of any class, including Singleton
class can call clone() method. If you want to create a clone of a singleton
object, then class must be implemented by java.lang.Cloneable interface.
You can use throw exception within the body of clone() method to prevent
cloning of a singleton object.
3) A Factory Design Pattern or Factory Method Pattern is mostly used design
pattern in java. It is a creational design pattern which deals with the creation
of an object. As per the GOF, this pattern defines an interface or abstract class
for creating an object, but subclasses are responsible for creating the class's
instance. In other words, this pattern is used to create objects where object
creation logic is hidden to the client and refers to newly created objects using
21
Introduction to J2EE
Architecture and Design
a common interface. This design pattern is also known as ‘Virtual
Pattern Constructor’. The advantage of Factory Pattern is that it allows the sub-
classes to choose the type of objects they create.

Check Your Progress 3


1) The JAR (Java Archive) is a package file format. The file extension of JAR
files is .jar and may contain libraries, resources and metadata files. Basically,
it is a zipped file containing the compressed versions of .class files, compiled
Java libraries and applications. WAR (Web Archive) is used to package web
applications. You can deploy any Servlet/JSP container. It may contain JSP,
Servlet, XML, images, HTML pages, CSS files and other resources. It
combines all the files into a single unit and takes a smaller amount of time
while transferring file from client to server. The extension of WAR files is
.war and needs a server to execute a WAR file.
2) You can create war file using jar tool of JDK. You can use -c switch of jar to
create the war file. For creating war file, you can go inside the project
application directory (outside the WEB-INF folder) then write command as
jar -cvf projectname.war * on the command prompt. For the deployment of
WAR file, you can place war file in specific folder of server. If you are using
the tomcat server and want to deploy the war file manually, go to the
‘webapps’ directory of apache tomcat and paste the war file. The server will
extract the war file internally. Now, you are able to access the web project
through the browser. If you wish to extract the war file manually then you
need to use -x switch of jar tool of JDK.

1.8 REFERENCES/FURTHER READING

• Kathy Sierra, Bryan Basham, anddd Bert Bates ,“Head First Servlets and
JSP”, O'Reilly Media, Inc., 2008.
• Budi Kurniawan , “Java for the Web with Servlets, JSP, and EJB: A
Developer's Guide to J2EE Solutions: A Developer's Guide to Scalable
Solutions” ,Techmedia , 2002.
• https://www.oracle.com/java/technologies/appmodel.html
• https://docs.oracle.com/javase/8/docs/technotes/guides/javaws/
• https://docs.oracle.com/cd/B10018_07/migrate.902/a95110/overview.htm
• Design Patterns: Elements of Reusable Object-Oriented Software – Erich
Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
• https://docs.oracle.com/javase/tutorial/deployment/jar/build.html
• https://introcs.cs.princeton.edu/java/85application/jar/jar.html

22
UNIT 2 BASICS OF SERVLET
Structure

2.0 Introduction
2.1 Objective
2.2 Introduction of Servlets
2.3 HTTP Protocol and Http Methods
2.3.1 HTTP Protocol Overview
2.3.2 HTTP Request
2.3.3 HTTP Response
2.3.4 HTTP Method
2.4 Servlet Architecture
2.5 Servlet Life Cycle
2.5.1 The init Method
2.5.2 The service Method
2.5.3 The destroy Method
2.6 Creating a Servlet
2.7 Running and Deployment of Servlet
2.8 Summary
2.9 Solutions/Answers
2.10 Further Readings

2.0 INTRODUCTION
In this new era of technology, the Internet is just like a bottomless ocean where you
will find anything from a website to a web application. As you know very well, a
website is a collection of related web pages that contains static (HTML pages, images,
graphics) as well as dynamic files, whereas a Web application is a piece of software
with dynamic functionality on the server. Google, Facebook, Twitter are some popular
examples of web applications.
Today, you are aware of the need of creating dynamic web pages. For this, you can
use server-side programming languages such as Java Servlets, Java Server Pages,
ASP.Net and PHP etc. This Unit and the next unit will provide you with more details
on Java Servlets. Next th Java Server Pages will be discussed in unit 4 of this block.
You are also aware of core Java concepts and compiling and running of java classes.
In this unit, you will learn the basics of Servlet, Servlet-API and life-cycle of the
servlet. Servlets are java classes that run on the Java-enabled web server and are
widely used for web processing as well as are capable of handling complex requests
obtained from the web server. Servlets need some protocol and methods for
communicating with the server. This unit will also cover HTTP protocol and methods
and guides you on how to write, run and deploy a servlet.

2.1 OBJECTIVES

After completion of this unit, you will be able to:

• Describe basics of Servlet,


• Difference between HTTP request and HTTP response,
• Use of HTTP methods,
1
Web Application
Development using J2EE
• Use different classes and interface included in Servlet API and some of its
methods,
• Describe how servlet container maintains the Servlet Life Cycle, and
• Write simple servlet for the web applications.

2.2 INTRODUCTION OF SERVLETS


You all are aware of java classes. A servlet is also a java class that is descended from
the class javax.servlet.http.HttpServlet. So, servlet is a java class, but not all java
classes are servlets. In this section, you will learn more about Java Servlet.

Java Servlets are small, platform-independent java programs that run on the
Java-enabled web server. It extends from a Java class or rather interface and
requires you to implement certain methods so that web container or servlet
container (Tomcat, etc.) is able to send execution to your servlet. Basically it creates
a class that extends either GenericServlet or HttpServlet, overriding the appropriate
methods, so it handles requests.

Web containers job is to handle the request of the web server; process these requests,
produce the response and send it back to the web server. Servlets are executed within
the address space of a Web Server.
As Servlet technology is based on java language, it is robust and scalable . It is used
to create a program for developing web applications. These programs reside on server
side. Java Servlet is the foundation technology for Java server-side programming. JSP
(Java Server Pages), JSF (Java Server Faces), Struts, Spring, Hibernate and others are
extensions of the servlet technology.
Servlet extends the capabilities of web servers that host applications accessed by
means of a request-response programming model. For developing web applications,
Java Servlet technology defines HTTP-specific servlet classes. A HTTP Servlet runs
under the HTTP protocol. This protocol is an asymmetrical request-response protocol
where the client sends a request message to the server, and the server returns a
response for requested data. You will get more details on HTTP protocol and methods
in the next section of this unit.
There are many interfaces and classes in the Servlet API for creating servlets, such as
GenericServlet, HttpServlet, ServletRequest, ServletResponse, and Servlet, which will
be discussed in section 2.4 of this unit.
A java servlet program has a life cycle that defines:
i. how the servlet is loaded and initiated,
ii. how a Servlet receives and responds to requests, and
iii. how it is taken out of service.
The Servlet life cycle will be discussed in detail in section 2.5 of this unit.

2.3 HTTP PROTOCOL AND HTTP METHODS

In the previous section, you have been explained about the servlets which are a server-
side scripting language. It follows client-server architecture in which client (browser)
sends data to server and it requires some protocol (set of rules) for communication
between the two. In this section, you will learn some of the basic protocol and
methods that make this communication possible.

2
Hypeertext Transffer Protocol (HTTP) is specially
s meaant to comm municate betwween Basics off Servlet
Clien
nt and Serveer using Webb (or Interneet). The HTT TP is a stateeless protocool, it
supports only onee request per connection.
c Itt can be furthher simplified as; HTTP cllient
conn
nects to the server to send d one requestt only and thhen it it is disconnected. This
T
mechhanism facilittates connectiing more userrs to a given sserver over a period
p of timee.
To ruun web appliications, web browsers com mmunicate wwith the web servers usingg the
HTT TP. When you u type any UR RL in the browser, the broowser sends ana HTTP Reqquest
to the server. Thee server receivves the request and sends bback the requuested data too the
browwser. In the foollowing sectiions, you willl learn more about the HTTTP Protocol and
HTT TP methods.
2.3.11 HTTP Protocol
P Overview
HTT TP Protocol is a network prrotocol used for
f transferrinng files on thee Internet . HT
TTP
is thee primary prootocol used for
f most web applications on the Interrnet. Whetherr the
appliication are wrritten in Java,, ASP.Net or PHP; all webb applicationss use HTTP. This
T
protoocol is the fouundation of any
a data exchhange on the Web. HTTP P works basedd on
requeest-response model betw ween a client and the servver. An HTT TP client sendds a
requeest message to a HTTP server. The server returnns a responsee message to the
nt. As HTTP is a statelesss protocol, thee current reqquest does nott know what has
clien
beenn done in the previous reqquests. For communicatio
c on between th he different web
w
pages, you need to establish sessions
s or create
c cookiess. These willl be discussedd in
Unit 3 of this blocck.

HTT TP is also called connectionnless protocool, which meaans that the client establishhes a
conn nection with the server before
b sendinng a request,, and the seerver sends bback
respoonse to the client
c over this connectionn only. Whenn a response is delivered, the
conn nection between the client and the serveer is destroyeed. If the samme client wantts to
conn nect to same server
s again, the
t client shoould establishh a new conneection. So, HT TTP
is deesigned as coonnectionlesss for the aboove said reason; the serveer should shhare
resouurces equally to the clientss who exist all over the woorld. If one cllient is connected
all th
he time with the server thenn the server cannot
c allocatte the time to other clients.

HTT TP was initiaally developeed by Tim Berners-Lee


B a
and his team
m in early 19990.
HTT TP/1.0 definess the basic protocol
p with some methoods such as GET, G POST and
HEA AD, and this version
v did not
n support innformational status codes.. The HTTP P/1.1
defin
nes seven HTTP
H methodds GET, PO OST, HEAD, OPTIONS, TRACE, PUT, P
DEL LETE, and also add many headers
h and faacilities to thee original HTTP/1.0.
Subssequently, in HTTP/2.0 th here has beenn a major reevision of thee HTTP netw work
proto
ocol. HTTP/22.0 is the firsst new versionn of HTTP since HTTP 1.1. HTTP/3 iss the
third
d major versio
on of the HT TTP used to exchange
e infformation on the World W Wide
Web.When a webb page link is clicked on a web page too look for a seearch or subm mit a
form
m from your browser,
b the browser translates your reequested URL L into a requ
uest
messsage accordinng to the speciified protocoll and sends it to the HTTP server. The

Figure 1: Process
P of com
mmunication between
b Web Client and Web
W Server

3
Web Application
Development using J2EE
HTTP Server (Web Server) interprets the request message received, maps the request
into a program kept in the server, executes the program and returns you an appropriate
response message. in the form of the resource has been requested or as an error
message. In figure 1 this request and response process is displayed.

HTTP messages manage the information exchange between a server and a client.
There are two types of HTTP messages: HTTP requests sent by the client to the
server, and HTTP responses, the answer from the server. Both the messages are
described below:
2.3.2 HTTP Requests
Whenever a client sends a message to a server it is an HTTP request. As you have
learned until now, when the client sends a request to the server, the server returns a
response to the client. Web Client sends a request specifying one of the seven HTTP
request methods (you can read more about these methods in the next section), the
location of the resource to be invoked, protocol version, a set of optional headers and
an optional message body.
In a simple terminology, as a client, when you type a URL of the website in the
browser, for example, you want to download your Hall-ticket from the IGNOU
website and open the website by typing the URL as
http://www.ignou.ac.in/studentzone/hallticket.jsp; a request is initiated from your
computer to the web server. This process sets up a connection from your computer to
the host computer where the IGNOU web server is hosted. The domain name from
your URL is converted into a machine-readable state known as an IP address by the
Domain Name System (DNS) server during the connection setup. The rest part of the
URL are path i.e. /studentzone/ and resource file (hallticket.jsp). The client computer,
after knowing the IP address of web server, path, resource file, your request goes to
the web server using HTTP methods such as GET. Some more technical operations
are needed to establish a connection between client and server. A detailed discussion
on this is beyond the scope of this unit.
For the requested IGNOU page, your request may look like the following line: method
name, path, resource name, and protocol version.
GET /studentzone/hallticket.jsp HTTP/1.1

You can also find these details using the following example. The ‘RequestServlet’
example illustrates some of the resources available in the request object. The detailed
running procedure is given in section 2.7 of this unit.
Source Code ‘RequestServlet’ example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class RequestServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

java.util.Date date = new java.util.Date();


out.println("Current Date & Time: " +date.toString());
out.println("<h3>Request Information Example</h3>");
out.println("Method: " + request.getMethod()+"<br>");
4
out.println("R
o Request URI: " + request.geetRequestURRI()+"<br>"); Basics off Servlet
out.println("P
o Protocol: " + request.getPro
r otocol()+"<brr>");
out.println("P
o PathInfo: " + request.getPat
r thInfo()+"<brr>");
out.println("R
o Remote Addreess: " + request.getRemoteAddr());
}
//d
doGet
}

The key
k methods included in thhe above prog
gram are desccribed in the table below:
Table 1: Some HtttpServletReqquest Method
ds
Meth
hod Description
n
getM
Method() Returns thee HTTP requeest method
getR
RequestURI() Returns thee complete reequested URI
getPrrotocol() Returns thee protocol useed by the brow
wser
getPaathInfo() only returnns the path paassed to the seervlet
getR
RemoteAddr() Returns thee IP address of
o the client

The output
o of thiss Servlet shouuld look like thhis (figure-2)):

Figure 2: Ou
utput Screen for
f 'RequestSeervlet’ examplle

As you
y know thaat the request message shhows the metthod, Requesst URI, Protoocol,
PathIInfo and the remote
r address of client machine.
m Heree, the method is GET, Reqquest
URI is the path ofo your ‘webaapps’ and thee Protocol verrsion is HTT TP 1.1 (it mayy be
different on your server). This servlet is runnning on the llocal machinee. So, the adddress
is 12
27.0.0.1. Thesse details depeend on your web
w server.
You can also cheeck your logss under the local
l web serrver. For exaample, the abbove
progrram shows thhe following line in the log
gs folder undeer the Tomcat Server:

127.0
0.0.1 - - [14/S
Sep/2020:11:2
22:20 +0530] "GET /ex/seervlet/RequesttServlet HTT
TP/1.1"

2.3.33 HTTP Response


R

Oncee a server recceives a requeest, it interpreets the requesst message an


nd responds with
w
an HTTP
H response message. The
T server sennds back a ressponse to the client containning
the version
v of HT TTP we are using, a respponse or statuus code, a description
d off the
respo
onse code, a set
s of optionaal headers, and d an optional message boddy.
HTTTP response sttatus codes iss used to indiicate whetherr a specific HTTP
H request has
been
n successfully completed orr not. Responnses are groupped in five claasses:
5
Web Application
Development using J2EE
Table 1: HTTP Response Classes

S.No. Status Code Description

1 Informational responses Request has been received and the process is


(100–199) continuing.
2 Successful responses Action was successfully received,
(200–299) understood, and accepted.
3 Redirects (300–399) Action must be taken to complete the request.

4 Client errors (400–499) Request contains incorrect syntax or cannot


be fulfilled - It means the server failed to
fulfil an apparently valid request.
5 Server errors (500–599) Server failed to fulfil a valid request.

It is not necessary for HTTP applications to understand the meaning of all registered
status codes. More details of the status code can be explored at: https://www.w3.org

For example, if the response line of HTTP applications is:

HTTP/1.1 200 222

Then it can be interpreted as: HTTP/1.1 is the HTTP version; The HTTP Status 200
indicates the successful processing of the request on the server.
2.3.4 HTTP Method
In the previous section, you read the term method in the context of the request
message. In this section, you will learn some frequently used methods for getting
response from the server. You are already aware of the HTTP request which is a
message that a client sends to a server. To send these requests, clients can use various
HTTP methods. These request methods are case-sensitive and should always be noted
in upper case. There are various HTTP request methods such as GET, POST, PUT,
HEAD, DELETE, OPTIONS and PATCH and each one is assigned a specific
purpose.
GET Method
GET method is used to retrieve requested data from a specified resource in the server.
GET is one of the most popular and commonly used HTTP request methods. GET
request is only used to request data (not modify). It means that the GET method is
used to retrieve information and does not make any change in the server. These types
of methods are called ‘safe’ methods.
The following simple HTML programme will demonstrate you how the ‘GET’
method will work:
<html><body>
<form name ="InfoForm" action="Info.jsp" method="GET">
<div> <label >Name</label> <input name="name1" value=""> </div>
<div> <label >Course</label> <input name="course" value=""> </div>
<div> <input type="Submit"> </div>
</form>
</body>
<html>

6
The above prograamme consistts of two input boxes i.e. name and coourse. When you Basics off Servlet
run the
t above proogram by usiing the proceedure definedd in the sectio
on 2.7, the reesult
screeen will display
y as shown inn the figure 3..

Figu
ure 3: Simple Form
F for 'GE
ET' method Exxample

When you put so ome values in


i the input boxes i.e. naame & coursse, and press the
‘Submit’ button as
a displayedd in Figure 3,
3 then actionn control will transfer on the
following HTML code line in the
t form:

m name ="InffoForm" actioon="Info.jsp" method="GE


<form ET">

So, action
a will bee taken by th he resource file:Info.jsp
f a the methood will be G
and GET.
Heree, GET methood is used to o retrieve vallues from thee server. Notte that the quuery
stringg (name/valu
ue pairs) is seent in the UR RL of a GET request. Afteer submittingg the
formm, the name/vaalue is visiblee as like the foollowing:

Heree, ‘localhost:8
8080’ indicatees that you arre referring too the local web
w server on this
machhine at a 80800 port numberr. The web paage uses the ppath /ex/JSP of o the web seerver
and accesses
a the resource
r file ‘Info.jsp’
‘ and
d after the resoource file namme, there is a text
?namme1=Poonam& &course=MC CA which indiicates passingg additional innformation too the
serveer in the form
m of the paraameter. In thhis case, name1 is defined d as the namee of
‘Namme’ input boxx (<input nam me="name1" >) and valuue of this boxx is ‘Poonam’’. In
the similar
s manneer, course (<iinput name=""course" >) is i the name of o ‘Course’ innput
box and
a value of this box is MCA.
M This example shows how the GET T method woorks.
You can use this type of queryy string to finnd the data froom the databaase or simplyy get
the parameter
p valuue to display on the web page.
p In the abbove examplee, server mayy use
the operation
o whicch is defined in the ‘Info.jssp’ file to dispplay data.
HEA
AD Method
d
The HEAD
H t GET method but doesn’t have a messsage-body inn the
methood is similar to
onse. In a weeb application, the serverr replies withh a response line and headers
respo
section only.
POS
ST Method
d
Anotther popular HTTP
H requesst method is POST.
P In webb communicaation, this metthod
is ussed to send data
d to a serrver to createe or update a resource. The informaation
submmitted using POST
P request method to thhe server is archived in thee request boddy of
the HTTP
H requestt. The inform
mation /data sent
s through tthe POST meethod will noot be
visib
ble in the URL
L as parameteers are not sennt along with the URL.
For example,
e youu can use thee same form defined in G
GET method, only changee the
namee of method as POST. So,S form conntains the following HTMML code line for
<form
m> element:
m name ="InfooForm" actionn="Info.jsp" m
<form method="POST">

7
Web Application When you submit the form by pressing ‘Submit’ button, information must be sent to
Development using J2EE
the server. In this example, parameters like name and course will be put inside the
request body. Like the GET method, parameter and their values are not visible in the
URL.
Both the Get and Post method of HTTP protocol is frequently used methods in web
programming. Using a GET request, information is sent to the server via URL
parameters. On the other hand with a POST method , some additional data is also
supplied from the client to the server in the message body of the HTTP request. An
advantage of the POST over the GET request is that it is more secure - it cannot be
bookmarked, and it is difficult to hack. Also it is not stored in the browser history.
This method is, therefore, more commonly used when sensitive information is
involved.
There are several other request methods. You may refer to more of these methods
from the ’Further Readings’ section at the end of this unit.
HTTP and Java
Servlets can be seen as java components that can respond to an HTTP request. There
are methods in Java Servlets corresponding to each of the HTTP methods. The seven
HTTP methods map on to seven servlet methods of the same name with a “do” in
front of the method. For example, GET maps on to doGet(). Mostly you can use either
GET or POST method while developing a web page.

☞ Check Your Progress 1

1. What is a Servlet? Define the workflow of a servlet,


----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------
2. What are the basic Features of HTTP?
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------
3. What is HTTP Message? What are request and response in the context of
HTTP?
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------

4. How is GET method different to POST method?


----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------

8
Basics off Servlet
2.4 SERV
VLET AR
RCHITE
ECTURE

Servlets are the Jaava program that runs on the Java-enabbled web servver. The cliennt or
web browser sendds the HTTP request to thhe web serverr. The web seerver receivess the
requeest and passees the requesst to the servlet container and subsequuently the serrvlet
contaainer forwardds this requestt to the corressponding servvlet. The servvlet processess the
requeest and generrates the respponse in the form of outpput. This proccess may reqquire
comm munication too a database and may alsoo invoke a web w service, or o computingg the
respo
onse directly. After processsing, the serv vlet builds thee response obbject and sendds it
back
k to the Web Container.
C

Fiigure 4: Servleet Architecturre

The servlet contaiiner sends thee response baack to the webb server; the web
w server seends
the response
r backk to the browser and thee browser diisplays it on the screen. The
diagrram shows the execution ofo servlet in Figure 4.
You need to use Servlet
S API tot create servvlets. These APIs
A allow deeveloper to build
b
progrrams that cann run with a web
w server. Th he Servlet AP
PIs (Applicatiion Programm ming
Interrface) containns two packkages: javax.sservlet and jjavax.servlet.http. These two
packkages make up u the servlett architecturee. The javax..servlet and javax.servlet.
j .http
packkages provide interfaces an nd classes for writing servlets. The javaxx.servlet packkage
contaains generic interfaces
i andd classes thatt are implemeented and exttended by alll the
servllet. The javaxx.servlet.http package
p contaains a number of classes annd interfaces that
are used
u to create HTTP protoccol-specific Servlets.
S
Gen
nericServleet Class
The javax.servlett package prrovides an abstract
a classs called Gen nericServlet that
implements Servllet, ServletConfig and javva.io.Serializzable interfacces. A servlet can
direcctly extend itt. The subclass of GenericcServlet is H
HttpServlet. Itt can handle any
type of request. YouY may creeate a genericc servlet by inheriting the GenericSerrvlet
classs and implemmenting the seervice( ) methhod. The proototype of serrvice() methood is
definned as followss:

publiic abstract vooid service(SeervletRequest req, ServletR


Response res)
throw
ws ServletExcception, IOEx xception;
The two objects of service() method are ServletRequeest and ServlletResponse. The
ServletRequest ob
bject holds thhe informatioon that is beinng sent to the servlet andd the
ServletResponse object
o is to assist
a a servleet in sending a response back to the cliient.
9
Web Application The javax.servlet.ServletException is a general exception that a Servlet can throw.
Development using J2EE
IOException is a checked exception and is thrown when there is any input/output file
operation issues while application is performing certain tasks accessing the files.

Servlet Interface
All servlets must implement the Servlet interface either directly or indirectly. Java
servlets class does not have a main() method, so all servlets must implement the
javax.servlet.Servlet interface. It defines five methods, including three life-cycle
methods. You may read the life-cycle methods such as init(), service() and destroy() in
the subsequent section 2.5 and other two methods are getServletConfig() and
getServletInfo().
ServletConfig Interface
An object of ServletConfig is created by the servlet container for each servlet. This
object is used to pass configuration related information to a servlet during start up.
The getServletConfig() method is used to return the object of ServletConfig. It
contains name/value pairs of initialization parameters for the servlet. It defines four
methods such as getServletContext(), getServletName(), getInitParameter() and
getInitParameterNames() for accessing this information.
Serializable interface
The Java Serializable interface (java.io.Serializable) is a marker interface. It means
that it contains no methods. Therefore, a class implementing Serializable does not
have to implement any specific methods.
HttpServlet Class
The javax.servlet.http package contains a number of classes and interfaces that are
used to create HTTP protocol-specific Servlets. The abstract class HttpServlet is a
base class for user defined HTTP Servlets which provide methods. The basic methods
such as doGet and doPost are for handling HTTP-specific services. When you are
developing your own servlets then you can use HttpServlet class which is extended
from GenericServlet.
public abstract class HttpServlet
Unlike with GenericServlet, when you extend HttpServlet, you can skip implement
ing the service() method. The HttpServlet class has already implemented the service()
method. The following are the prototype of the service() method:

protected void service(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
When the HttpServlet.service() method is invoked, it first reads the method type
stored in the request, and on that basis it determines the method to be invoked. For
example if the method type is GET, it will call doGet() method, and if the method
type is POST, it will call doPost() method. These methods have the same parameter as
the service() method.
There are many interfaces in javax.servlet.http package but the three important
interfaces HttpServletRequest, HttpServletResponse and HttpSession are described
below:
Interface HttpServletRequest
The HttpServletRequest interface captures the functionality for a request object that is
passed to a HTTP servlet. It provides access to an input stream and allows the servlet

10
to read data from the client. The HttpServletRequest interface extends the Basics of Servlet
ServletRequest interface.

public interface HttpServletRequest extends ServletRequest

The servlet container creates an HttpServletRequest object and passes it as an


argument to the servlet's service methods (doGet, doPost etc). The HttpServletRequest
interface has many methods. Some of the commonly used methods of
HttpServletRequest are:

1. getParameter()
It returns the value associated with a parameter sent to the servlet as a part of a
GET or POST request. The name argument represents the parameter name.

public String getParameter(String name)


2. getQueryString()
It returns the query string that is contained in the request URL if any. This
method returns null if the URL does not have a query string. A query string is
defined as any information following a ? character in the URL.

public String getQueryString()

3. getCookies()
The getCookies() method returns an array of Cookie objects found in the client
request. This method does not take any parameters and throws no exceptions.
Cookies are used to uniquely identify clients to servlet. In case of no cookies in
the request, an empty array is returned.

public Cookie[] getCookies()

4. getHeader()
It returns the value of the specified request header as a String. In case if the
request did not include a header of the specified name, this method will return
null. If there are multiple headers with the same name, this method returns the
first header in the request. The header name is case insensitive.

public String getHeader(String name)

5. getMethod
It returns the name of the HTTP method used to make the request. Typical return
values are ‘GET’, ‘POST’, or ‘PUT’

public String getMethod()

6. getSession()
It returns the current session associated with the request or if the request does not
have a session, creates one.

11
Web Application public HttpSession getSession(boolean create)
Development using J2EE
public HttpSession getSession()

Interface HttpServletResponse

The HttpServletResponse extends the ServletResponse interface to provide HTTP


specific functionality while sending a response to the client. It provides access to an
output stream and allows the servlet to send data to the client.
public interface HttpServletResponse extends ServletResponse

This interface has many methods; some are described in the following sections.
1. getWriter() Method
It obtains a character-based output stream that enables text data to be sent to the
client.

public PrintWriter getWriter()

2. addCookie() Method
This method is used to add a Cookie to the HttpServletResponse object. It returns
no value and throws no exception. This method can be called many times to set
more than one cookie.

public void addCookie(Cookie cookie)


3. addHeader() Method
This method is used to add a response header with the given name and value.

public void addHeader(String name, String value)

4. getOutputStream() Method
It obtains a byte-based output stream that enables binary data to be sent to the
client.

public ServletOutputStream getOutputStream()

5. sendError() Method
This method sends an error to the client in the response object. The error consists
of only the ‘int’ status code and returns no value.

public void sendError(int statusCode) throws IOException

The following sendError() method sends an error to the client in the response
object. The error consists of an ‘int’ status code and a String message. It returns
no value.
public void sendError(int statusCode, String message) throws IOException

6. sendRedirect() Method
This method redirects the client to the passed-in URL, which must be an absolute
URL. It returns no value.
12
public void sendRedirect(String uri) throws IOException Basics of Servlet

Note- You can reference the Servlet-API from your Tomcat installation at
https://tomcat.apache.org/tomcat-9.0-doc/servletapi/index.html

Interface HttpSession
This is an important interface used to identify a user across more than one page
request or visits to a website and stores information about that user. Servlet Container
uses this interface for the creation of session between HTTP client and HTTP server.
Using HttpSession, you can maintain state (data) between transactions. The
HttpServletRequest interface provides two methods such as getSession() and
getSession(boolean create) to get the object of HttpSession. Both the methods
getSession() and getSession(boolean create) are explained in the “HttpServletRequest
interface’ section of this Unit. The signature of this interface is as under:
public interface HttpSession

The commonly used methods of HttpSession interface are defined below. You can
find an example of these methods in the next unit of this course.

1. getId() Method
The getId() method returns a string containing a unique identifier assigned to
the current HttpSession.
public String getId()

2. getCreationTime() Method
The getCreationTime() method returns the time in which the session was
created.
public long getCreationTime()

3. getLastAccessedTime() Method
This method returns the last time the client sent a request associated with this
session object.
public long getLastAccessedTime()

4. getAttribute() Method
This method is used to return the value of given parameter from the session.
public Object getAttribute(String name)

5. setAttribute() Method
This method is used to set the attribute in session.

public void setAttribute(String name, String value)

6. invalidate() Method
This method is used to destroy the session.
public void invalidate()

For example, session.invalidate();


13
Web Application
Development using J2EE
Note: You can find more methods of HttpSession interface in the following link:
https://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html

☞ Check Your Progress 2


1. What is Servlet interface and what is the use of it?
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------
2. Write the difference between GenericServlet and HTTPServlet?
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------
3. What is ServletConfig?
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------
4. What is ServletContext?
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------

2.5 SERVLET LIFE CYCLE


A Java Servlet has a life cycle that defines the steps in the whole processing of a
servlet. This includes:
1. The Servlet loading and initialization,
2.How servlet receives and responds to requests, and
3.How a servlet is taken out of service.
The servlet life cycle is very simple object oriented design. A servlet life cycle
includes the entire process from its creation to the destruction. A servlet is first
initialized and then it serves to zero or more service requests until the service ends
and shuts down. Servlet is loaded only once, and it stays resident in the memory till it
is servicing a request. Servlet container manages the entire life cycle of a Servlet,
using the javax.servlet.Servlet interface. Every servlet you write must implement the
javax.servlet.Servlet interface either directly or indirectly. The Servlet interface
defines all the methods of servlet life cycle such as init( ), service( ) and destroy( ).
Now let us discuss the life cycle methods in detail.
2.5.1 The init() Method
The init() method is where the servlet’s life cycle begins. The servlet container calls
this method after the servlet class has been instantiated. This method is called exactly
once by the servlet container to indicate to the servlet that the servlet is being placed
into service. In this method, servlet creates and initializes the resources, including the
data members that it will be using while handling requests.

The signature of this method is defined as follows:


14
public voiid init (ServleetConfig conffig) throws SeervletException Basics off Servlet

This method takees a ServletC Config object as a parametter. The ServvletConfig obbject
contaains the servllet's configurration and iniitialization paarameters. Th
his init() metthod
can also throw a ServletExcception. The ServletException is the most imporrtant
excepption in servvlet programm ming. If the servlet cannnot initialize the resourcee to
hand
dle the requestt, then the meethod will throow an executtion.

Figure 5: Seervlet life cyclee

2.5.22 The service() Meth


hod
The service() metthod is used to handle inncoming requests and geneerate a respoonse.
This method is caalled by the servlet
s contaiiner and cannnot start servicing the reqquest
until the servlet’ss init() methood has been executed. Thhe most com mmon use of this
methhod is in thee HttpServlett class. The HttpServlet class providdes http speccific
methhods such as doGet,
d doPosst, doHead, dooTrace etc. Inn order to gen
nerate a respoonse
you should
s override the doGet or doPost meethods as per your requirem ment.
This method has the
t following signature:

public voiid service(SerrvletRequest req, ServletR


Response res) throws
ServletEx
xception, javaa.io.IOExcepttion

This method impplements a request and responser paraadigm. The servlet contaainer
passees two objeects, ServlettRequest ob bject and ServletRespon nse object. The
ServletRequest object
o contains the clien nt’s request and ServletR Response obbject
contaains the servlet’s response. Both objectts are importaant because thhey enable yoou to
writee code that determines
d hoow the servleet fulfils the client request. The serviice()
methhod may thhrow the ServvletExceptionn and IOExcception whilee processing the
requeest. This methhod throws a ServletExcep ption if any exxception occuurs that interfferes
with the servlet's normal
n operaation and also
o throw a javaa.io.IOExcepttion if an inpuut or
outpuut exception occurs
o during
g the executioon of service()) method.

2.5.33 The desstroy() Metthod


15
Web Application The destroy() method is called only once when all the processing of the servlet is over
Development using J2EE
and it is at the end of its life cycle. When your application is stopped or Servlet
Container shuts down, this method will be called to close down those shared resources
and other clean up required before the servlet is taken out of service. This is the place
where any resources that were created in init() method will be cleared up.

The signature of this method is defined as follows:


public void destroy( )

2.6 CREATING A SERVLET

In this section, we will try to create a basic servlet. This will help you in becoming
familiar with the basic parts of the servlets. Here is a simple servlet program code for
printing a text message such as ‘Welcome to the IGNOU Family!’.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class WelcomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet Testing</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Welcome to the IGNOU Family!!");
out.println("</BODY></HTML>");
}
}

Write the above code in a notepad and save it as WelcomeServlet.java on your PC.
You will find running procedure for the servlet in the next section.

2.7 RUNNING AND DEPLOYMENT OF


SERVLET

In this section, you will find the installation process of Apache’s Tomcat. You can use
it for running and deployment of your Servlets as well as JSP programs. You will
study JSP in Unit 4 of this course. It is the best practice to use IDE for web
development. Here, you can go through the simple steps for running your servlet
and JSP program using Apache Tomcat without any IDE. Apache Tomcat is an
open source web server for testing servlets and JSP programs. You can use Notepad to
write your program. Also, there are some open source Integrated Development
Environment (IDE) for developing J2EE applications. NetBeans IDE supports the
development of all Java application types, including Java SE (including JavaFX), and
J2EE. More about the IDEs you will learn in MCSL-222 course.
The following steps are based on Windows Operating System( Windows XP/8/10):

16
Step 1 - Downloaad and install Java Developpment Kit. Basics off Servlet

Step 2 - Download the latesst version off Tomcat Seerver and innstall it on yyour
machhine.
Step 3 - After succcessful installlation of Javaa and Tomcatt, you can sett the environm ment
variaables by usinng the Enviro onment Variables option.. For this, do d right clickk on
Systeem icon  properties Advanced
 S
System Settinng  environment variabbles.
Noww, click on ‘N New’ button and enter thee variable naame as JAVA A_HOME andd in
variaable value wriite the path off Java installaation directoryy and click onn the ‘ok’ buttton.
The following
f scrreen comes affter the selectiion of the stepp3.

Figure
F 6: Screeen for settingg the environm
ment variable.

In a similar man nner, you caan set the vaariable namee and variablle value for the
following environnment variablee by using steep 3:

variab
ble name variabble value:
classp
path C:\Prrogram Files\AApache Softw ware Foundatiion\apache-
tomcat-7.0.37\lib\sservlet-api.jarr;C:\Program
m Files\Apachee
Softwware Foundatiion\apache-toomcat-7.0.37\\lib\jsp-
api.jaar;C:\Program
m Files\Apachhe Software
Founndation\apachee-tomcat-7.0..37\lib\msbase.jar;C:\Progrram
Files\\Apache Softw ware Foundattion\apache-tomcat-
7.0.37\lib\msutil.jaar;C:\Program
m Files\Apachhe Software
Founndation\apachee-tomcat-7.0..37\lib\mssqlsserver.jar;
Path C:\PrrogramFiles\JJava\jdk1.7.0__25\bin;C:\PrrogramFiles\JJava\j
dk1.77.0_25\lib;
CATA
ALINA_HOM
ME C:\Prrogram Files\AApache Softw ware Foundatiion\apache-
tomcat-7.0.37
JRE_H
HOME C:\Prrogram Files\JJava\jdk1.7.00_25\jre

tep 4 - After instaallation, you will


w find the tomcat
t folder,, which contaains the follow
wing
foldeers:
17
Weeb Application
Devvelopment usingg J2EE
• bin (binary files for Tomcat and a friends),
• connf (configuratiion files),
• lib (library
( JAR files),
• logss (server log files),
f
• tem
mp (temporaryy files),
• webbapps (area Tomcat lookks for web application, it contains JSP files,
Servvlets and otheer content), an nd
• worrk (working space
s for holdding translatedd JSP files).

You can seee these folderss under your web


w applicatiion like the foollowing figurre 7.

Step 5 - Creeate directoryy “ex” under thhe ‘webapps’’ folder as perr the followinng figure 7:

Fiigure 7: Direcctory Structurre for Tomcat

Step 6 – Create
C one ‘seervlets’ folderr for source file and one “JSP” folderr (for JSP
program) unnder ‘ex’ foldder. Also creaate a directoryy ‘WEB-INF’ under the ‘eex’ folder.
Under WEB B-INF folder create a foldeer named ‘claasses’. All yoour java classes used in
your web appplication shoould be placedd in ‘classes’ folder.

Step 7 - Coppy web.xml ffile from ROO


OT directory aand paste into
o “WEB-INF”” folder
under the “eex” folder.

Now, the Jaava and Tomccat installatioon process is completed.

Compiling
g and Runniing the Serv
vlet

Step 8 – Un
nder the ‘servlets’ folder, place
p your serrvlet source fiile. Now, youu will
compile thiss servlet by ussing the following commaand at the Com mmand Promppt:

Program Filess\Apache Sofftware Foundaation\apache-tomcat-


C:\P
7.0..37\webapps\eex\servlets>jaavac Welcom
meServlet.javaa

18
Basics off Servlet

Figuree 8: Command
d Prompt for S
Step 8

Step 9- After succcessful compiilation, ‘WelccomeServlet.cclass’ file will be created.


Placee this file in th
he location: C:
C / Program Files/…/…/w
F webapps/ex/WWeb-INF/classses
foldeer.
Step 10 – In the deployment
d deescriptor (web
b.xml) file unnder the WEB
B-INF folder,
writee the followinng code as thee sub-elementt of <webapp> > element.

<servlet>
vlet-name>W
<serv WelcomeServllet</servlet-naame>
<serv
vlet-class>W
WelcomeServleet</servlet-claass>
</servlet>

<servlet-mmapping>
<servvlet-name>W WelcomeServllet</servlet-naame>
<url--pattern>/servvlet/WelcomeeServlet/*</urrl-pattern>
</servlet-maapping>

Step 11- Start Toomcat Server. In any case, if Tomcat Seerver is not ruunning from yyour
progrram menu or shortcut, runn the ‘startup’ command froom Commandd Prompt likee the
following way:

C:\Prrogram Files\\Apache Softw


ware Foundattion\apache-toomcat-7.0.37\\bin>startup

Step 12- Open neew tab in thee browser or open new wiindow and ty
ype the follow
wing
URLL to execute your
y servlet.

http://locaalhost:8080/ex/servlet/WellcomeServlett

Conggratulations!! Your first seervlet is succeessfully creatted and run at


a Tomcat Serrver.
Noww, you are ablle to create a servlet. Thiss is a simplee servlet exam mple. In the nnext
Unit of this cou urse, you will learn som me other com mplex servletts with databbase
conn
nectivity.

Figu
ure 9: Output Screen for ‘W
WelcomeServleet’ program

19
Weeb Application
Devvelopment usingg J2EE
Steps to Create Servleet Applicatiion in Netbeeans IDE
In the abovee section, youu have createdd your first Seervlet Applicaation but withhout using
any Integratted Developm ment Environnment (IDE). Using IDE, you can eassily create
Servlet Appplications. Heere are steps to create Serrvlet Applicaation in Netbeeans IDE.
Installation process are given
g in the laab manual.
Now, start Netbeans
N and performs thee following steeps:
Select File -> New Project (CTRL+S SHIFT+N) frrom Menu. Inn this window w you can
select Java Web
W categoryy for your new
w Servlet/JSP
P project and select
s the Nexxt button.

Figure 10: New Project Window

In the next window youu can enter project


p namee and location of your chhoice. For
example, yo ou have givven the project name as MyProject and selected a Folder
C:\Projects for location as a select the Next button.
a shown in thhe figure-11 and

Figure 11: Selection off Name and L


Location of Pro
oject

Now a wind dow appears with Server settings, youu can select Finish
F buttonn from the
button Paneel.

The compleete directory structure requ


uired for the Servlet Appllication will be
b created
automatically by the IDE
E.
20
Basics of Servlet

Figure 12: Directory Strucure

Now you are ready to create your web application. To create a Servlet, open Source
Package, right click on default packages -> New -> Servlet. Give a Name to your
Servlet class file and click on the Next button.

Figure 13: Name and Location window for new Servlet

In the next window you can change servlet name and patterns and finaly click on
finish button.

Figure 14: Configure Servlet Deployment Window

21
Web Application Now that Servlet class is ready, you can change the code as per your reqiurement .
Development using J2EE
Once this is completed, edit the index.html file and add the following code in the
index.html. This file is read as the first page of the web application.

<h1>Click here to go <a href="hello" >MyServlet Program</a></h1>

Edit web.xml file. You can see here the specified url-pattern and servlet-name, this
means when hello url is accessed your Servlet file will be executed. If the index.html
is not listed as welcome file in web.xml and then you can add this file.

Figure 15: Web.xml file

Now Run your application, right click on your Project name and select Run. Click on
the link created, to open your Servlet and your first servlet in NetBeans will run. The
output of this servlet is shown in Figure-16.

Figure 16:Output of first Servlet program in NetBeans

☞ Check Your Progress 3

1. Which interface contains Servlet life cycle methods?


----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------
2. Explain servlet life cycle methods.
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------
3. What is the difference between init() and destroy() methods in servlet?

22
---------------------------------------------------------------------------------------------- Basics of Servlet
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------

4. Write a servlet program to display “We are student of SOCIS, IGNOU!!”.


----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------

2.8 SUMMARY

This unit introduced you to the basics of Servlet. Servlet is a Java class that creates
dynamic content. It takes user request which was sent from the web browser, for
processing. Java Servlet is an established technology used for creating dynamic web
applications.
After defining the basics of servlet, the unit described the HTTP protocol and HTTP
methods. HTTP refers to Hyper Text Transfer Protocol. It is a protocol which
governs any data exchange on the Web. HTTP is a client-server protocol i.e. each
request is sent by the client to a server that handles it and provides an answer, called
the response. While communicating with the Server, clients can use various requests
methods. Two of them i.e. GET, and POST are widely used methods that take part in
requesting the data in applications.
This Unit also introduced you two packages i.e. javax.servlet and javax.servlet.http
that make up the servlet architecture. The two main classes GenericServlet and
HttpServlet are defined in Servlet-API. The GenericServlet class provides
implementations for all methods; most of them are blank. You can extend
GenericServlet and override only methods that you need to use. If you are going to
create a web application, then you can extend the HttpServlet class. In the life cycle of
a servlet, you have learned three methods such as init(), service(), and destroy()
methods. At the end of the unit, you are able to write a simple servlet.

2.9 SOLUTIONS/ANSWERS

☞ Check Your Progress 1


1. A servlet is a small Java program that runs on a web server. Servlets are often
run when the user clicks a web link, submits a form or performs some other
type of action on a website. Servlets receive and respond to requests of the
clients/users of web applications. Using servlets, dynamic web pages are
created. It can be seen as a mediator between the incoming HTTP request
from the browser and the database. Servlet is a robust server-side
programming language.
When a web client sends an HTTP request to web server, the webserver
receives the request and passes the request to the servlet container. The servlet
container is responsible for instantiating the servlet or creating a new thread to
handle the request. The servlet container forwards this request to the
corresponding servlet. The servlet processes the request and generates the
response in the form of output. During processing, servlet follows all the
phases of life cycle. When servlet container shuts down, it unloads all the
servlets and calls destroy() method for each initialized servlets.

23
Web Application 2. The Hypertext Transfer Protocol (HTTP) is an application-level protocol for
Development using J2EE
developing distributed applications. This protocol is the foundation for data
communication for the WWW. The basic features of HTTP are as follows:
• HTTP is a request and response protocol.
• HTTP is a media independent protocol.
• HTTP is a stateless protocol.
3. HTTP messages consist of textual information encoded in ASCII format. It is
used to show how data is exchanged between client and server. There are two
types of messages: requests sent by the client for action to the server
and responses or the answer from the server. It is based on client-server
architecture. An HTTP client is a program that establishes a connection to a
server to send one or more HTTP request messages. An HTTP server is a
program that accepts connections to serve HTTP requests send by the clients
and send HTTP response messages to the client.
4. Both GET, and POST method are used for transfer of data from client to
server in HTTP protocol. The main difference between POST and GET
method is that GET carries request parameter appended in URL string while
POST carries request parameter in message body which makes it a more
secure way of transferring data from client to server in HTTP protocol. GET
method can send a limited amount of data to the server, while POST method
can send data in bulk to the server.

☞ Check Your Progress 2

1. Servlet interface is an API for servlets. Every Servlet should either implement
the servlet interface or extends the class which already implements the
interface. javax.servlet.GenericServlet and javax.servlet.http.HttpServlet are
the Servlet classes that implement the Servlet interface; hence, every servlet
should either implement the Servlet interface directly or by extending any of
these classes.
2. GenericServlet is an abstract class that implements Servlet interface while
HTTPServlet abstract class extends the GenericServlet class. GenericServlet
class is a base class for HTTPServlet. GenericServlet does not support any
protocol while HTTPServlet support HTTP and HTTPS protocol.
HTTPServlet can handle cookies and session but GenericServlet cannot
handle them.
3. ServletConfig interface belongs to the package javax.servlet.ServletConfig. It
is used for passing the configuration parameters to the servlet. Each Servlet
has a separate ServletConfig object. Parameters of ServletConfig are defined
under <init-param> tags in web.xml file.
4. Each web application has a common ServletContext. All the servlets in the
web application can access the ServletContext. It has the web-application
information and resources, which are common and accessible to all the
servlets present in the web application. ServletContext is common for all the
servlets in the web application.

☞ Check Your Progress 3

1. Servlet interface contains the common methods for all servlets i.e. provides
the common behaviour for all servlets. All the three lifecycle methods of a
Servlet are defined in Servlet interface, javax.servlet.Servlet. The Servlet
Container calls the init() after instantiating the servlet and indicates that the
servlet is ready for service. The service() is the method that accepts the
24
request and response only after init() has been completed. The servlet is Basics of Servlet
terminated by calling destroy() method.
2. A servlet life cycle includes the entire process from its creation till the
destruction. The servlet is initialized by calling the init() method. The servlet
calls service() method to process a client's request. Destroy() method is used
to destroy the servlet. It is called only once at the end of the life cycle of a
servlet.
3. The init() method is used to create or load objects used by the servlet to
handle its requests while the server calls a servlet's destroy() method when the
servlet is about to be unloaded. In the destroy() method, a servlet should free
any resources allocated during initialization and shutdown gracefully. Hence
this acts as an excellent place to deallocate resources such as an open file or
open database connection.
4.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class studentServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet program</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("We are student of SOCIS, IGNOU!!");
out.println("</BODY></HTML>");
}
}

2.10 FURTHER READINGS

• Jason Hunter, and William Crawford “Java Servlet Programming”,


O'Reilly Media, Inc.,2001.
• Kathy Sierra, Bryan Basham, anddd Bert Bates ,“Head First Servlets and
JSP”, O'Reilly Media, Inc., 2008.
• https://www.w3.org/
• https://www.liquidweb.com/kb/installing-tomcat-9-on-windows/
• https://docs.oracle.com/cd/E19857-01/820-0261/abxbh/index.html
• https://tomcat.apache.org/tomcat-9.0-doc/servletapi/index.html
• https://www.w3adda.com/servlet-tutorial
• https://www.w3schools.com/tags/ref_httpmethods.asp
• https://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html

25
UNIT 3 SESSION MANAGEMENT AND
DATABASE CONNECTIVITY IN
SERVLET

Structure

3.0 Introduction
3.1 Objectives
3.2 Session Management
3.2.1 HttpSession
3.2.2 Cookies
3.2.3 URL Writing
3.2.4 Hidden Fields
3.3 Servlet Collaboration
3.3.1 Using RequestDispatcher Interface
3.3.1.1 forward() Method
3.3.1.2 include() Method
3.3.2 Using HttpServletResponse Interface
3.3.2.1 sendRedirect() Method
3.3.3 Using ServletContext Interface
3.3.3.1 setAttribute() Method
3.3.3.2 getAttribute() Method
3.4 Database Connectivity
3.4.1 Insert data into Database
3.4.2 Retrieve Data from Database
3.5 Summary
3.6 Solutions/Answers to Check Your Progress
3.7 References/Further Reading

3.0 INTRODUCTION
In the previous unit, you have already gone through the basics of Servlets in detail
which are a server side programming language. As you know that the servlets are used
for dynamic web application. Several users interact with such web applications
simultaneously. Do you know how to manage this dynamic application among the
users? A strategy called session management is applied in these applications. In this
unit, you will learn more about session management. In Java Servlet, session is
managed through different techniques such as HttpSession object, Cookies, URL
rewriting and Hidden Form field. For example, when you check your result on the
IGNOU website and put your roll number in the input field, it shows that some roll
numbers might appear for your selection. It is all possible by the cookies. You will
find explanations and examples of these techniques used in session management.
In addition, this unit introduced you to Servlet Collaboration which is all about
sharing information among the servlets. The Servlet-API provides the
RequestDispatcher, HttpServletResponse and ServletContext interface to achieve
Servlet Collaboration. RequestDispatcher interface is useful for forwarding the
request to another web resource and including the resource in the current servlet.
HttpServletResponse interface makes available a method sendRedirect to
communicate with others. A servlet can also share information among multiple
1
Web Application
Development using J2EE servlets by using setAttribute and getAttibute method of ServletContext. This unit
explains to you how the servlets communicate with each other using the methods
defined in these three interfaces. Apart from these, this unit also enlightens you about
database access using Java Database Connectivity (JDBC) technology.
In the previous unit, you have already gone through the procedure of compiling as
well as after compiling servlet made entries in deployment descriptor (web.xml) file
and invoked them from a web browser. The previous Unit also defined the creating
and running procedure of servlet in NetBeans. This Unit is also devoted to the
servlets. So, there is no need to define the same procedures again.

3.1 OBJECTIVES

After going through this unit, you will be able to:

• Describe how to manage session between servlets,


• Connect servlet with database,
• Use forward() and include() method,
• Share information between servlets,
• Use setAttribute() and getAttribute() in servlets, and
• Insert and retrieve data to/from database.

3.2 SESSION MANAGEMENT

In the previous unit, you studied the Java Servlets used to create dynamic content-
based web pages or web applications. Dynamic web pages are different from static
web pages in which web server creates a web page when a web client or user requests
it. For example, when you check your online results on IGNOU website, different
pages are generated for different students by the IGNOU web server depending on
your enrolment number.
We all know that HTTP is a stateless protocol which is explained in the previous Unit.
It means that the HTTP protocol does not remember information when client or user
communicates with the server. Whenever you send a request to the server through
HTTP, the HTTP treats each request as a new request. But sometimes in web
applications, clients are doing some important work such as online shopping, online
banking etc. In that situation, it is necessary to know about the client and remember
the client's request accordingly. For example, an online banking application system
enables many clients to do their different activities like checking account balance(s),
obtaining statements and making financial transactions simultaneously. For
maintaining each client’s session, you can use session management.
Before going into session management details, you should know about the two
important terms, i.e. session and state, which are necessary for implementing business
transactions across multiple clients. These are as under:
Session: The server should recognize a series of requests from the same user which
form a single working ‘session’. For example, in net banking application, each client
can be differentiated from another client by associating a unique identifier in request
and response within a specific working session.

2
Session Management and
State: The server should be able to remember information related to the previous Database Connectivity in
request and other business transaction that are made for that request. For example, in Servlet
net banking application, state comprises client information such as account number
and amount transaction made within the particular session.
Do remember one thing-- session management does not change the nature of HTTP
protocol i.e., stateless feature provides a way to remember the client information.
Session management is also known as session tracking, which permits Servlet/JSP to
maintain information about a series of request from the same client. It is a mechanism
to store session information for each client. For example, When a user visits any web
application, unique identification information about the user is stored in an object
available during the particular session until the user quits the web application.
There are four ways to manage sessions: HttpSession object, Cookies, URL rewriting,
and hidden fields.
3.2.1 HttpSession Object
Any dynamic website or web application uses the concept of sessions and Session
object to store data for a particular user. For example, when you visit any web
application for the first time, you have entered login name and password. This
information might be stored in session variable and maintained by the servlet
container during your visit to web application so that it can be accessed when needed.
When your session is started, the requesting browser is allotted a unique id for each of
the clients for identifies the client. This Session object is denoted by
javax.http.HttpSession interface.
You have learned about the HttpSession interface under the Servlet API in the
previous Unit. Servlet API provides session management through HttpSession
interface. This HttpSession interface provides a mechanism to identify a user to
examine who is visiting a web application and to store the user information. Servlet
Container creates a session id for each user. You can maintain state between the
transactions by using methods of HttpSession interface.
Example -1
The following example will explain to you about session management using the
methods defined in the HttpSession interface.
Following servletSession.java is servlet program that uses session tracking to keep
track of how many times a particular user has accessed a page and to display some
details of the current session such as Session identifier, Creation Time and Last
Access Time. The source code of this program is listed below:

servletSession.java

import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class servletSession extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
Integer ct = (Integer) session.getAttribute("ct");
if (ct == null)
{ ct = new Integer(1); }
3
Web Application
Development using J2EE else { ct = new Integer(ct.intValue()+1); }
session.setAttribute("count", ct);
out.println("Session Details: ");
out.println("<br/>");
out.println("You have visited this page : " + ct + ((ct.intValue() ==1)? " time" : " times")
);
out.println("<br/>");
out.println("Session ID : " + session.getId());
out.println("<br/>");
out.println("New Session : " + session.isNew() );
out.println("<br/>");
out.println("creation Time : " + new Date(session.getCreationTime()));
out.println("<br/>");
out.println("Last Access Time : " + new Date(session.getLastAccessedTime()));
}
}

You already have learnt about the running procedure of servlet and methods included
in the above servlet program in Unit 2 Block 1 of this course. Compile the above
servlet, put the class file in the classes folder, and create appropriate entry in the
web.xml file under the WEB-INF folder in your ‘webapps’ folder. Now, you can start
your web server and run the program from your browser.

When you access this program for the first time, the visiting counter will be one and
the new Session will ‘true’. When visiting counter increases in numbers the new
session will be ‘false’. This program will also display some details of the current
session such as Session identifier, Creation Time and Last Access Time.

Output of the above servlet program is displayed in the following figure-1.


Creating and running procedures of Sevlet are given in the previous Unit of this block.

Figure 1: Output of Servlet by using HttpSession Object


In the similar way, you can create above servlet program and add the code in
index.html file like the following:
<h1>Click here to go <a href="servletSession" >Session Servlet Program</a></h1>

When you will run your Project in NetBeans it is displayed as output like the figure-
2:

4
Session Management and
Database Connectivity in
Servlet

Figure 2: Output Screen of Welcome Index Page

When you will click on ‘Session Servlet Program’ link, then servlet will run and give
output as Figure-3:

Figure 3: Output Screen of Session Servlet program

3.2.2 Cookies
In the last section, you have studied session management through HttpSession object
in Servlet. Here you will learn about Cookies. This is another session management
technique. Cookies are a small part of information like a name, a single value and
optional attributes such as comment, path and domain qualifiers, a maximum age, and
a version number. A servlet sends this cookie information to a web browser. It is
saved by the browser and later sent back to the server. The browser probably
supports 20 cookies for each Web server, 300 cookies total and may limit cookie size
to 4 KB each. You can uniquely identify a client through cookie's value, so cookies
are generally used for session management. If the client disables the cookies then it
won’t work and you cannot maintain a session with cookies.
There are two types of cookies such as Non-persistent cookie and Persistent cookie in
servlets. The Non-persistent cookie is effective for a single session only and
removed each time when the user closes the browser. On the contrary, Persistent
cookie is effective for multiple sessions, and it is removed only when user logouts.
A cookie is indicated by the Cookie class in the javax.servlet.http package. You can
create a cookie by calling Cookie class like the following:
Cookie c = new Cookie(“userid”, “socis”);

You can send the cookie to the client browser by using addCookie() method of the
HttpServletResponse interface like the following:

response.addCookie(c);

5
Web Application
Development using J2EE You can retrieve cookies from request using getCookie() of the HttpServletRequest
interface like the following:

request.getCookie(c);

Example -2
The following example demonstrates to you how to create cookies and how these
cookies are transferred to another servlet. This example contains one HTML form
(cookieForm.html) and two servlet programs (CreateCookieServlet.java and
GetCookieServlet.java).
The source codes of the programs are given below:

cookieForm.html

<form action="../servlet/CreateCookieServlet" method="post">


Name:<input type="text" name="uname"/><br/>
<input type="submit" value="Submit"/>
</form>

CreateCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CreateCookieServlet extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
out.print("Welcome "+name);
out.print(", Submit your data for GetCookieServlet");
//create cookie object
Cookie c=new Cookie("uname",name);
//add cookie in the response
response.addCookie(c);
out.println("<form action='../servlet/GetCookieServlet' method='post'>");
out.println("<input type='submit' value='Submit data'>");
out.println("</form>");
}
catch(Exception e){System.out.println(e);}
}
}

GetCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookieServlet extends HttpServlet
{
6
Session Management and
public void doPost(HttpServletRequest request, HttpServletResponse response) Database Connectivity in
{ Servlet
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie c[] = request.getCookies();
out.println("Welcome in SOCIS "+c[0].getValue());
}
catch(Exception e){System.out.println(e);}
}
}

Now, you can compile both the servlets program and place class files in the classes
folder of the your web application. Also, make an entry in the deployment descriptor
file and first run the HTML form program from your browser. When you submit your
data by clicking submit button of the HTML program (see figure-4), the control is
transferred to CreateCookieServlet program (see figure-5).

Figure 4: Cookie HTML Form

The process of creation and sending of cookies are included in CreateCookieServlet


program. Now at this stage, form data is fetched and displayed on screen. When you
click on ‘Submit data’ button, the control goes to the GetCookieServlet program (see
Figure-5)

Figure 5: Intermediate output of CreateCookieServlet program

Now, the GetCookieServlet program fetches your data from CreateCookieServlet


program and displays this as an output on your monitor screen like the following
figure-6.

Figure 6: Final Output through Cookie techniques in session management

7
Web Application
Development using J2EE 3.2.3 URL Writing

In the previous section, you have learnt two session management techniques i.e.
HttpSession Object and Cookies. The third technique that you can use to maintain
user sessions is by using URL writing. In this approach, the token (parameter) is
embedded in each URL. When client submits request using such URLs, the token is
retransmitted to the server. In each dynamically generated page, server embeds an
extra query parameter or extra path information. If a browser does not support cookies
then in that case URL rewriting technique is the best alternative for session
management.
Using URL Writing technique, you can send parameter name/value pairs like the
following:

http://myserver.com?name=xyz&age=20

When you click on URL, the parameter name/value pair will transfer to the servlet.
The servlet will fetch this parameter by using getParameter() method of
HttpServletRequest interface from the requested URL and use it for session
management.
Example -3
The following example will show you how to work URL Writing technique with
session management. This example comprises the 3 programs such as html form
(URLWritingForm.html) and two Servlet program (CreateURLServlet.java and
FetchURLServlet.java). The source codes of programs are listed below:
URLWritingForm.html
<html>
<head><title>URL Writing Session FORM</title></head>
<body>
<form action="../servlet/CreateURLServlet" method="post">
<fieldset>
<legend>Student Details</legend>
Student Name :<input type="text" name="uname"> <br>
Password: <input type="password" name="pwd"> <br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body></html>

CreateURLServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CreateURLServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("uname");
String password = request.getParameter("pwd");

8
Session Management and
if(password.equals("socis")) Database Connectivity in
{ Servlet
response.sendRedirect("FetchURLServlet?username="+ name);
}
else
{out.println("Password is incorrect");}
}
}

FetchURLServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FetchURLServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
out.println("Welcome in SOCIS, "+name);
}
}

Now, you can compile both the servlet programs and place class file in ‘classes’
folder. Also make entry in web.xml file and start web server. Finally, you can run
URLWritingForm.html file from your browser. Here, you can submit your data such
as student name, password and click on ‘Submit’ button (see Figure-7)

Figure 7: URL Writing HTML Form


After submitting your data, control goes to the CreateURLServlet program. This
servlet program fetches your username and password from html form and compares
your password statically with given ‘socis’ password in the program. If a match is
done then control is transferred to the FetchURLServlet program else it displays an
error message on the server.
Here, you can see parameters value in URL of the FetchURLServlet program in
address bar like the following figure-8.

Figure 8: URL Parameter value in address bar

After fetching the parameter value, the FetchURLServlet program will display output

Figure 9: Example Output screen for URL Writing technique


Web Application
Development using J2EE as like following Figure-9.

3.2.4 Hidden Fields


Another technique for managing user sessions is by passing a token as the value for an
HTML hidden field. You have seen web-form many times on the website. When
client submits the form, additional fields will also be sent in the request in the form of
hidden fields to keep track of the session. This method gives you the advantage to use
this without depending on the browser whether the cookie is disabled or not. It has a
disadvantage also as it is not secure because anyone can view the hidden form field
value from the HTML file and use it to hack the session. Another disadvantage of
using this method is that it needs extra form submission on each page.
You can create a unique hidden filed in the HTML form to keep track of the session
like the following format:
<input type=”hidden” name=”userid” value=”socis”>

You can get this hidden field in Java Servlet using the getParameter() method of
HttpServletRequest interface.
String param1 = request.getParameter("userid");

☞ Check Your Progress 1

1. What is session management? What are the different techniques of session


management in servlets? Why is session management needed for HTTP
protocol? Explain how cookies can be used for session management.

----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------
--------------------------------------------------------------------------------------
2. Write a servlet program by using HttpSession Object of session management.
Servlet program will display creation time when user will visit web page for
the first time else it displays last access time. Also display session ID in both
the conditions.

----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------
--------------------------------------------------------------------------------------
3. What is the difference between a session and cookie?
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------
--------------------------------------------------------------------------------------

10
Session Management and
Database Connectivity in
3.3 SERVLET COLLABORATION Servlet

In the previous section, you have gone through the session tracking techniques. Using
these techniques, you can track a series of user requests. This section describes to you
how servlets share information between two or more servlets.
Servlets running together under the same server, need to communicate with each
other for exchanging data information. When two or more servlets can communicate
or share common information, you can call it Servlet Communication or Servlet
Collaboration.
Servlet collaboration means sharing information among the servlets. This tactic
requires each servlet to know the other servlet with which it collaborates. Sometimes,
a situation arises in program coding when you may require passing the request from
one servlet to another. Also, you may want to include the content from HTML, JSP or
Servlet into your servlet. Java provides Servlet-API to accomplish Servlet
Collaboration and Servlet-API covers two interfaces namely:
javax.servlet.RequestDispatcher and javax.servlet.http.HttpServletResponse. Both
interfaces have various methods which are used for sharing information between
servlets.

3.3.1 Using RequestDispatcher Interface


RequestDispatcher is an interface which is found in javax.servlet package. There are
two methods defined in the RequestDispatcher interface: forward () and include()
methods for dispatching requests to/from web resources. Both the methods accept a
javax.servlet.ServletRequest and a javax.servlet.ServletResponse object as arguments.
The client or browser is not involved in request dispatching.

3.3.1.1 The forward() Method


This method is used to forward a request from a servlet to another web resource like
servlet, JSP file or HTML file on the server. When this method is called, control is
transferred from the current to the next resource called.
The signature of this method is as follows:

public void forward(ServletRequest request, ServletResponse response)


throws ServletException, java.io.IOException

3.3.1.2 The include() method


This method is used to include the content of another servlet, JSP page, HTML file in
the servlet response. After calling this method, the response of another resource is
included in the called resource.
The signature of this method is as follows:

public void include(ServletRequest request, ServletResponse response)


throws ServletException, java.io.IOException

For using a servlet forward() or include() method, you first need to obtain a
RequestDispatcher object. You can obtain a RequestDispatcher object like the
following:

11
Web Application
Development using J2EE RequestDispatcher rd = request.getRequestDispatcher(String resource);
Example-4

The following example explains how to use both the forward() and include() method
of RequestDispatcher interface to achieve Servlet Collaboration. This example
comprises one HTML program (loginForm.html) and two servlets programs
(RequestDispatcherServlet.java and WelcomeStudentServlet.java). The LoginForm
contains two input fields i.e., name and password. RequestDispatcherServlet program
received data from LoginForm and compares statically with given data in the servlet
program. If a match is done, control is transferred to the WelcomeStudentServlet
program, else control gets back to LoginForm again to re-enter the data.
The source codes of all three programs are listed below:

LoginForm.html

<html>
<head></head>
<body>
<form action="../servlet/RequestDispatcherServlet" method="post">
<fieldset>
<legend>Student Details</legend>
Student Name: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>

RequestDispatcherServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestDispatcherServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name=req.getParameter("user");
String pass=req.getParameter("pwd");
if(name.equals("Ram") && pass.equals("socis"))
{
RequestDispatcher rd=req.getRequestDispatcher("WelcomeStudentServlet");
rd.forward(req, res);
}
else
{
out.print("User name or password is incorrect!");
RequestDispatcher rd=req.getRequestDispatcher("../servlets/LoginForm.html");
12
Session Management and
rd.include(req, res); Database Connectivity in
} Servlet
}
}
WelcomeStudentServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeStudentServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("user");
out.print("Welcome in IGNOU, "+name+"!");
}
}

You can compile both the servlet programs and make a suitable entry in web.xml file.
Now you can start the web server and run HTML form through the browser.
When you run your LoginForm.html, it will display like the following Figure-10 with
two input fields. When you enter student name and Password and click on submit
button then action control goes to the RequestDispatcherServlet program.

Figure10: Login Form for RequestDispatcher servlet example

When you input the Student Name as Ram and Password as socis then it will welcome
you (see figure-11); otherwise, it will ask to re-enter values (see figure-12)

Figure 11: Request Dispatcher example, Welcome Screen

When condition is false, it will display a message “User name or password is


incorrect” and LoginForm will display again for re-enter input values (see figure-12).

13
Figure 12 Request Dispatcher example, Login Form Screen
Web Application
Development using J2EE
3.3.2 Using HttpServletResponse Interface
The HttpServletResponse Interface captures the functionality of a response object that
is returned to the client from an HTTP servlet. The interface HttpServletResponse
offers many protocol-specific methods which are not available in ServletResponse
interface. The interface HttpServletResponse extends the
javax.servlet.ServletResponse interface. You have already explored two of the
methods in HttpServletResponse at the time of servlet writing in this unit as well as
Unit 2. These two methods setContentType() and getWriter() are used when sending
output to the browser. The setContentType(java.lang.String type) method is used to
set the type of the response data e.g. text, HTML etc. The getWriter() method returns
the PrintWriter object for sending text data to the client.

res.setContentType("text/html");
PrintWriter out = res.getWriter();

Another method of HttpServletResponse interface is addCookie() method which you


have already studied in section 3.2.2 of this Unit. Another most important method in
HttpServletResponse interface is sendRedirect() method. In the next section, you will
learn about this method. You can use this method to redirect the user to another web
page.
3.3.2.1 The sendRedirect() Method
The sendRedirect() method of HttpServletResponse interface is used to redirect
response to another web resource such as HTML, servlet or jsp file. The
sendRedirect() method works at the client side. This method always sends a new
request. It can be used within and outside the application. For some applications, you
want to send the request outside your web application and then it becomes most
useful because it takes more time to fetch resources.

The syntax of sendRedirect() method is as under:

public void sendRedirect(String URL) throws IOException;

The following example illustrates the simplicity of sendRedirect() method:

response.sendRedirect("http://www.ignou.ac.in");

In the previous section, you have studied forward() method. Function of both the
methods forward() method of RequestDispatcher interface and sendRedirect() of
RequestDispatcher interface are almost similar but they differ also.

Difference between forward() and sendRedirect() method


Both methods bring the user to a new web resource. Both are similar, but knowing the
fundamental difference between the two can help you write a servlet more efficiently.
The difference between the two methods is as follows:
• The forward method can be used to redirect the request without any help of client
browser, and control transfer remains within-applications resources only,
whereas sendRedirect method can redirect the request to client browser and
control transfer goes outside the current domain.
• In forward method, HttpServletRequest object and HttpServletResponse object
are passed to the new resource, whereas in sendRedirect method, previous
HttpServletRequest object is lost. For passing information between the original
and new request, you can pass the information as a query string appended to the
destination URL.
14
Session Management and
Database Connectivity in
3.3.3 Using ServletContext Interface Servlet

In servlet programming, servlet context is the environment where the servlet runs. The
ServletContext’s object is created by the web container at the time of deploying the
project. Using this you can use to access all the resources available within the
application and to store attributes which other servlets with the same context can use.
You can use one context per "web application" per Java Virtual Machine. The
ServletContext object is used to get configuration information from deployment
descriptor file (web.xml), which will be available to any servlet or JSPs that are
component of the ‘webapps’.

The ServletContext Interface defines various methods which are used by servlets to
communicate with its servlet container. For example, dispatch requests or writes to a
log file to get the MIME type of a file. The object of ServletContext can be added and
retrieved from the context using the setAttribute and getAttribute methods.

How to get the Object of ServletContext

ServletContext app = getServletContext();


//This is convenient way to get the ServletContext object
OR
ServletContext app = getServletConfig().getServletContext();
//You can get the ServletContext object from ServletConfig object

When you have defined ServletContext object, you can set attributes of
ServletContext object by using the setAttribute() method. From now, ServletContext
object is available to all the servlets of the web application. By using the
getAttribute() method, other servlets can get the attribute from the ServletContext
object.

3.3.3.1 setAttribute() Method


This method stores an object and binds the object with the given attribute name in the
application scope. It means that the said object is accessible from any servlet within
the same web application. If attribute name already exists in the ServletContext, the
old bound object will be replaced by the object passed to this method.

void setAttribute(java.lang.String name, java.lang.Object obj)

This method has two parameters:

String name: By providing the value of this argument, you can specify the name of
attribute.
Object obj: By providing the value of this argument, you can specify the value of the
named attribute.

3.3.3.2 getAttribute() Method


This method is used to get attribute with the given name from context. It returns the
value of named attribute as an Object or NULL if there is no attribute by that name.

Object getAttribute(String name)

Example- 5

15
Web Application
Development using J2EE The following example explains to you how setAttribute() and getAttribute() method
works with the ServletContext.
The example uses two servlets: ServletDemo1 and ServletDemo2 and one HTML
Form (Login.html). This form comprises two input fields such as name and
percentage of student. A student must have a percentage of more than 80. When the
user submits the form, control will transfer to the ServletDemo1 servlet.

The ServletDemo1 servlet received two input values i.e. name and percentage by
using getParameter() method from html form. This servlet uses setAttribute() method
to bind name attribute and does this by first obtaining the ServletContext object.
Here, this servlet checks percentage if percentage is more than 80, then the control
will pass to the ServletDemo2 servlet, otherwise control will transfer to Login form to
fill data again.
In ServletDemo2 servlet, after getting the ServletContext object, you can use
getAttribute() method to get name attribute.

The code source of the three programs is listed below:

Login.html

<form action="../servlet/ServletDemo1" method="post">

<fieldset>
<legend>Student Details</legend>

Student Name: <input type="text" name="username">


<br>
Percentage: <input type="text" name="percent">
<br>

<input type="submit" value="Submit">


</fieldset>
</form>

ServletDemo1.java

import java.io.*;
import javax.servlet.*;
public class ServletDemo1 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
//Creating ServletContext object
ServletContext sc = getServletContext();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Using ServletContext object to set and read attributes");
out.println("<br/>");
String uname = request.getParameter("username");
int Per = Integer.parseInt(request.getParameter("percent"));
//Setting name attribute to be shared between multiple servlets
sc.setAttribute("Name", uname);
if( Per > 80)
{

16
Session Management and
RequestDispatcher rd = sc.getRequestDispatcher("/servlet/ServletDemo2"); Database Connectivity in
rd.forward(request,response); Servlet
}
else
{
out.print("Data is incorrect!");
out.println("<br/>");
out.print("Fill your data again");
RequestDispatcher rd = sc.getRequestDispatcher("/servlets/Login.html");
rd.include(request,response);
}
}
}
ServletDemo2.java
import java.io.*;
import javax.servlet.*;
public class ServletDemo2 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
ServletContext sc = getServletContext();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<b>" + "Congratulations! " + sc.getAttribute("Name") + "</b>");
}
}

Now, you can compile both servlets and create appropriate entry in web.xml file.
Finally, you can start server and run the Login form from your browser. The output of
the html program is displayed like the following figure13.

Figure 13: Login form

Here you can submit your data. The flow controls of servlets depends on your
percentage. If you submitted more than 80, you will get congratulations (see figure-
14), this procedure is defined in the ServletDemo2 servlet otherwise you will get back
to login again to re-enter data (see figure- 15)

When condition will be true, you will get following figure-14:

17
Web Application
Development using J2EE

Figure 14: Output of setting and getting attribute example

Figure 15: Output Screen for re-enter data

When the condition is false, you will get the following to re-enter data:

☞ Check Your Progress 2

1. What is servlet collaboration? How many ways can servlet communicate


with each other? What is the purpose of RequestDispatcher Interface?
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
2. What is the difference between forward() and sendRedirect() method?
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
3. Write a servlet program for opening the IGNOU website by using
sendRedirect() method.
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------

3.4 DATABASE CONNECTIVITY

18
Session Management and
In the previous section, you have studied more about the advanced features of servlets Database Connectivity in
with examples, but all this work has been done statically without any database Servlet
connectivity. This section will provide you in-depth knowledge of data access,
specifically insertion and retrieval of data to/from a database.
Database access is one of the important features of Web application. Java has its own
technology for database connectivity called JDBC (Java Database Connectivity).
JDBC provides a standard library for accessing a wide range of relational databases
like MS-Access, Oracle and Microsoft SQL Server. Using JDBC API, you can access
a wide variety of different SQL databases. The core functionality of JDBC is found in
java.sql package.
Consider a table named as Student created in Microsoft SQL Server database with
Roll No, Name and Program name. This table is used in both the following sections.
This section defines example(s) for storing/retrieving data into/from a Microsoft SQL
Server using type-4 JDBC driver. You can run these programs on any web server such
as Tomcat. For running these programs, you need a JDBC driver in .jar form and
placing them in lib directory under the web server.

3.4.1 Insert data in Database

For inserting data into a database, you can use the following example.

Example - 6
The following example will demonstrate to you how to store data in a database using
servlet. For this, create a HTML Student Form and one Servlet for storing data into a
database.
The student form contains student’s details like student enrolment no., student name
and Programme name. You will have to create a student table with related fields of
student form. When you submit these details, access ‘DataStoreServlet’ to store data
into the database.
The DataStoreServlet program is written similar to the above servlet programs with
database query and ‘try’ and ‘catch’ clause of standard Java mechanism.

The source codes of both the files are listed below:

StudentForm.html
<html>
<body>
<form action="../servlet/DataStoreServlet" method="post">
<h3>Indira Gandhi Open University </h3>

<fieldset>
<legend><b>Student Details </b></legend>

Enrolment No: <input name="sid" type="text"/><br>


Student Name : <input name="sname" type="text" value="" ><br>
Programme : <input type="text" name="prg" value=""> <br>
<input type="submit" value="Submit" />

</fieldset>
</form>

19
Web Application
Development using J2EE </body>
</html>

In the following servlet program, the first step is to get the data from
‘StudentForm.html’ program using request.getParameter() method. After connecting
to database, an insert query is executed using executeUpdate() method.

DataStoreServlet.java

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DataStoreServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String rollNo = req.getParameter("sid");
String StuName = req.getParameter("sname");
String prgName = req.getParameter("prg");
//create connection object
Connection con = null;
// create statement object
Statement stmt = null;
// connection string using Type-4 Microsoft SQL Server driver
// you can also change the next line with your own environment
String url=
"jdbc:microsoft:sqlserver://127.0.0.1:1433;user=sa;password=poonam;DatabaseN
ame=SOCIS";
try
{
// load JDBC type-4 SQL Server driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = DriverManager.getConnection(url);
if (con != null)
{
stmt = con.createStatement();
//insert query
String rsql ="insert into student
values("+rollNo+",'"+StuName+"','"+prgName+"'"+")";
//execute query
stmt.executeUpdate(rsql);
out.println("Your data is successfully stored in database");
}
if(con == null)
{ con.close(); // release connection }
}
// end of try clause catch(SQLException se)
{ out.print("SQL:"+se.getMessage());}
catch(Exception e)
{ out.print("Exception:"+e.getMessage());}
}
}
20
Session Management and
Database Connectivity in
As earlier, you can compile the above servlet and make related entry in deployment Servlet
descriptor file (web.xml) then start your web server and run your StudentForm.html
file from your browser. When you run your form, it will display output like the
following figure-16:

Figure 16: Student data Form for storing data into database

In the above screen, when you will enter values then the following screen (figure-17)
will show you a message for successful data storage.

3.4.2 Retrieve Data from Database

We have just seen in the previous section about the storage of data into a database
using servlet program. This section explains to you how to retrieve some data from a
database. Figure 17: Data stored in persistent storage

Example-7

The following example gives you an illustration about how to retrieve data from the
database. After execution of the above DataStoreServlet program, you have stored
sufficient data into the database. Now, you will execute the following code for
retrieving the data from the database. In this program, one additional ResultSet object
is used for retrieving data from the select query. The data is retrieved from ResultSet
object by using getXXX() method such as getInt() and getString(). Note that if the
column name is an integer type, then you should use getInt() method instead
getString() method. The following RetDataServlet program is listed for retrieving data
from database.

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RetDataServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Connection con = null; //create connection object
Statement stmt = null; // create statement object
ResultSet rs = null; // create ResultSet object
21
Web Application
Development using J2EE // connection string using Type-4 Microsoft SQL Server driver
// you can also change the next line with your own environment
String url=
"jdbc:microsoft:sqlserver://127.0.0.1:1433;user=sa;password=poonam;DatabaseN
ame=SOCIS";
try
{
// load JDBC type-4 SQL Server driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = DriverManager.getConnection(url);
if (con != null)
{
stmt = con.createStatement(); // select SQL statement
String rsql ="select * from Student";
rs = stmt.executeQuery(rsql); //execute query
out.println("<table border=1><tr><td>Roll Number</td><td>Student
Name</td><td>Programme</td></tr>");
while( rs.next() )
{
out.println("<tr><td>" + rs.getInt("RollNo") + "</td>");
out.println("<td>" + rs.getString("Student_Name") + "</td>");
out.println("<td>" + rs.getString("Programme") + "</td></tr>");
}
out.println("</table>");
}
if(con == null) {con.close();}
}
catch(SQLException se){ out.println("SQL:"+se.getMessage());}
catch(Exception e){ out.println("Exception:"+e.getMessage());}
}
}

Now, you can compile the above servlet and make entry in deployment descriptor file
(web.xml), start your web server and run your servlet program from your browser.
After running the RetDataServlet program, the data will be displayed on your output
screen like following figure-18:

If you want to build your project using Oracle or other database as back end then you
can change only port no. and relevant JDBC driver name in above servlet source code.

Figure 18: Display data from database

3.5 SUMMARY

In this unit, you have learned how to use session management using four techniques:
HttpSession object, Cookie, URL Writing, and Hidden form field. You have been
shown a number of examples to demonstrate the use of session management in the
22
Session Management and
servlets. In addition, this Unit introduced you to Servlet collaboration which is all Database Connectivity in
about sharing information among the servlets. The Servlet-API provides the Servlet
RequestDispatcher interface to achieve Servlet Collaboration. This interface is useful
for forwarding the request to another web resource and including the resource in the
current servlet. Apart from these, this unit also discussed database access using Java
Database Connectivity (JDBC) technology.

3.6 SOLUTIONS/ANSWERS TO CHECK YOUR


PROGRESS

☞ Check Your Progress 1

1) Session management allows servlets to maintain information about a series of


requests from the same user. Session in Java Servlet is managed through four
techniques such as HttpSession API, Cookies, URL rewriting and Hidden
Field.
HTTP is a stateless protocol. It means a HTTP server does not remember any
state information. So one needs to maintain state using session management
techniques.
For this cookie can be used in the following way for managing sessions in
java servlets:
• You can create a cookie by calling Cookie class like the following:
Cookie c = new Cookie(“userid”, “socis”);
• You can send the cookie to the client browser by using addCookie()
method of the HttpServletResponse interface like the following:
response.addCookie(c);
• You can retrieve cookies from the request by using getCookie() of the
HttpServletRequest interface like the following:
request.getCookie(c);
2) The source code of servlet program by using HttpSession object is as under:

import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class sessionServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
if ( session.isNew())
{
out.println("New Session : " + session.isNew() );
out.println("<br/>");
out.println("Session ID : " + session.getId());
out.println("<br/>");
23
Web Application
Development using J2EE out.println("creation Time : " + new Date(session.getCreationTime()));
}
else
{
out.println("New Session : " + session.isNew() );
out.println("<br/>");
out.println("Session ID : " + session.getId());
out.println("<br/>");
out.println("Last Access Time : " + new
Date(session.getLastAccessedTime()));
}
}
}

3) Both the Session and Cookie are used to store information. The session is
stored in server-side machine, whereas Cookies are stored on the client-side
machine. Session should work regardless of the settings on the client browser.
Session data will be available to all pages on the site during the particular
session of visit. Session can store objects, and cookies can store only strings.
Cookie expires depending on the lifetime you set for it whereas a Session
ends when a user closes the browser or after leaving the site.

☞ Check Your Progress 2


1) Servlet collaboration means sharing information among the servlets. This
tactic requires each servlet needs to know the other servlet with which it
collaborates. The Servlet API provides the following interfaces and their
methods which are responsible for sharing information between servlets:
• RequestDispatcher Interface : include() and forward() method;
• HTTPServletResponse Interface : sendRedirect() method;
• ServletContext Interface : setAttribute() and getAttribute() method;

RequestDispatcher interface is found in javax.servlet package. There are two


methods defined in the RequestDispatcher interface: forward () and include()
methods for dispatching requests to/from web resources.

2) Both the methods bring the user to a new web resource. Both are similar but
there is a fundamental difference between the two. The difference between
two methods is as follows:

• The forward method can be used to redirect the request without the help
of the client browser and control transfer remains within-applications
resources only. The sendRedirect method can redirect the request to the
client browser and control transfer goes outside the current domain.
• In forward method, HttpServletRequest object and
HttpServletResponse object are passed to the new resource whereas in
sendRedirect method, previous HttpServletRequest object is lost. For
passing information between the original and new request, you can pass
the information as a query string appended to the destination URL.
3) The source code of servlet by using sendRedirect() method is given below:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

24
Session Management and
public class sendRedirectServlet extends HttpServlet Database Connectivity in
{ Servlet
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
res.sendRedirect("http://www.ignou.ac.in/");
}
}

3.7 REFERENCES/FURTHER READING

•Jason Hunter, and William Crawford “Java Servlet Programming”, O'Reilly


Media, Inc., 2001.
• Kathy Sierra, Bryan Basham, anddd Bert Bates ,“Head First Servlets and JSP”,
O'Reilly Media, Inc., 2008.
• Budi Kurniawan , “Java for the Web with Servlets, JSP, and EJB: A Developer's
Guide to J2EE Solutions: A Developer's Guide to Scalable Solutions”, Techmedia ,
2002.
• Pratik Patel and Karl Moss, “Java Database Programming with JDBC: Discover the
Essentials for Developing Databases for Internet or Intranet Applications”, Coriolis
Group, 1996.
• https://www.w3adda.com/servlet-tutorial
• https://tomcat.apache.org/tomcat-5.5-
doc/servletapi/javax/servlet/ServletContext.html
• https://tomcat.apache.org/tomcat-5.5-
doc/servletapi/javax/servlet/http/HttpSession.html
• list of drivers: http://www.devx.com/tips/Tip/28818

25
UNIT 4 JAVA SERVER PAGES
Structure

4.0 Introduction
4.1 Objectives
4.2 JSP Overview
4.3 JSP Life Cycle
4.4 JSP API
4.5 Components of JSP
4.5.1 Directives
4.5.2 Scripting Elements
4.5.3 Action Elements
4.6 JSP Implicit Objects
4.6.1 out Object
4.6.2 request Object
4.6.3 response Object
4.6.4 session Object
4.6.5 application Object
4.6.6 page Object
4.6.7 pageContext Object
4.6.8 config Object
4.6.9 exception Object
4.7 An Introduction to JSP Standard Tag Library (JSTL)
4.8 Exception handling in JSP
4.8.1 Using errorPage and isErrorPage attribute of page directive
4.8.2 Using try and catch block in Scriptlets
4.8.3 Using <error-page> element in Deployment Descriptor
4.9 Database Connectivity
4.9.1 Insert data in Database using JSP
4.9.2 Retrieve Data from Database using JSP
4.10 Summary
4.11 Solutions/Answers to Check Your Progress
4.12 References/Further Readings

4.0 INTRODUCTION
Servlet is a server-side programming language. In unit 2 and 3 of this course, you
have already gone through the concept of Servlets in detail. . In this Unit, you will
learn another server-side language i.e. Java Server Pages (JSP). Both the JSP and
Servlets are correlated. JSP uses a component-based approach that allows web
developers to easily combine static HTML for look-and-feel with Java components
for dynamic features.
JSP is a specification of Sun Microsystems which first appeared in 1999. The current
specification of JSP is 2.3. The updates between JSP 2.2 and 2.3 are relatively minor.
JSP is a technology for developing dynamic web pages. It follows the characteristics
of Java ‘write once and run anywhere’. A JSP document contains HTML tags as well
as JSP elements. JSP page comprises different components such as directives,
scripting elements, standard actions and implicit objects.
This unit covers how to create a JSP page. It also provides a basic understanding of
JSP components that make an entire JSP page, Java Bean, Custom tag, and life cycle
of Java Server Pages. This unit will also introduce you to the exception handling in

1
Web Application
Development using J2EE JSP as well as database connectivity which are a necessary feature for any web
application.

4.1 OBJECTIVES

After going through this unit, you should be able to:

• use JSP to create dynamic web pages,


• use directives, scripting and action elements in a JSP page,
• write java code within the JSP page,
• create a custom tag,
• forward request from JSP pages to other resources,
• write program for handling exceptions at page and application level in JSP,
and
• develop database applications using JDBC and JSP.

4.2 JSP OVERVIEW

Java Server Pages (JSP) is powerful web technology. Using this technology, you can
create dynamic content based web pages. Dynamic web pages are different from static
web pages in which web server creates a web page when a web client or user requests
it. For example, your online results on IGNOU website, the page for every student
instead IGNOU web server dynamically creates a page depending on your enrolment
number.
As you know very well, an HTML page is a static page; it contains static content that
always remains the same. When you insert some dynamic content or java code inside
the HTML page, it becomes JSP page. A JSP page encompasses a very simple
structure that makes it easy for developers to write JSP code as well as for servlet
engine to translate the page into a corresponding servlet. You can change content
dynamically with the help of Java Bean and JSP elements. The JSP elements are the
basic building blocks of the page. JSP page consists of directives, scripting elements
and action elements. Each of these elements can use either JSP syntax or be expressed
in XML syntax, but you cannot use both syntaxes simultaneously. For this problem,
you can use the include mechanism to insert files that may use a different syntax.
Both JSP and Servlets are very closely related to each other. You have already studied
the Servlets in Unit 2 and Unit 3 of this course. The Java Server Pages have more
advantages over the servlets, which are as follows:

• JSP allows programmers to insert the Java code directly into the HTML file,
making the JSP document and development process easier, while Servlets use
plenty of ‘println’ statements for printing an HTML document that is usually
very difficult to use. The JSP has no such tedious task to perform.
• JSP supports element based dynamic content that allows programmers to
develop custom tags libraries to satisfy application needs.
• In a JSP page, visual content and logic are separated, which is not possible in
the servlets.
• JSP pages can be used in conjunction with servlets that handle business logic.
• Major advantage of JSP page is that in case JSP page is modified, there is no
need to recompile and redeploy the project. But the Servlet code needs to be

2
Java Server Pages
updated and recompiled if we have to change the look and feel of the
application.
To create the first JSP page, write some HTML code and java code, similar to code
given below, and save it with .jsp extension. This is a simple example of JSP where
you are using the scriptlets tag to put Java code in the JSP page. You will learn
scriptlets tag in section 4.5 of this unit.

<html><body>

<% out.println(“Welcome to the IGNOU family"); %>

</body></html>

For running the JSP program, you need Apache’s Tomcat. You have already installed
this software for servlets using the procedure defined in section 2.7 of Block 1 Unit 2
of this course. You should only create a ‘JSP’ folder under the ‘ex’ folder, and this
folder exists in the ‘webapps’ directory in Apache Tomcat. For this, you can see the
following figure-1. Place your JSP document in the ‘JSP’ folder to run the JSP page.

Figure 1: Directory structure for your program in Tomcat

Start your Tomcat Server, open a browser, and type the following URL to execute
your first JSP program.
http://localhost:8080/ex/JSP/first.jsp
The output of the program is displayed in figure-2:

Figure 2: First Program in JSP

You have seen the above program, which looks like an HTML document with some
added tags containing java code that allows the server to insert dynamic content in the
page. When a client sends a request for a JSP page, the server executes a JSP page
elements merges with static contents and sends the dynamically page back to the
client browser.
Steps for Creating and running procedure of JSP in NetBeans

3
Web Application
Development using J2EE Creating and running procedure of servlet in NetBeans is defined in Unit-2 of this
block. Installation process is given in Lab manual. This Unit is devoted to JSP. The
creating and running procedure of servlet as well as JSP are similar. To create a JSP,
open ‘Source Packages’ in NetBeans, right click on default package -> New -> JSP.

Figure 3: Creation window of JSP

Give a name and select location to JSP file as you have given a name MyJSP.jsp
under MyProject in Figure-4. Also select JSP File (Standard Syntax) option.

Figure 4: Name and Location window for JSP file

Finally select Finish button from button Panel.

Figure 5: Button Panel

4
Java Server Pages

Figure 6:Source code of MyJSP file

Now JSP file is ready, you can change the code as per your reqiurement .

Once this is completed. For running the particular JSP file, right-click on the file and
select ‘Run File’ (Shift+F6). The output of the MyJSP file is displayed as shown in
figure-7:

Figure 7: Output Screen of MyJSP file

JSP uses server-side scripting that is actually translated into servlets and compiled
before they are run. You can study more about the life cycle of JSP in subsequent
section 4.3.

4.3 JSP LIFE CYCLE


In this section, you will go through the life cycle of JSP and see how a JSP page is
displayed. When the JSP is first accessed, it is translated into a corresponding servlet
(i.e. java class) and compiled, then JSP page services request as a servlet. The

Figure 8: The steps of a JSP page processing 5


Web Application
Developmeent using J2EE translation of JSP pagge is done by the JSP P engine of the underlyying web
container/seervlet containner (e.g. Toomcat). Figuure-8 shows how a JSPP page is
processed.

The life cyccle of JSP paage is controllled by three m


methods i.e. jspInit(),
j _jsppService()
and jspDestroy().

jspInit() - The jspInit()) method is called only once duringg life cycle of o a JSP.
Similarly, servlet
s also hhas an init() method whoose purpose is i the same as a that of
jspInit(). jspInit() methhod is used tot initialize oobjects and variables
v thatt are used
throughout the life cyclee of JSP. This method is defined in JspPage
J interfface. This
method is innvoked whenn the JSP pagge is initializeed. It has no parameters, returns
r no
value and thhrown no exceeptions.
The signature of the methhod is as folloows:
pub
blic void jspInnit() { // Iniitialization coode }

_jspServicee() – _jspSerrvice() is the method that iis called everry time the JS
SP page is
requested to serve a requesst. This method is defined in the
javax.servleet.jsp.HttpJspP
Page interfacce. This metthod takes HttpServletReq
H quest and
HttpServletR Response objjects as an arrgument. Thee _jspService() method coorresponds
to the body of the JSP ppage. It is deffined automaatically by thee processor annd should
never be reddefined by yoou. It returns no value. Thee underscore (‘_’) signifies that you
cannot override this methhod. The sign nature of the method
m is as follows:
f

public void _jspService


(
javax.servvlet.http.HttpSServletRequest request,
javax.servvlet.http.HttpSServletResponnse response))
throws javvax.servlet.SeervletExceptioon, java.io.IO
OException
{
// servicess handling codde
}

jspDestroy(()- The jspDeestroy() is invvoked only onnce when the JSPJ page is abbout to be
terminated. It is synonyymous to thee destroy() m method of a servlet. Youu have to
override jsp
pDestroy() if you need to perform any cleanup, suchh as releasingg database
connectionss or closing oppen files. Thee signature off the method is as follows:

pub
blic void jspD
Destroy(){ // cleanup code }

Following figure-9
f show
ws the life cyclle of JSP page:

Figure 9: life cycle off JSP Page

6
Java Server Pages
4.4 JSP API

The JSP technology is based on JSP API (Application Programming Interface) that
contains two packages such as javax.servlet.jsp and javax.servlet.jsp.tagext. In
addition to these two packages, JSP also needs two packages of servlets such as
javax.servlet and javax.servlet.http. Both packages provide interfaces and classes for
writing servlets. You have already studied this in Block 1 Unit 2 of this course.

Package javax.servlet.jsp
The javax.servlet.jsp package has two interfaces such as HttpJspPage and JspPage and
four classes such as JspEngineInfo, JspFactory, JspWriter and PageContext. These are
as follows:

Interface Description
JspPage The JspPage is the interface that all JSP servlet classes must implement.
The JspPage interface has two methods, JspInit and JspDestroy. The jspInit
method is similar to the ‘init’ method in the javax.servlet.Servlet interface.
The jspDestroy method is analogous with destroy method of the
javax.servlet.Servlet interface. You have studied both the methods in
section 4.3 of this Unit. JSP developers rarely make full use of these two
methods.
HttpJspPage The HttpJspPage interface directly extends the JspPage interface. Each JSP
page implements this interface. It supports only one method _jspService().
The _jspService() method is already described in life cycle of JSP in
section 4.3 of this Unit.
Class Description
JspEngineInfo The JspEngineInfo is an abstract class that provides information of the
current JSP engine.
JspFactory The JspFactory is an abstract class that defines a number of factory
methods available to a JSP page at runtime for the purposes of creating
instances of various interfaces and classes used to support the JSP
implementation.
JspWriter The jspWriter class is derived from the java.io.Writer class. This is the
normal mechanism for JSP pages to produce output to the response. No. of
methods are defined in this class such as print( ) and println( ).
PageContext The PageContext class is an abstract class. It extends JspContext to provide
useful context information when JSP technology is used in a servlet
environment. This class provides methods that are used to create other
objects. For example, getServletConfig() returns a ServletConfig object
and getServletContext() returns a ServletContext object.

Apart from these interfaces and classes, the two exception classes: JspException and
JspError are also defined in javax.servlet.jsp package of JSP API. JspException is the
base class for all JSP exceptions. For details, please refer to the following link:
https://docs.oracle.com/cd/E17802_01/products/products/jsp/2.1/docs/jsp-2_1-
pfd2/javax/servlet/jsp/package-summary.html

Package javax.servlet.jsp.tagext
The javax.servlet.jsp.tagext encompasses classes and interfaces for the definition of
JSP Tag Libraries. The use of this package is defined in the creation of custom tag
under the section 4.5.1(taglib directives) of this unit. The interfaces in the

7
Web Application
Development using J2EE javax.servlet.jsp.tagext package are BodyTag, IterationTag, Tag, and
TryCatchFinally. The classes are defined in this package such as BodyContent,
BodyTagSupport, PageData, TagAttributeInfo, TagData, TagExtraInfo, TagInfo,
TagLibraryInfo, TagLibraryValidator, TagSupport, TagvariableInfo and VariableInfo.
You know more about the package details; please refer to the following link:
https://docs.oracle.com/javaee/5/api/javax/servlet/jsp/tagext/package-summary.html

4.5 COMPONENTS OF JSP


In this section, we are going to learn the components of JSP that make up a JSP page.
There are three types of JSP components such as Directives, Scripting and Action.
All the components are to be discussed in detail in the following sections:

4.5.1 Directives
Directives have great use as it guides the JSP container for translating and compilation
of JSP page. Directives control the processing of an entire JSP page. It appears at the
top of the page. Using directives, the container translates a JSP page into the
corresponding servlet. They do not directly produce any output. A directive
component comprises one or more attributes name/value pairs. Directives are defined
by using <%@ and %> tags. The syntax of Directive is as under:
<%@ directive attribute = “value” %>
There are three types of directives used in JSP documents: page, include and taglib.
Each one of these directives and their attributes is defined in the following sections:
The page Directive
The page directive defines attributes that apply to an entire JSP page, such as the size
of the allocated buffer, imported packages and classes/interfaces, and the name of the
page that should be used to report run time errors. The page Directive is a JSP element
that provides global information about an entire JSP page. This information will
directly affect the compilation of the JSP document. The syntax of JSP page directive
is as under:
<%@ page attribute = “value” %>
The following are the different properties that can be defined by using page directive:
Attribute Description
Language= “scripting This attribute outlines the language that will be used to
language” compile the JSP document. By default, it is java language.
import= “import list” This attribute defines the names of packages.
session= “true|false” It specifies whether or not the JSP document participates in
HTTP session. The default is true.
extends= “classname” This attribute states the name of the parent class that will be
inherited by the generated servlet. It is rarely used.
buffer= “none|size in kb” The default value is 8kb. It specifies the size of ‘out’ buffer.
autoFlush= “true|false” The default is true. It means that the out buffer will be
automatically flushed when full. If it is false, it will be
raised as an exception when the buffer is full.
Info= “text” If this attribute is used, the servlets will override the
getServletInfo() method.
errorPage= This attribute defines the relative URL to JSP document that
“error_page_url” will handle the exception.
isErrorPage= “true|false” This attribute indicates that the current page can act as an
error page for another JSP page. The default value is false.
isThreadSafe= The default value is true. It indicates that the page can
“true|false” service more than a request at a time. When it is false, the
SingleThreadModel is used.
8
Java Server Pages
An example of the use of page directive is as follows:
<%@ page import=”java.io.*, java.util.Date” buffer=”16k” autoFlush=”false” % >
<%@ page errorPage=”error.jsp” %>

You can specify one or more page directives in your JSP document. In the above
example, first page directive statement instructs the web container to import java.io
package and java.util.Date class. It also instructs the web container to set buffer size
to 16k and turn off autoflushing. The second page directive statement defines a name
of error page which is used for handling errors.

The include Directive

JSP include directive is used to include files such as HTML, JSP into the current JSP
document at the translation time. It means that it enables you to import the content of
another static file into a current JSP page. The advantage of using an include directive
is to take advantage of code re-usability. This directive can appear anywhere in a JSP
document. The syntax of include directive is as follows:

<%@ include file = “relative URL” %>

Note: Relative URL only specifies the filename or resource name, while absolute
URL specifies the protocol, host, path, and name of the resource name.
Consider the following example for include Directive. In this example, there are two
files: an HTML file, and another is a JSP file. You can create both files but run only
JSP file and the result is displayed like the figure-5.
Source code for header.html:
<html> <body>
<h2>Indira Gandhi National Open University</h2>
<h4>The text is from Header File</h4>
</body></html>

Source code for index.jsp:


<html><body>
<h3>Example of include directive</h3>
<%@ include file= "header.html" %>
</body></html>

The output of the above program is shown in the following figure-10:

Figure 10: Example of Include Directive

The taglib Directive

This directive allows users to use Custom tags in JSP. A custom tag is user-defined
tag. The custom tag eliminates the need for scriptlet tag. In this section, you will learn
9
Web Application
Development using J2EE about the creation of custom tag libraries in Java Server Pages. It is a reusable code in
a JSP page and tag library is a collection of custom tags. The taglib directive has the
following syntax:

<%@ taglib uri=”tagLibraryURI” prefix=”tagPrefix” %>

The uri (Uniform Resource Identifier) attribute defines an absolute or relative uri of
tag library descriptor (TLD) file, and the prefix attribute defines the string that will
identify a custom tag instance.
There are four components which you need to use customs tags in a JSP page:

1) The Java file that does the processing or Tag handler class
2) Tag Library Descriptor (TLD) file that points from JSP to Java file
3) JSP file that contains the tag being used
4) Deployment descriptor file (web.xml) that states the server where to find the TLD
file
Tag Handler Class
It is a java class that defines the behaviour of the tags. This class must implement the
javax.servlet.jsp.tagext package.

Tag Library Descriptor (TLD) file


A tag library descriptor file is an xml document. It defines a tag library and its tags.
This file must be saved with a .tld extension to the file name. It contains <taglib> root
element and <tlib-version>, <jsp-version>, <short-name>, <tag> which all are sub
elements of the taglib element. The <tag> is the most important element in the TLD
file because it specifies the tag's name and class name. You can define more than one
<tag> element in the same TLD file.

Deployment Descriptor file (web.xml)


The deployment descriptor is an xml file that specifies the configuration details of the
tag. The most essential element for custom tag in web.xml file is <taglib-location>.
Using the web.xml, the JSP container can find the name and location of the TLD file.

JSP file
Once you have created tag handler java class, tag descriptor file, and defined
configuration details in deployment descriptor file, you have to write a JSP file that
uses the custom tag.

The following are five easy steps for building a JSP application that uses custom
tags:

Step-1: Write, compile and deploy a java class called MyCustomTag.java, which is
given in the following source program. The class file must be placed in the directory,
say ‘customTag’ under the WEB-INF/classes directory like the figure 11. The
directory ‘customTag’ is user defined directory.

Source Code for simple CustomTag


package customTag;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class MyCustomTag extends TagSupport
{
public int doEndTag() throws JspException
10
Java Server Pages
{
JspWriter out = pageContext.getOut();
try
{ out.println("Hello!! Creating a First Custom tag"); }
catch(Exception e) {}
return super.doEndTag();
}
//doEndTag()
}
//main class

Figure 11: classes directory structure for Custom Tag in Tomcat

Step-2: Create a TLD file named taglib.tld as shown in following source program and
save it in WEB-INF directory.

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library


1.2//EN" "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version></jsp-version>
<short-name></short-name>
<tag>
<name>myTag</name>
<tagclass>customTag.MyCustomTag</tagclass>
</tag>
</taglib>

Step-3: Create a JSP file named SimpleCustomTag.jsp from the following source
code and save it in the directory say ‘JSP’ like the figure 12 under your ‘webapps’
folder.

<html><body>
<%@ taglib uri="/myTLD" prefix="easy" %>
<easy:myTag />
</body></html>

Figure 12: File structure for Custom tag in JSP

Step-4: Edit your deployment descriptor (web.xml) file. To use custom tags, you must
specify a <taglib> element in your deployment descriptor file. It is a large file; you
can place the following code under the <web-app> root element.

11
Web Application
Developmeent using J2EE <jsp-config>>
<taglib> <taaglib-uri> /myyTLD </tagliib-uri>
<taglib-locatio
< on>/WEB-IN NF/taglib.tld </taglib-locati
< on>
</taglib>
</jsp-configg>

Step-5: Starrt server let uus say Tomcaat (if you are using this). Open
O web broowser and
run the
t JSP pagge usinng the URL as
http://localhhost:8080/ex/JJSP/SimpleCu ustomTag.jspp. The followiing screen coomes as an
output for a simple custoom tag.

Fiigure 13: A sim


mple JSP Custtom Tag pagee

When a useer requests to a JSP page, the t JSP contaainer first cheecks the taglibb directive
and gets thee taglib ‘uri’ attribute. Onn the basis off this, JSP coontainer lookks into the
ng and gets the name of
web.xml filee to find tagliib location annd continues tthe processin
tag. After getting
g the naame and locattion of TLD file, it obtainns the java class. Now,
the JSP conttainer loads thhe class for cuustom tag andd continues thhe processingg.

4.5.2 Scrripting elem


ments

JSP scriptinng elements iis a mechanissm for embeddding java coode fragmentts directly
into a HTM
ML page. Therre are three sccripting languuage elements such as decclarations,
expressionss, scriptlets innvolved in JSP scripting. Each
E of these scripting elem ments has
an appropriaate location in the generatted servlet. Inn this section,, you will loook at these
elements annd how togethher they will result
r in a com
mplete servlett.

JSP Scriptingg Element Descriptionn


Declarations
D To declare the
t variables and
a methods for the page.

Expressions
E To return a value from thhe scripting coode as a Strinng to the
page.
Scriptlets To execute java source ccode

Declaration
ns
Declarations are used to declare the variables
v and mmethods that you can use in
i the JSP
document. The
T declaratiion part is innitialized wheen the JSP document
d is initialized.
i
After the deeclarations haave been inittialized, they are availablee to other exxpressions,
declarationss and scriptletts. A declaraation starts wiith <%! and ends with %>. % It has
the followin
ng syntax:
<%! declarationn %>
Following iss an example for JSP Decllarations:

<%! x=
=0; %> // x is an integer typpe variable
<%! int x, y, z; %> /// x, y, z is an integer type variable
v
n String(“JSSP”); %> // string type variable declaraation
<%! Strring name = new
<%! pubblic String geetName() { return name; } %> //methodd declaration
12
Java Server Pages
Expressions
The code placed within JSP expression element is written to the output stream of the
response. You need not write out.print() to write data. Expressions are evaluated at
request time, and the result is inserted where the expression appears in the JSP file.
The syntax of the expression is as follows:

<%= expression %>


Note: Do not end your statement with a semicolon in case of expression tag.
Here is an example of expressions:

<%! int x, y, z; %> // x, y, z is an integer type variable


<%
x=5, y=5;
z = x/y;
%>
<%=z %>

For example, to show the today date and time:


<%= new java.util.Date() %>

Scriptlets
A scriptlet element is used to execute java source code in JSP. It is executed at the
request time and makes use of declarations, expressions and Java Beans. You can
write scriptlets anywhere in a page. It contains a valid java statement within the <%
and %> tag and gets inserted into the _jspService() method of generated servlet. The
syntax of the scriptlet is as follows:

<% // java code %>


Note: Semicolon at the end of scriptlet is necessary.

The following example will demonstrates how to add two numbers and print this
result on output screen using Scriptlets.

<html><body>
<% int num1 = 5, num2 = 15, sum;
sum= num1 + num2;
out.println("sum= "+sum);
%>
<footer><hr>&copy;2020 SOCIS, IGNOU</footer>
</body></html>

Output of the above program is as follows:

Figure 14: Output screen for Scriptlets example


13
Web Application
Development using J2EE ☞ Check Your Progress 1
1. Write the basic steps for processing JSP request.
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_____________________________________________
2. Write a JSP program for Fibonacci Series.
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_____________________________________________

3. Write a JSP program using Scriptlets that add numbers from 1 to 10 and prints
this result.
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_____________________________________________

4.5.3 Action Elements


In the previous section, you have already learnt about two JSP components i.e.
Directives and Scripting elements. Now, you will learn about the third JSP component
i.e. Action elements or Standard actions tags that can be embedded in a JSP program.
JSP provides many standard action tags that you can use for specific tasks such as
add java bean objects in JSP document, forward the request to another resource or
include other resources in current resource, etc. At the compile time, they are replaced
by java code. The list of some important standard JSP action elements are given
below:

JSP Action Description


<jsp:useBean> To get the java bean object from given scope or to create a new object
of java bean.
<jsp:getProperty> To get the property of a java bean, used with jsp:useBean action.
<jsp:setProperty> To set the property of a java bean object, used with jsp:useBean
action.
<jsp:param> To define the name/value pair of parameter to be passed to
<jsp:useBean>, <jsp:forward>, <jsp:include> and <jsp:plugin> tag.
<jsp:forward> To forward the request to another resource.
<jsp:include> To include a resource at runtime, the recourse may be HTML, JSP or
any other file
<jsp:plugin> To embed another component such as applet in JSP

Before you start learning about how you can add Java Bean in the JSP page, you must
look at what a bean is. A Java Bean is a java class that maintains some data called
properties and has a no-arguments constructor. It is reusable component that work on
any Java Virtual Machine. To create Java Bean, you must create a java class that
implements java.io.Serializable interface and uses public get/set methods to show its
properties.
<jsp:useBean> Action
This action is used to include an instance of java bean within JSP document. The
syntax of first JSP standard action is as follows:

14
Java Server Pages
<jsp:useBean id=”name”
scope=”page | request | session | application”
class=”className” >
body
</jsp:useBean>

In the above syntax, ‘id’ represents the name of the object and this attribute is
necessary. The ‘class’ attribute represents the fully qualified class name of the object.
The class name is case sensitive. The ‘scope’ attribute represents the life of the object.
It may be page, request, session or application. It means how long the object is
available for a single user or all application users. JSP provides different scope for
sharing data between web pages. These are:
• Page - ‘page’ scope means the JSP object can be accessed only from within the
same page where it is created. By default, it is page. JSP implicit objects out,
exception, response, pageContext, config and page have ‘page’ scope.
• Request – Beans with request scope are accessible only within pages that are
processing the same request for that the object was created in. Objects that have
request scope are most often used when you need to share information between
resources that is pertinent for the current request only. Only Implicit object
request has the ‘request’ scope.
• Session – This object is accessible from any JSP within the same session.
Implicit object session has the ‘session’ scope.
• Application - This object is accessible from any JSP within the same web
application. Implicit object application has the ‘application’ scope.

<jsp:setProperty> Action
The second JSP standard action is used to set the Java Beans property value. The
syntax for this action is as follows:

<jsp:setProperty name=”beanName” property=”propertyName” />

In the above syntax, ‘name’ attribute represents the name of the bean instance defined
by <jsp:useBean> action and ‘property’ attribute represents the bean property for
which you want to set a value.

<jsp:getProperty> Action

This final bean handling action is <jsp:getProperty> which gets the named property
and outputs its value for inclusion in the page as a String. The syntax for this action is
as follows:

<jsp:getProperty name=”name” property=”propertyName” />

In the above syntax, ‘name’ attribute represents the name of the bean instance defined
by <jsp:useBean> action and ‘property’ attribute represents the bean property for
which you want to get a value.

The following is a simple Java Bean example that stores University details:

Let’s create a Java Bean named university.java and place class file under WEB-
INF/classes/bean1 directory.

15
Web Application
Development using J2EE Source code for university.java

package bean1;
public class Iguniversity
{
public IGuniversity()
{
}
private String uname; //define university name
private int year; //define year variable
private String school;
/* ------ getMethod and setmethod for university name--- */
public String getUname()
{
return uname;
}
public void setUname(String uname)
{
this.uname = uname;
}

/* ‐‐‐‐‐‐ getMethod and setmethod for Year‐‐‐ */

public int getYear()


{
return year;
}
public void setYear(int year)
{
this.year= year;
}

/* ------ getMethod and setmethod for School--- */


public String getSchool()
{
return school;
}
public void setSchool(String school)
{
this.school = school;
}
}

You can access the properties of the Java Bean from the following JSP file named as
universitydetails.jsp.

<jsp:useBean id="universityinfo" class="bean1.IGuniversity" scope="session" />


<jsp:setProperty property="*" name="universityinfo"/>

You have entered following university details:<br>


<jsp:getProperty property="uname" name="universityinfo"/><br>
<jsp:getProperty property="year" name="universityinfo" /><br>
<jsp:getProperty property="school" name="universityinfo"/><br>

Now, you can create a JSP file named ‘beanexample.jsp’ for putting values to the
bean.

16
Java Server Pages
<html><head><title>useBean, getProperty and setProperty example </title></head>
<form action="universitydetails.jsp" method="post">
University Name: <input type="text" name="uname"><br>
Year <input type="text" name="year"><br>
School: <input type="text" name="school"><br>
<input type="submit" value="Go"> </form> </html>

Now, you can run ‘beanexample.jsp’ file in your browser using the URL as
http://localhost:8080/ex/JSP/beanexample.jsp and get the following screen for the
above programs.

Figure 15: Input Screen for Bean Example

The following output screen is as follows for the University details program:

Figure 16: Output Screen for a Java Bean Example

<jsp:param>
The <jsp:param> action is used within the body of <jsp:include> , <jsp:forward> and
<jsp:plugin> tag to supply extra name/value pair of parameter. Following is the
syntax of the <jsp:param> action :

<jsp:param name=”paramName” value=”paramValue” />

In the above syntax, name attribute defines the name of parameter being referenced
and value attribute represents the value of named parameter.

<jsp:include>

The <jsp:include> action is used to include additional static or dynamic resources in


current JSP document at run-time. The static resource is inserted at the translation
time and the dynamic resource at the request time. In the previous section, you have
already studied the static include i.e. include directive.
The syntax for this action is as follows:
17
Web Application
Development using J2EE <jsp:include page=”relativeURL” flush=”true” />
OR
<jsp:include page=”relativeURL” flush=”true” >
<jsp:param ……/>
</jsp:include>
In the above syntax, page attribute defines the path of the resource to be included and
flush attribute indicates whether the buffer is flushed. It is an optional parameter. The
first syntax is used when <jsp:include> does not have a parameter name/value pair. If
you want to pass the parameter to the included resource, use the second syntax. The
<jsp:param> tag allows parameter to be appended to the original request.
<jsp:forward>
The <jsp:forward> action is used to terminate the current execution of JSP page and
forwarding the client request to another URL, whether it can be an HTML file, JSP or
Servlet within the same application at the run time. The <jsp:param> tag is used with
<jsp:forward> action element to passing parameter. The syntax for <jsp:forward>
action tag is as follows:
<jsp: forward page=”relative_url” flush=”true” />
OR
<jsp: forward page=”relative_url” flush=”true” >
<jsp:param ……/>
</jsp: forward >
<jsp:plugin>
The <jsp:plugin> action element enables the JSP to include a bean or a applet in the
client page. The <jsp:param> is also used with <jsp:plugin> action element to send
parameters to Applet or Bean. It has the following syntax:
<jsp:plugin type=”pluginType” code=”classFile”codebase=”relativeURLpath>
<jsp:param ……/>
</jsp: plugin >
In the above syntax, type attribute indicates the type of plugin to include in JSP page,
code attribute represents the name of class file and codebase attribute is the path
where the code attribute can be found.

4.6 JSP IMPLICIT OBJECT

JSP Implicit objects or predefined variables are the java objects that you can use
directly without being declared first in scriptlets of JSP document. JSP implicit
objects are created during the translation phase of JSP to the servlet. These variables
are automatically available for the JSP page developer to use. These nine implicit
objects are summarized in the following table:
Table: JSP Implicit Objects
S.No. Implicit Object Type Scope
1 out javax.servlet.jsp.JspWriter Page
2 request javax.servlet.HttpServletRequest Request
3 response javax.servlet.HttpServletResponse Page
4 session javax.servlet.http.HttpSession Session
5 application javax.servlet.ServletContext Application
6 page javax.servlet.jsp.HttpJspPage Page
7 pageContext javax.servlet.jsp.pageContext Page
8 config javax.servlet.http.servletConfig Page
9 exception java.lang.throwable Page

18
Java Server Pages
4.6.1 out Object

This implicit object is a simple and frequently used in scriptlet of JSP page. You call
either its print() or println() method to send output to the client browser. For example,
<% out.println(“ JSP is an easy language”); %>
In the above code, you use the implicit out object that represents
javax.servlet.jsp.JspWriter class.

4.6.2 request Object


The request object is an instance of HttpServletRequest interface. This object is used
to retrieve the values that the client browser passed to the server during HTTP request,
such as cookies, session, headers information, or parameters associated with the
request. The most common use of request object is to access queries by calling the
getParameter() and getQueryString() method.

For example: <% String name=request.getQueryString(); %>

You can find another example of request.getParameter() method in Database


Connectivity section of this Unit.

4.6.3 response Object


The response object is an instance of HttpServletResponse interface. It is used to add
or manipulate response such as redirect response to another resource, send error etc.
Using response object, a reply is sent back to the client browser.

<% response.sendRedirect(“http://www.ignou.ac.in”);%>

For example, when the above code is executed, the sendRedirect() method of the
javax.servlet.HttpServletResponse to redirect the user to IGNOU website.

4.6.4 session Object


The session object is represented by the javax.servlet.http.HttpSession interface. This
object is most often used when there is a need to share information between requests
for a single user. It is used to store the user’s data to make it available on other JSP
pages until the user session is active. This object is used to track the user information
in the same session.
4.6.5 application Object
The application object is an instance of javax.servlet.ServletContext. The
ServletContext object is created only once by the web container when application or
project is deployed on the server. This object is used to get initialization parameter
from configuration file. There is one ServletContext object for each web application
per Java Virtual Machine.
4.6.6 page Object
The page object is an instance of javax.servlet.jsp.HttpJspPage interface. The page
object is just as it sounds, a reference to the current instance of the JSP page. The page
object is a synonym for ‘this’ reference and is not useful for programming language.

19
Web Application
Development using J2EE 4.6.7 pageContext Object
The pageContext object is an instance of javax.servlet.jsp.PageContext. It is used to
represent the entire JSP page. The pageContext object is used to set, get and remove
attribute of the JSP page.
It provides a single point of access to many page attributes such as directives
information, buffering information, errorPageURL and page scope. It is also provide a
convenient place to store shared data. This object stores references to the request and
response objects for each request. The PageContext class defines several fields,
including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and
APPLICATION_SCOPE, for identifying the four scopes of attributes.
4.6.8 config Object
The config object is an instance of javax.servlet.http.servletConfig. The container for
each jsp page creates it. This object is used to get the configuration information of the
particular JSP page by using the getServletConfig method. This can be useful in
retrieving standard global information such as the paths or file locations.

4.6.9 exception Object


This implicit object only exists in a defined errorPage. It contains reference to
uncaught exception that caused the error page to be invoked. This object is assigned to
the Throwable class, which is the super class of all errors and exceptions in the java
language. You can find a complete description of errorPage mechanism including the
use of this exception object in section 4.8 (exception handling in JSP) of this unit.

☞ Check Your Progress 2

1. What is the purpose of action elements in JSP?


______________________________________________________________
______________________________________________________________
______________________________________________________________
__________________________________________

2. Write and explain the various bean scopes.


______________________________________________________________
______________________________________________________________
______________________________________________________________
__________________________________________

3. Explain the application implicit object with example.


______________________________________________________________
______________________________________________________________
______________________________________________________________
__________________________________________

4.7 AN INTRODUCTION TO JSP STANDARD


TAG LIBRARY

In the section 4.5.2 (Scripting elements), you have learnt about the scriptlets in JSP
pages to generate dynamic content. Sometimes it creates readability issues and made
it difficult to maintain the JSP pages. To overcome this problem, Custom tags have
been introduced. Although custom tags are better choice than scriptlets but web
20
Java Server Pages
developers need to be consumed a lot of time in coding and testing such tags. A new
feature named JSP Standard Tag Library (JSTL) has been introduced for web
developers to develop web pages in a better manner.
The Java Server Pages Standard Tag Library is a collection of useful JSP tags to
simplify the JSP development. The JSTL tags can be classified as per their features
such as Core Tags, Formatting tags, SQL tags, XML tags and JSTL Functions. For
JSTL 1.1 Tag details, refer to the link:
https://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/. To begin working with JSP
JSTL tags, you need to first install the JSTL library. If you are using the Apache
Tomcat, then use this link:
https://tomcat.apache.org/taglibs/index.html to download the library.
There are different types of JSTL tags to include in JSP document as per your
requirement.

JSTL Core Tags


The core group of tags are the most commonly used JSTL tags. To use these tags in
JSP, you should have used the following taglib:
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
JSTL Formatting Tags
The Formatting tags provide support for message formatting, number and date
formatting. To use these tags in JSP, you should have used the following taglib:
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
JSTL XML tags
These tags provide support for creating and manipulating the XML documents. The
JSTL XML tag library has custom tags used for interacting with the XML data. This
includes parsing the XML, transforming the XML data and the flow control based on
the XPath expressions. To use these tags in JSP, you should have used the following
taglib:

<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>

JSTL Functions
JSTL includes a number of standard functions; most of them are common string
manipulation functions. To use these tags in JSP, you should have used the following
taglib:
<%@ taglib prefix = "fn" uri = "http://java.sun.com/jsp/jstl/functions" %>

JSTL SQL Tags


The JSTL SQL tag library provides tags to access the database such as Oracle,
mySQL, or Microsoft SQL Server. To use these tags in JSP, you should be used the
following taglib:
<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
There are two important JSTL SQL tag such as <sql:setDataSource> and <sql:query>
which are described below:

21
Web Application
Development using J2EE JSTL <sql:setDataSource> tag
This tag is used to create a DataSource configuration that may be stored into a
variable that can be used as an input to another JSTL database-action. You can use
this tag like the following:

<sql:setDataSource var="name_of_variable" driver="name_of_driver"


url="jdbc_url" user=" " password=" "/>

In the <sql:setDataSource> tag, var attribute is optional and it specifies the variable's
name, which stores a value of the specified data source. The dataSource attribute is
optional that specifies the data source. The driver attribute defines the JDBC driver
class name and url attribute specifies the JDBC URL associated with the Database.
Both the user and password are the optional attributes that specify the JDBC
database user and password name.

JSTL <sql:query> tag

This tag is used for executing the SQL query written into its body or through the sql
attribute. For example:

<sql:query dataSource="${db}" var="name_of_variable">


SELECT ProgCode, Prname from programme;
</sql:query>

In the <sql:query> tag, var is a required attribute that specifies the name of the
variable to stores a value of the query result, sql attribute specifies the statement of
SQL query to execute and dataSource is an optional attribute specifies the data
source.

4.8 EXCEPTION HANDLING IN JSP

When you are writing a JSP code, there is a chance that you might make coding
errors that can occur in any part of the code. In Java Server Pages (JSP), there are two
types of errors. The first type of error comes at translation or compilation time when
JSP page is translated from JSP source file to Java Servlet class file. The second type
of JSP error which is called a request time error occurs during run time or request
time. These run time errors result in the form of exception. Exception Handling is the
process to handle runtime errors.

There are three ways to perform exception handling in JSP. They are:
• errorPage and isErrorPage attributes of page directive
• <error-page> tag in Deployment Descriptor file
• try and catch block in Scriptlets

4.8.1 Using page directive attributes


You have already learned about the page directive in section 4.5.1 of this Unit. The
page directive defines attributes that apply to an entire JSP page. The two attributes of
the page directive, such as ‘errorPage’ and ‘isErrorPage’ and one implicit object
‘exception’ are useful in JSP exception handling.
The errorPage attribute

22
Java Server Pages
The errorPage attribute of page directive is used to specify the name of error page that
handles the exception. The error page contains the exception handling code
description for a particular page. The syntax of this attribute is as follows:

<%@ page errorPage=”relative URL” %>

The isErrorPage attribute


The isErrorPage attribute of page directive indicates whether or not the JSP page is an
errorPage. The default value of this attribute is false.

<%@ page isErrorPage=”true” %>

For exception handling, you need to create a simple JSP page and write only one
additional errorPage attribute of page directive at the top of the JSP page to make an
error page and set its value equal to the location of your JSP error page. In a similar
way, you can create another JSP page where an exception may occur. Here, you can
put first line of isErrorPage attribute of page directive at the top of the JSP page and
set its value equal to true and write the second line of code designates where the
thrown exception is being used.
For example, you have to create an ‘error.jsp’ named file which contains source code
for handling exception and the other page named ‘processPage.jsp’ file, where
exception may occur and define the errorPage attribute of page directive. The third
file inputPage.jsp is used for input values. This example is for dividing two values and
displaying the result.
Source code for inputPage.jsp
<html>
<head> <title>InputPage.jsp</title> </head>
<body>
<form action="processPage.jsp">
Enter Number 1<input type="text" name="num1"><br>
Enter Number 2 <input type="text" name="num2"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Source code for processPage.jsp

<%@ page errorPage="error.jsp" %>


<html>
<head> <title> procesPage.jsp </title> </head>
<body>
<%
String n1 = request.getParameter("num1");
String n2 = request.getParameter("num2");

int Var1 = Integer.parseInt(n1);


int Var2 = Integer.parseInt(n2);
int Var3 = Var1 / Var2;

out.println("First number = "+ Var1);


out.println("Second number = "+ Var2);
out.println("Division of two numbers are "+ Var3);

%>
</body></html>
23
Web Application
Development using J2EE Source code for error.jsp.

<%@ page isErrorPage="true" %>


<html>
<head>
<title>error.jsp</title>
</head>
<body>
Your page generate an Exception : <br>
<%= exception.getMessage() %>
</body>
</html>
Output of the above programs

When you run the above program code, it shows the following two screens one after
another. In the first screen (figure-17), there are two input box where you will input
two integer values and click on submit button. In the second screen (figure-18), the
browser displays the result after the division of two numbers.

Figure 17: Input Screen for entering values

Figure 18: Output Screen for division of two numbers

Now, you will run the above same program again and input any integer value in first
text box and zero in second text box and click on submit button. The program will
generate an Arithmetic Exception: division by zero. When you will input any float
value in any text box, then it will also generate exception.

Figure 19: Exception handling Screen


24
Java Server Pages
4.8.2 Using try and catch block in Scriptlets
If you want to handle exception within the current JSP page, you can also use the
standard java exception handling mechanism in the Scriptlets component of the JSP
page. For this, you can use try and catch clause in your source code. In try block, you
can write the normal code that might throw an exception. The catch block is used to
handle the exception. Both the try and catch clauses are written inside the scriptlets.
Unlike page directive, there is no need to write an error page for this mechanism.

You can use the try and catch block like the following manner:
<%
try { // code that thrown an exception }
catch (exception e) { // exception handler for exception occur in try block}

%>
The following program code is for handling exception using try and catch clause of
Java. In this program, normal coding is defined in try block and exception handling
code is in catch block. In try block, there are three integer variable x, y and z defined.
The variable x contains a value zero and y contains value 10. When the program tries
to divide the value of y by x then exception occurs. The program control flow is
preceded and displays only those states which are included in catch block.

Source Code for Exception handling through try and catch clause

<html>
<head><title> Exception handling through try and catch clause </title></head>
<body>
<%
try
{
int x = 10;
x = x/ 0;
out.println("Output = " + x);
}
catch (Exception e)
{ out.println("Error caught by Catch block : " + e.getMessage()); }
%>
</body></html>

Output of the program:

Figure 20: Output Screen for Exception handling through try and catch clause

4.8.3 Using <error-page> tag in Deployment Descriptor file


In the above section, you have learned about the page level exception handling in JSP
through page directive and try-catch mechanism in scriptlets. If you want to describe
the exception handling in the JSP page at the application level, you can use the <error-
25
Web Application
Development using J2EE page> tag element in the Deployment Descriptor file. The deployment descriptor is a
file named web.xml. It resides in the web applications under the WEB-INF/ directory.
This approach is better as you don’t need to use the page directive to declare the error
page in each JSP file. Making a single entry in the web.xml file serves the purpose.
You can specify either an <exception-type> element with the expected exception's
class name, such as java.lang.ArithmeticException or <error-code> element with an
HTTP error code value such as 500 with <location> element. The <location> element
states JSP container for path of the resource to show when the error occurs. If you
want to handle all the exceptions you need to specify the java.lang.Exception in the
exception type element.
To include a generic error page for all exceptions at application level in the following
way in web.xml file:

<error-page>
<exception-type>Exception</exception-type>
<location>/error.jsp</location>
</error-page>

If you want to handle exception using any specific error status code such as File not
found error 404, Server error 500, then you can specify <error-code> element instead
of <exception-type>. This is the best way to declare error page by using error-code
element in web.xml file. It is used as under:
<error-page>
<error-code>500</error-code>
<location>/jsp/error.jsp</location>
</error-page>

Here is the example for exception handling at the application level using <error-page>
element. The example code is very similar to the above-used example in page
directive option. For this example, four files are needed to run the program:

• inputPage.jsp file for input values (The code is same as described in the
example of page directive section 4.8.1)
• processPage.jsp for dividing two numbers and displaying the result. (You can
use the same code which is described in the example of page directive section
4.8.1 except the line which contains errorPage attribute of page directive).
• error.jsp file for displaying the exception (which is also the same as the
example defined in page directive option).
• web.xml file for specifying the <error-page> element.
Source code for web.xml: You can include the following code in your web
application under the WEB-INF/web.xml file. In this example, error.jsp file is placed
under the jsp/error.jsp folder in web application.

<web-app>
………
……….
<error-page>
<error-code>500</error-code>
<location>/jsp/error.jsp</location>
</error-page>
………..
</web-app>

26
Java Server Pages
Now, you can run the program as similar to the example of page directive section
4.8.1. In this way, you can handle the exceptions at page as well as application level.
Note: The page directive declaration overrides any matching error page
configurations in the deployment descriptor. Suppose the JSP page throws
java.lang.ArithmeticException and deployment descriptor has an exception-type
attribute for that exception, the web container invokes the page directive instead of
any URI specified in deployment descriptor (web.xml) configuration.

Check Your Progress 3

1. What is the use of JSTL tags in JSP?


______________________________________________________________
______________________________________________________________
______________________________________________________________
__________________________________________

2. What is JSP error page?


______________________________________________________________
______________________________________________________________
______________________________________________________________
__________________________________________

3. Explain the use of deployment descriptor in JSP.


______________________________________________________________
______________________________________________________________
______________________________________________________________
__________________________________________

4.9 DATABASE CONNECTIVITY

Database access is one of the important features of Web application. Java has its own
technology for database connectivity called JDBC (Java Database Connectivity).
JDBC provides a standard library for accessing a wide range of relational databases
like MS-Access, Oracle and Microsoft SQL Server. Using JDBC API, you can access
a wide variety of different SQL databases. The core functionality of JDBC is found in
java.sql package.
In the previous sections, you have seen examples on Scriptlets and Java Bean where
data is fetched from HTML form and displayed on JSP document in a static manner.
This section will provide you in-depth knowledge of data access, specifically insertion
and retrieval of data to/from a database.
Consider a table named as Student is created in Microsoft SQL Server database with
Roll No, Name and Course name. This table is used in both the following sections.
This section defines example for storing/retrieving data into/from a Microsoft SQL
Server using type-4 JDBC driver. You can run these programs on any web server such
as Tomcat. For running these programs, you need a JDBC driver in .jar form and
place them in lib directory under the web application.

4.9.1 Insert data in Database using JSP

Let us take an example: a JSP form named “Form.jsp” contains student’s details like
student enrolment no., student name and Programme name. When you submit these
details it access ‘actionPage.jsp’ document to store data into the Database.

27
Web Application
Development using J2EE Source Code for Form.jsp

<html>
<body>
<form name="form1" method="post" action="actionPage.jsp" >
<h3>Indira Gandhi Open University </h3>
<fieldset>
<legend><b>Student Details </b></legend>
Enrolment No.:<input name="srno" type="text" value="" size=9><br>
Student Name : <input name="sname" type="text" value="" size=15><br>
Programme : <input type="text" name="prg" value="" size=15> <br>
<input type="submit" value="Submit" />
</fieldset>
</form>
</body>
</html>

In the following source code, the first step is to get the data from ‘Form.jsp’ program
using request.getParameter() method. After connecting to Database, an insert query is
executed using executeUpdate() method. The program is written by using try and
catch clause of standard Java mechanism within JSP scriptlets and data connectivity
through the Type-4 driver of SQL Server.

Source Code for actionPage.jsp

<%@ page import="java.util.*" %>


<%@ page import="java.sql.*;" %>
<html>
<head><title>Insert data into database</title></head>
<body>
<h3>Insert data in Database using JSP</h3>
<table border=1>
<%
String rollNo = request.getParameter("srno");
String StuName = request.getParameter("sname");
String prgName = request.getParameter("prg");

Connection con = null; //create connection object


Statement stmt = null; // create statement object

// connection string using Type-4 Microsoft SQL Server driver


// you can also change the next line with your own environment
String url=
"jdbc:microsoft:sqlserver://127.0.0.1:1433;user=sa;password=poonam;DatabaseName=SOCI
S";
try
{
// load JDBC type-4 SQL Server driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = DriverManager.getConnection(url);
if (con != null)
{
stmt = con.createStatement();
//insert query
String rsql ="insert into student values("+rollNo+",'"+StuName+"','"+prgName+"'"+")";
//execute query

28
Java Server Pages
stmt.executeUpdate(rsql);
out.println("Your data is successfully stored in database");
}
if(con == null)
{
con.close(); // release connection
}
}
// end of try clause
catch(SQLException se){ out.print("SQL:"+se.getMessage());}
catch(Exception e){ out.print("Exception:"+e.getMessage());}
%>

When you run the ‘Form.jsp’ program, you will see the following screen (figure-21):

Figure 21: Input Form for storing data into database

In the above screen, when you will enter values then the following screen (figure-22)
will show you a message for data storage

Figure-22 : Data stored in persistent storage

4.9.2 Retrieve Data from Database using JSP

The following example gives you an illustration of how to retrieve data from the
Database. After execution of the above program, you have stored sufficient data into
Database. Now, you will execute the following code for retrieving the data from
Database. In this program, one additional ResultSet object is used for retrieving data
from select query. The data is retrieved from ResultSet object by using getXXX()
method such as getInt() and getString(). Note that if the column name is an integer
type, you should use the getInt() method instead of the getString() method.

29
Web Application
Development using J2EE Source Code for getData.jsp

<%@ page import="java.util.*" %>


<%@ page import="java.sql.*;" %>
<html>
<head><title>Retrieved data from database</title></head>
<body>
<h3> Retrieve Data from Database using JSP</h3>
<table border=1>
<%
Connection con = null; //create connection object
Statement stmt = null; // create statement object
ResultSet rs = null; // create ResultSet object

// connection string using Type-4 Microsoft SQL Server driver


// you can change the next line with your own environment
String url=
"jdbc:microsoft:sqlserver://127.0.0.1:1433;user=sa;password=poonam;DatabaseName
=
SOCIS";
Try
{
// load sql server JDBC type-4 driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

con = DriverManager.getConnection(url);

if (con != null)
{
stmt = con.createStatement();

// select SQL statement


String rsql ="select * from Student";

//execute query
rs = stmt.executeQuery(rsql);
%>
<tr><td>Roll Number</td><td>Student Name</td><td>Programme</td></tr>
<%
while( rs.next() )
{
%><tr>
<td><%= rs.getInt("RollNo") %></td>
<td><%= rs.getString("Student_Name") %></td>
<td><%= rs.getString("Programme") %></td>
</tr>
<%
}
}
if(con == null) {con.close();}
}
catch(SQLException se){ out.print("SQL:"+se.getMessage());}
catch(Exception e){ out.print("Exception:"+e.getMessage());}
%>

After running the above program, the following output screen (figure-23) is
displayed:
30
Java Server Pages

Figure 23: Display data from database

If you want to build your project using Oracle Database as back end, for this you can
change only port no and Oracle JDBC driver name in the above source code.

4.10 SUMMARY

In this unit you have gone through the components of ‘Java Server Pages’ which
makes the entire JSP document as directives, scripting and action elements. A ‘Java
Server Pages’ component is a type of Java servlet that is designed to fulfil the role of a
user interface for a Java web application. This Unit also introduced you the JSP API
on which the entire JSP relies. JSP API is a set of classes and interfaces that is used
for making JSP pages. JSP supports nine automatically defined variables which are
called implicit objects. When you write a JSP program, you might face a run time
error(s). For this JSP provides exception handling through the page directive element,
core java mechanism and deployment descriptor file.
Now, you are able to create a JSP document that can be used for a variety of purposes
such as retrieving information from a database, passing control between pages and
accessing Java Beans components.

4.11 SOLUTIONS/ANSWERS TO CHECK YOUR


PROGRESS

☞ Check Your Progress 1


1) When a client requests a JSP page, the browser sends a request to web server
which is forwarded to the JSP engine. If it is a new request from the client
then it is translated and compiled by the JSP engine into a servlet. Now,
servlet is ready for servicing the client request and generates response which
returns to the browser via web server. For the second time the same request
from the client (including browser and web server request) to JSP engine, the
JSP engine determines the request that the JSP-Servlet is up-to-date, if yes
then it immediately passes control to the respective JSP-Servlet for fulfilling
the request

2) <html><body>
<%! int n = 10, num1 = 0, num2 = 1; %>
<% for (int i = 1; i <= n; i++)
{
out.print(num1 + " , ");

31
Web Application
Development using J2EE int sum = num1 + num2;
num1 =num2;
num2 = sum;
}
%>
</body></html>

3) <html><body>
<% int sum=0;
for (int i = 1; i <=10; i++)
{ sum = sum+i ; }
out.print("sum ="+ sum);
%>
</body></html>

☞ Check your Progress 2

1) Standard actions are tags that affect the runtime behaviour of the JSP. These
JSP action tag is used to perform some specific tasks such as insert a file
dynamically, reuse external JavaBean components, forward the request to the
other page and generate HTML for Java Applet Plugin.
2) JSP provides different scope for sharing data between web pages. These are:

• Page - ‘page’ scope means the JSP object can be accessed only from
within the same page where it is created. By default, it is page. JSP
implicit objects out, exception, response, pageContext, config and page
have ‘page’ scope.
• Request – Beans with request scope are accessible only within pages
processing the same request that the object was created in. Objects that
have request scope are most often used when you need to share
information between resources that is pertinent for the current request
only. Only Implicit object request has the ‘request’ scope.
• Session – This object is accessible from any JSP within the same session.
Implicit object session has the ‘session’ scope.
• Application - This object is accessible from any JSP within the same web
application. Implicit object application has the ‘application’ scope.
3) It is used for getting initialization parameters and for sharing the attributes and
their values across the entire JSP application. For example,
<%=application.getServerInfo()%>, it returns the name and version of the
servlet container on which the servlet is running.

☞ Check your Progress 3

1) The ‘Java Server Pages’ Standard Tag Library (JSTL) contains a set of tags to
simplify the JSP development. JSTL provides tags to control the JSP page
behaviour and common tasks such as xml data processing, conditionals
execution, iteration and SQL tags.
2) A JSP error page is designed to handled runtime errors and display a
customized view of the exception. You can include an error page in your
application at page or application level. At page level, you can use page
directive or standard java mechanism options. At the application level, you
can only use an <error page> element of the deployment descriptor.

32
Java Server Pages
3) This file is an xml file whose root element is <web-app>. It is reside in the
web applications under the WEB-INF/ directory. You can configure JSP tag
libraries, welcome files, customizing HTTP error code or exception type. You
can use the <error-page> element in the deployment descriptor to specify
exception type or HTTP error code and location of the error page. The JSP tag
libraries can be defined using the <tag-lib> element of the deployment
descriptor.

4.12 REFERENCES/FURTHER READINGS

• Kathy Sierra, Bryan Basham, anddd Bert Bates ,“Head First Servlets and
JSP”, O'Reilly Media, Inc., 2008.
• Brown-Burdick et al., “Professional JSP”, Apress,2001.
• Budi Kurniawan , “Java for the Web with Servlets, JSP, and EJB: A
Developer's Guide to J2EE Solutions: A Developer's Guide to Scalable
Solutions” Techmedia , 2002.
• James Goodwill , “Pure JSP”, Techmedia, 2017.
• https://docs.oracle.com/cd/E17802_01/products/products/jsp/2.1/docs/jsp-
2_1-pfd2/javax/servlet/jsp/package-summary.html
• https://docs.oracle.com/javaee/5/api/javax/servlet/jsp/tagext/package-
summary.html
• https://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/
• https://tomcat.apache.org/taglibs/index.html
• list of drivers is available at : http://www.devx.com/tips/Tip/28818

33
UNIT 5 INTRODUCTION TO J2EE
FRAMEWORKS
Structure

5.0 Introduction
5.1 Objectives
5.2 Struts 2.x framework introduction
5.2.1 Struts 2 features
5.2.2 Struts2 core components
5.2.3 Working and flow of Struts 2
5.3 Introduction to Spring framework
5.3.1 Spring Framework
5.3.2 Spring MVC
5.3.3 Spring Boot
5.4 Introduction of Annotation
5.4.1 Built-in Java Annotations
5.4.2 Java Custom Annotations
5.5 Introduction of Hibernate with Java Persistence API
5.5.1 Hibernate Architecture
5.5.2 Hibernate Framework advantages
5.5.3 Java Persistence API
5.6 Summary
5.7 Solutions/ Answer to Check Your Progress
5.8 References/Further Reading

5.0 INTRODUCTION

In Units 1 to 4, we have already discussed J2EE and design patterns like MVC. In this
unit, we shall cover an introduction to various open-source J2EE frameworks.
Spring MVC framework is used for creating Web applications that utilize MVC
architecture. Apache Struts 2.x is a free open source framework that utilizes MVC
(Model-View-Controller) architecture to develop web applications. Spring Framework
offers an extensive programming model with the configuration for developing J2EE
applications. Spring Boot made on top of the spring framework and set stand-alone
Spring-based application much faster. Spring Boot applications require minimal
Spring configuration, so the development is much more comfortable.
Java Persistent API (JPA) is a specification that offers object-relational mapping
standards for managing java application relational database. It is used to persist,
access and collect data between java objects and relational database. JPA is a
specification, so it requires an implementation to perform any operation. JPA is
considered as a link between ORM and relational databases. ORM tools like
Hibernate, iBatis and TopLink implement JPA specifications for data persistence.
Annotations allow additional information about a program. They do not directly affect
the code behaviour they annotate. Annotations start with '@'. They are mainly used for
instructions during Compile time, Build-time and Runtime.

1
Introduction to J2EE
Frameworks 5.1 OBJECTIVES

This unit covers various J2EE open-source frameworks, and after going
through this unit, you will be able to:
• explain Struts 2.x framework,
• describe the concept of Spring, Spring MVC and Spring Boot,
• use Java Annotation in programming, and
• describe Java Persistent API using Hibernate.

5.2 STRUTS 2.x FRAMEWORK INTRODUCTION

Struts1 was an open-source framework to develop Java EE web applications. Struts1


was created by Craig McClanahan and given to the Apache Foundation. The
WebWork framework started developing independently by keeping base as the Strut
framework to provide more features to the developers. Still, later on, they reunited and
offered more robust Apache Struts 2. It extended the Java Servlet API and employed a
Model, View, Controller (MVC) architecture.

Apache Struts 2.x is a web application framework based on OpenSymphony. It


supports the complete application development cycle from the build to maintenance
phase built on the MVC design pattern. In a typical Java web application, a client calls
the server using a web form. Subsequently, the information pass to a Java Servlet that
produces an HTML-formatted response after interaction with the database.

Suppose the information passed to a JavaServer Pages (JSP) document offers similar
results after combining the HTML and Java code. But as these approaches mix the
application logic with the presentation so they are considered insufficient for larger
projects' maintenance. Strut2 is an MVC based framework where the application logic
is isolated from the user interface layer. The application logic interacts with the
database in the Model and is the lowest level of the pattern. The View is responsible
for exhibiting data in the form of HTML pages to the client. The Controller holds the
instances or the software code that passes the information between the Model and
View.
5.2.1 Struts 2 features

Various new features were added in Struts2, making it a more robust and enterprise-
ready framework for application development. Some of the features are as follows:
• POJO Forms and POJO Actions: Struts2 allows using any Plain Old Java
Object (POJO) to get the form input or Action class. The POJO prevents the
developers from interface implementation or inheritance of any class.

• Tag Support: Struts2 allows developers to use new tags where they have to
write less code and so they are code efficient form tags

• AJAX support: Struts2 supports the asynchronous requests using the AJAX
tags. AJAX is beneficial in improving the performance by only sending the
required field data and avoiding unnecessary information.

• Easy integration: Struts2 supports easy integration with other frameworks like
Spring, Tiles, hibernate etc.

2
• Template and Plugin support: Struts2 supports creating views with the help of Frameworks for J2EE
templates and supports plugins to improve performance.
• Profiling: Struts2 supports debugging through integrated debugging and
profiling and also has inbuild debugging tools.

• Easy to modify tags: Struts2 supports easy tag modification, requiring only
basic HTML, XML and CSS knowledge.

• Promote less configuration: Struts2 supports default values for the various
settings, which provide ease of access.

• View Technologies: Struts2 supports multiple view options like JSP,


Freemarker, Velocity etc.

The client sends the request in terms of "Actions" to the Controller as per the
specifications. The Controller demands the corresponding Action class to interact with
the respective model code. Finally, returns an "ActionForward" string containing
output page information to refer to the client.

5.2.2 Struts2 core components

The Model here is the business class where we write calls to business logic that
implement with actions. The Model is executed with interceptors to intercepts
specific purpose requests, and the dispatch servlet filter acts between the framework
and the client as the Front Controller.

The JSP/HTML represents the View, and it is a combination of result types and
results. The presentable MVC pattern expresses through JSP pages, Velocity
templates, or some other presentation-layer technology. The action class characterizes
the Controller. The Controller's job is to route the incoming HTTP request to the
appropriate action. It maps requests to actions. The value stack and OGNL are linking
with the other components through a common thread. Also, there are few other
components to store configuration information of web application, actions,
interceptors, results etc. Primarily, we need to create the following components for the
Struts2 project-

• Configuration Files: This component creates the configuration files to couple


the Action, View and Controllers like struts.xml, web.xml, struts properties.
There are two main configuration files i.e. struts.xml and struts.properties file,
where struts.xml file is used to override the applications default settings and
struts.proerties file is used to modify the behaviour of the framework.

The struts.xml file is created within the WEB_INF/classes directory and holds
the configuration information to be modified as actions. The struts.properties
file allows us to change the framework properties as per the requirements.

• Action: This component contains an action class that controls the user's
interaction, the Model, and the View and holds the complete business logic
and helps in the data processing. The Action class also responds to a user
request and allows the framework to return the result back to the user based
on the configuration file.

We can create an Action class using a simple action class, where we may use
any java class mandatorily containing an execute() method with the return
type of string. The second method to create Strut 2 Action class is
implementing action interface, and it also contains a execute() method
implemented by the implementing class. The third method is by extending the
3
Introduction to J2EE Action Support class and is the default implementation to provide various web
Frameworks application functionalities.
• Interceptors: This component is a part of the Controller, and it creates
interceptors or uses existing interceptors as required. These are like servlet
filters and execute before and after the processing of the request. Generally,
they perform common actions like session logging, validation etc., for
different actions.

The interceptors are pluggable, so we can remove them from the application
whenever we don't require any specific action. The removal doesn't require
redeploying but simply editing the struts.xml file by removing the entry.

• View: This component creates JSPs to control the user's interaction to take
input and display the final message.

• VALUESTACK: This component is a storage area used to store associated


data during processing, i.e. Temporary, Model, Action and Named objects.

• Object Graph Navigation Language (OGNL): This component provides the


functionality of retrieving VALUESTACK data and helps in converting data
types.

StrutsPrepareAndExecuteFilter works as the Front Controller in Struts 2, and it


implies that the Controller component acts first in the processing. Strut2 is Pull-MVC
based architecture where data storage in ValueStack and render by view layer.

The Servlet Filter Object scans and regulates each incoming request and tell the
framework which requests URLs map to which actions. XML-based configuration
files or, generally, the Java annotations used to perform this operation.

5.2.3 Working and flow of Struts 2

Let us discuss the various steps of flow as shown in figure 5.1

1 The client/user sends an HTTP resource request to the server. It reaches to


ServletContainer.

2 Web Container loads the web.xml and verifies the URL pattern if it matches; web
Container forwards the request to StrutsPrepareAndExecuteFilter (Front
Controller).

3 Based on the request URL mapping in struts.xml, the Filter dispatcher identifies
the appropriate action class to execute.

4 Before the Action class is executed, the request is passed through the stack of
interceptors. Interceptor allows common tasks defined in clean, reusable
components such as workflow, validation, file upload etc., that you can keep
separate from your action code.

5 The action class calls business logic. Action executed through the action methods
performing database operations of storing or retrieving data.

6 Processed data from business logic sent back to the Action class.

7 Based on the result, the Controller identifies the View rendered. Before the
response is generated, the stack of interceptors is executed again in the reverse
order performing clean-up etc

4
8 View rendereed to the user through the servlet
s controoller. Framewoorks for J2EE

Figure 5.1 Strut


S 2 flow

Strutts2 offers varrious methodss to create Acction classes,, own interceeptors for various
comm mon tasks an nd converterss for renderinng result pagges. These caan be configuured
using
g struts.xml or annotatioons and suppport many tags and OG GNL expression
languuage to help build
b web app
plications in Java.
J

☞ Check
C Your Progresss 1:

1.
1 What are the Struts2 coore componennts?

2.
2 Explain th
he operationaal flow of struuts2.

3.
3 What is thhe role of Acttion?

5
Introduction to J2EE
Frameworks

4. How are ValueStack and OGNL related to each other?

5. What is the role of interceptors in Struts2?

5.3 INTRODUCTION TO SPRING FRAMEWORK

The spring framework is a lightweight and open-source Java platform that provides
solutions to various technical problems through J2EE applications. Initially, the
Spring framework was released under the Apache 2.0 license, and Rod Johnson wrote
it in June 2003. Spring is assumed as a framework of frameworks that supports other
frameworks like struts, hibernate etc., through extensive programming and
configuration model.

Spring is lightweight, with the basic version of only around 2MB. The spring
framework is used to develop simple, reliable, and scalable Java applications. It
builds web applications on top of the Java EE platform with different extensions.

It uses various new techniques to make easier J2EE development and eliminate the
complications of developing enterprise applications. Different methods like
Dependency Injection, Inversion of Control, Plain Old Java Object (POJO) and
Aspect-Oriented Programming (AOP) are used to develop enterprise applications. It
mainly focuses on business logic and offers better options and easy development for
the Web applications compared to classic Java frameworks and Application
Programming Interfaces (APIs) like servlets, JSP, JDBC etc.
Spring framework offers many advantages, and the following are the list of benefits:
• POJO - It allows developers to use POJOs for enterprise-class applications
development, making them evade using an EJB container like an application
server instead of using a servlet container like Tomcat.
• Modular - It supports a large number of modules, and due to the modular
nature of Spring, the developer considers only the one they require for the
development.
• Integration - It offers good integration with existing frameworks like ORM,
logging frameworks and other view technologies etc.
6
• Testability - It offers simple application testing due to the use of POJOs. The Frameworks for J2EE
environment-dependent code moves directly into the framework for injecting
test data that supports dependency injection.
• Web MVC - It offers an elegant web MVC framework that delivers better
options than other web frameworks such as Struts etc.
• Central Exception Handling – It offers an API that translates technology-
specific exceptions into consistent, unchecked exceptions.
• Lightweight – It is lightweight compared to EJB containers and is very
efficient with low resources like memory and CPU to develop and deploy
applications.
• Transaction management - It provides proper scalability for the consistent
transaction management interface. It supports a global transaction to local
transactions by scaling up and down as required.

5.3.1 Spring Framework

The fundamental design principle of the Spring framework is "Open for extension,
closed for modification". To better understand the Spring Framework, let us first
discuss Dependency Injection (DI), Inversion of Control (IoC) and Aspect-oriented
programming (AOP).

In any java-based project, we use objects as a unified one to act as a working


application. For complex applications, we generally try to keep classes independent
from other java classes. Spring Dependency Injection helps in sticking together these
classes while keeping them independent, and this principle helps in reusability and
facilitates unit testing.

The dependency injection facilitates creating an object for someone else and allows
the direct use of dependency. Let us understand the vital concept of Dependency
Injection using an example.

Consider a car class containing various objects such as wheels, fuel, battery, engine
etc., and the car class is responsible for creating all dependent objects. If we decide to
change the TATA battery to an AMARON battery at any stage, we need to recreate
the car object with a new AMARON dependency.

We can change or inject the battery's dependencies at runtime rather than compile
time using Dependency injection. Dependency injection is acting as a middleware for
creating required objects and providing them to the car class.

There are typically three types of DI viz. constructor injection, setter injection,
interface injection, and they are responsible for creating and providing the objects to
the required classes. For any change in the object requirement, the DI will handle it
automatically without bothering the concerned class. The inversion of the control
principle behind DI states that class dependencies should be configured from outside
and not statically, i.e., should not be hard-coded.

Let us summarize the inversion of control and dependency injection as

• Inversion of Control – Inversion of Control is based on the abstraction principle of


object-oriented programming, where program objects depending not on
implementations but interfaces of other objects for the interaction.

• Dependency Injection – It is a structural design pattern and is a vital aspect of the


spring framework implementation of Inversion of Control. In this technique, Spring
7
Introducction to J2EE containers innject an objecct into other dependencies
d s and dependeencies are impplemented
Framewo orks at the objectt creation tim
me, i.e. the deependent objjects are creaated outside of a class
and then prrovide these objects throuugh a class refference with other
o classes..

Constructorr or setter m
method is useed to implem ment Dependeency injectionn through
parameter passing,
p and thhe Libraries or
o the Inversion of Controll containers aare used to
implement these
t approacches.

Another im
mportant conceept of the spriing frameworrk is Aspect-ooriented progrramming:

• Aspect-orieented prograamming – It is a program mming style where


w instead of OOPS
objects, thee aspects are used. An aspect
a is a class that span ns multiple application
nodes distributed across methods, claasses, object hierarchies
h annd object models, such
as logging,, security, trransaction ettc. AOP deffines specificc policies and a offers
modularity, and in this pparadigm, the program logiic is broken down
d into distinct parts
called concerns, enablinng the applicaation to adaptt to changes. The Springg Aspect-
oriented prrogramming module interrcepts an appplication throu ugh interceptoors to add
extra functioonality duringg method executing beforee or after methhod executionn.

The applicaation classes are separateed into differrent moduless through Deependency
injection an
nd cross-cuttiing concerns separate fromm the affecteed objects thhrough the
Aspect-oriennted program
mming.

Spring is modular
m and provides
p arou
und 20 modulles, and we canc use them based on
application requirementss. Let us disccuss a few esssential moduules as depicted in the
figure 5.2:

Figure 5.2
2: Spring Fram
mework

Core contaainer

It comprisess Bean moduule, Core moddule, Contextt module, andd Expression Language
module.

• Thee Core moduule offers the frameworkk's critical paarts, like Deependency
Injeection (DI) orr Inversion off Control (IoC
C) features.
• Thee Beans moodule offerss the BeanF Factory for the factoryy pattern
impplementation and is respoonsible for ccreating and managing thhe context
stru
ucture unit.

8
• The Context module offers an ApplicationContext interface to access any Frameworks for J2EE
object. It is built on a core and beans module base and inherits features from
the Bean modules to facilitate internationalization.
• The Expression Language module offers object graph querying and
manipulating at runtime through a powerful expression language.

Data Access/Integration Layer

It comprises the JDBC module, object-relational mapping module, Object/XML


mapping module, Java Messaging Service module and Transaction modules.

• The JDBC module offers an abstraction layer that eases access by reducing
tedious JDBC coding of manually connecting the database.
• The ORM module offers an integration layer supporting object-relational
mapping APIs, like JPA, JDO, Hibernate, iBatis etc.
• The OXM module offers an abstraction layer for linking Object/XML
mapping implementations for JAXB, XMLBeans, XStream etc.
• The Java Messaging Service (JMS) module offers features for creating,
sending receiving messages.
• The Transaction module offers transaction management for programmatic and
declarative classes with POJOs interfaces (Plain Old Java Objects).

Web Layer

The Web layer comprises the Web, Web-MVC, Web-Socket, and Web-Portlet
modules.
• The Web module offers elementary features like uploading/ downloading
files, initializing the Inversion of Control container using servlet listeners,
creating a web application, etc.
• The Web-MVC module offers implementation for web applications through
Spring MVC.
• The Web-Socket module provides client-server communication using
WebSocket-based support in web applications.
• The Web-Portlet module offers the Model-View-Controller implementation
with a portlet environment and mirrors the Web-Servlet module
functionality.

Miscellaneous Modules

Following are a few other essential modules, viz. AOP, Aspects, Instrumentation etc.
• AOP module offers aspect-oriented programming capabilities.
• The Aspects module offers robust AOP framework integration AspectJ.
• The Instrumentation module offers provision to the class instrumentation and
loader in the server applications.

5.3.2 Spring MVC


Spring MVC is a Java-based framework that provides an MVC design pattern and
ready components to build a web application. The MVC pattern loosely coupled the
important application aspects like input logic, business logic, and UI logic, resulting in
developing flexible web applications. A spring MVC implements Inversion of
Control, Dependency Injection etc., features and provide optimized solutions using
DispatcherServlet class.

9
Introducction to J2EE The applicaation logic intteracts with thhe database inn the Model anda is the lowwest level
Framewo orks of the patteern. The View w is responsible for exhiibiting data in n the form of
o HTML
pages to thee client. The Controller
C hollds the instancces or the sofftware code thhat passes
the informattion between the Model annd View.
The Model encapsulates the application data; the View rennders that data d and
generating output displaay on the client. The C Controller does the proceessing by
building thee correct moddel based on the
t specificattions that are subsequentlyy sent for
rendering. A class DisppatcherServleet plays a vital role in teerms of mappping the
request to thhe correspondding resource viz. the contrrollers, modells, and views.

The DispaatcherServleet

The Springg MVC DisppatcherServlett request proocessing worrkflow is depicted in


figure 5.3.
1. DisppatcherServleet plays a vittal role in thhe Spring MV VC frameworrk design.
It haandles all the HTTP requeests and HTTP P responses.
2. Onn receiving ann HTTP requ uest, the DisppatcherServlett working as the Front
Conntroller gets handler
h mappiing informatioon from the XML.
X
3. Thee HandlerMappping calls thhe appropriatee Controller anda based on the
t Get or
Post methods, annd the Controoller appropriiately calls thhe service meethod. The
busiiness logic based service method based sets the model data and
subsequently retuurns the Vieww name to thee DispatcherServlet.
4. DisppatcherServleet appropriateely chooses tthe defined View
V by cheecking the
ViewResolver enntry in the XM ML file for thhe request.
5. Afteer finalizing the View, DispatcherSeervlet passes the Model data and
invooke specified View to rendder on the broowser.

Fiigure 5.3: Spriing Web MVC


C DispatcherS
Servlet requestt processing workflow
w

Spring MV
VC Configu
uration

To create a simple Springg MVC appliccation, we neeed to perform


m the followinng steps:
1. We need to add the spring coontext and sprring web MV VC dependenccies to use
C framework in
the Spring MVC i the java prroject. We add spring-mvcc.jar in the
10
application classpath for the java project and add the jar file in the /WEB- Frameworks for J2EE
INF/lib folder for the web application.
2. Configure the DispatcherServlet through the web.xml file for handling
requests through the spring container. For the application deployment, the
Servlet container creates an instance for the ContextLoaderListner, which
facilitates the loading of the webApplicationContext.
3. Configure the spring file to define beans for annotations usage and configure
the view resolver for view pages.
4. Configure the web request mappings to handle the client requests.

The Spring also provides a built-in interface, the MultipartResolver interface, to


upload file in Spring MVC Application. The implementation is easy and only requires
a little configuration change with the controller handler method to handle the
incoming file for processing. The Spring also supports annotation-based validations
through bean variable and custom-based validators through controller class for data
validation in Spring Web MVC Framework.

Spring MVC Framework advantages

• Separate roles - The different components of the flow are parts of the
applicationContext that extends the plainApplicationContext. A specialized
object fulfils the position of each element.
• Lightweight – To develop and deploy an application, the Spring MVC
Framework uses a lightweight servlet container.
• Robust Configuration - Spring MVC offers a strong configuration for the
framework and application classes.
• Reusable business code – Spring MVC Framework offers reusable code that
permits usage of existing objects instead of creating a new one.

5.3.3 Spring Boot


Spring is commonly used to create scalable applications, but there are configuration
overheads that are time-consuming and take some time. Sprint boot framework
provides an efficient solution, with minimal efforts to develop the production-ready
stand-alone spring-based application. Spring Boot module is built on top of the spring
framework that offers a Rapid Application Development(RAD) to the new Spring-
based web-based or straightforward applications. In spring boot, developers need not
worry much about the configuration. It provides default configuration "Opinionated
Defaults Configuration" for code and annotations and can quickly start new
developments. It also includes functionality like code-reusability through Spring Boot
Batch, which is very effective in transaction management, maintaining logs, job
processing statistics etc.

Spring Framework and Embedded Servers like Tomcat comprises the spring boot,
and the XML configuration part is not required, which reduces the cost and
development time. As we have discussed, Spring integrates various modules during
application development. For instance, we need to configure DispatcherServlet, View
Resolver, Web Jar, XMLs, etc., but spring boot is an auto-configuration tool. Spring
boot autoconfigures automatically using a web jar that helps us choose and set up the
required number of modules fast and allows us to change as needed. Spring Boot
framework bundles all the dependencies and provides stand-alone JAR file with
embedded servers for the web application. The spring STS IDE or Spring Initializr
may be used for application development.

11
Introduction to J2EE
Spring Boot components
Frameworks
The essential Spring Boot components are:
1. Spring Boot Starter: It includes a set of convenient descriptors to make
application development much more manageable. The spring framework
offers many dependencies, and the Spring Boot Starter aggregates them
together to enhance productivity. The Spring Boot ensures the required
libraries are added to the build.

2. Spring Boot autoconfiguration: It automatically configures the Spring


application based on classpath parameter dependencies and makes
development fast and easy.

3. Spring Initializer: It is a web application that helps create an internal project


structure, i.e. a skeleton project, automatically reducing development time. It
helps in quick start a new project using the web interface "Spring Initializr'.

4. Spring Boot Actuator: It allows us to monitor and manage the application


while pushing it for production and helps us in debugging. It controls the
application using HTTP endpoints. We may enable the actuator simply by
adding the dependency to the starter, i.e. spring-boot-starter-actuator, and it is
disabled if we don't add the dependency. It provides complete insight into the
running spring boot application.

5. Spring Boot CLI: It allows us to write Groovy Spring Boot application with
concise code without requiring traditional project build.

Advantages of Spring Boot


• Stand-alone: It can create stand-alone applications.
• Embedded HTTP servers: Deployment of the WAR files is not required
as the web applications' testing may quickly be done using
different Embedded HTTP servers.
• CLI tools: For developing and testing an application, the CLI tools are
available
• Better productivity: For application development, there is no
requirement of XML configuration that reduces the development time and
improve productivity
• Plugins: A lot of plugins are available for the development and testing of
an application. It offers several plugins.
• Autoconfiguration: The Spring boot configures the classes automatically
based on the project requirements.
• Starter: Based on the application requirements, the Starter concept
available in the pom.xml file confirms all the required JARs dependency
downloads.

12
Frameworks for J2EE
☞ Check Your Progress 2:
1. What is Dependency Injection?

2. What is Aspect-Oriented Programming?

3. What is the difference between Spring Boot and Spring MVC?

4. What are the essential components of Spring Boot?

5.4 INTRODUCTION OF ANNOTATION

Java Annotations is a form of syntactic metadata that allows adding supplement info
in the source code. We can add an annotation to packages, classes, interfaces,
methods, and fields, but they do not change the program's execution, i.e. they are not a
part of the program itself. The annotation representation is like @ followed by
annotation name; for example, @Entity contains the annotation name following @,
i.e. Entity and compiler will act accordingly.

Java Annotation applications


Java annotations can be used in various instructions, such as Compiler, Build-time,
Runtime etc.

13
Introduction to J2EE • Compiler instructions: The compiler uses annotations to detect errors or
Frameworks suppress warnings. @Deprecated, @Override & @SuppressWarnings are the
three built-in annotations used to provide specific instructions to the compiler.
• Compile-time instructors: Software tools process the metadata information
and subsequently pass the compile-time instructions to the compiler. The
software tools generate required code, XML files etc.
• Runtime instructions: The Java reflections is used to access the Runtime
annotations that provide instructions to the program at runtime.

5.4.1 Built-in Java Annotations

The @Override, @SuppressWarnings and @Deprecated are the Built-in Java


Annotations used in Java code, whereas @Target, @Retention, @Inherited and
@Documented are Built-in Java Annotations used in other annotations.

• @Override annotation ensures subclass overriding the parent class method,


otherwise giving a compile-time error. For example, any spelling error can be
handled using @Override annotation that provides the method overridden.

Let us understand the concept taking an example:

class ClassParent
{
public void display()
{
System.out.println("Method of Parent class");
}
}
class ClassChild extends ClassParent
{

@Override
public void display()
{
System.out.println("Method of Child class");
}
}
class Main
{
public static void main(String[] args)
{
ClassChild c1 = new ClassChild ();
c1.display();
}
}

OUTPUT: Method of Child class

From example, we observe that the display() method is present in both the ClassParent
superclass and ClassChild subclass. The display method is called from the main
program actually called the subclass method instead of the method in the superclass.

• @Deprecated annotation marks deprecated methods and informs the user not
to use such methods and prints warning that it may be removed in the future
version.

14
Frameworks for J2EE
For example:

class Main
{

// @deprecated
// use of deprecated method which has been replaced by a newerMethod()

@Deprecated
public static void methodDeprecated()
{
System.out.println("Method is Deprecated");
}

public static void main(String args[])


{
methodDeprecated();
}
}

Output: Method is Deprecated

We observe that method has been declared deprecated from the example, and the
compiler generates a warning message.

• @SuppressWarnings annotation is used to suppress potential compiler


warnings. The annotation allows us to ignore a specific warning. The
deprecation and unchecked are the two most common warnings,
Deprecation annotation used to ignore deprecated method and unchecked to
ignore raw types. For example, @SuppressWarnings("unchecked",
"rawtypes") annotation will ignore warning at compile time for using the non-
generic collection.

class Main
{
@Deprecated
public static void methodDeprecated()
{
System.out.println("Method is Deprecated");
}

@SuppressWarnings("deprecated")
public static void main(String args[])
{
Main d1 = new Main();
d1. methodDeprecated ();
}
}

Output: Method is Deprecated

From the example, we observe that methodDeprecated has been declared deprecated,
and the compiler generates a warning message, but we can avoid the compiler
warning by using @SuppressWarnings("deprecated") annotation.

15
Introduction to J2EE
5.4.2 Java Custom Annotations
Frameworks

User-defined or Java custom annotations are very useful in developing readable code
and are declared using @interface with the annotation name. The method declaration
prohibited having any parameters and restricted to have primitives, String, Class,
enums, annotations, and array of the preceding types as a return type in user-defined
annotations.

We require a retention policy and a target to create an annotation. A retention policy


defines the time duration in the program's life-cycle, where we have to retain the
annotation. The retention of the annotation may be compile-time or runtime as per the
annotation's retention policy. The three standard retention policy are Source, Class
and Runtime.
Source: compiler discard annotations so invisible for compiler and runtime.
Class: The class file records the annotations but not retained by Java Virtual machine,
so only visible by compiler.
Runtime: class file records the annotations but retained by Java Virtual machine at the
runtime so visible to both the compiler and runtime.

• @Target annotation tag defines the valid Java constructs among the
methods, class, fields etc. An annotation may associate with one or more
targets.

• @Documented annotation indicates the inclusion of new annotation into


java document.

• @Inherited annotation allows inheritance where we can apply an annotation


to other annotation. Annotation inheritance is not available by default and so
not available to child class from the parent class.

• @Repeatable annotation facilitates annotation more than once as, by default,


it is applied once on a java element.

5.5 INTRODUCTION OF HIBERNATE WITH


JAVA PERSISTENCE API (JPA)

We may require storing the information during any application development, and
several applications use relational databases for this purpose. Although the JDBC API
offers the database connectivity to perform various database operations for Java
applications, it requires a lot of code to manage.
Spring offers API to integrate with Object-Relational Mapping (ORM) frameworks
such as Java Data Objects, Hibernate etc. These tools simplify the database operations
like data creation, manipulation, and access required to implement a persistent storage
application.
Hibernate is a lightweight, open-source Java framework that simplifies the database
interaction during Java application development. Hibernate implements the Java
Persistence API specifications and bridges the gap between the java object and the
relational database to provide data persistence.
JPA specifications define a common abstraction that we can use in our program to
interact with ORM products.

16
Framewoorks for J2EE

Figure 5.4: Java Persistence API speccifications

5.5.11 Hibeernate Architecture

The Hibernate fraamework is built on top off existing Javva API, and thhe architecturre is
charaacterized intoo four layers viz. Databaase, Back-endd API, Hiberrnate framew work,
and Java
J applicatiion layer.

The core
c componeents of Hibernnate architectture are:

• Configuraation object holds the configuratioon propertiess viz. databbase


configuraation file and class
c mappingg files.
• SessionFaactory is a faactory of sessions that provvides a factory method too get
the sessio
on object. It iss a heavyweigght object, im mmutable and is available too all
the sessioons. It is creaated at the timme of applicaation startup for later use and
persists till the Hibernaate is runningg.
• Session objects providde an interfacee between thee application and a the databbase.
It is a liightweight object
o and geets instantiatted wheneverr an applicaation
requires a database intteraction. Thee session object offers a methodm to creeate,
read, updaate and deletee operations.
• Transactio onFactory is a factory of o Transactioon that offerrs a method for
transactioon managemennt.
• ConnectioonProvider is an optional factory
f of JDBBC connectio ons.
• Transient or Persistentt objects are database
d objeects. In the traansient statess the
new objeccts created inn the Java program are not associated with w any hibernnate
session. Still,
S in the caase of the perrsistent state the
t object is associated
a wiith a
hibernate session.

Figu
ure 5.5: Hibern
nate architectture

17
Introduction to J2EE Hibernate provides the support for persisting the Collections and depending on the
Frameworks type of interface; Hibernate injects the persistent collections. The Persistent object
contains a persistent state saved to the database, whereas the transient object does not
save or is associated with any session yet. A newly created entity is transient until it
persisted. Detached state is when a previously persistent object is currently not
associated with any session. We may switch instance from Transient to persistent by
calling save(), persist(), or saveOrUpdate() and switching Persistent instances to
transient by calling delete(). We may switch instance from Detached to persistent by
calling update(), saveOrUpdate(), lock() or replicate(). The transient or detached
instance state may convert to a new persistent instance by calling merge().

5.5.2 Hibernate Framework advantages


The Hibernate framework advantages are as follows:
• Open Source - It is an open-source and lightweight framework.
• Sound Performance - The hibernate framework offers better performance due
to the internal cache mechanism. Out of the two caches, the first level cache is
by default enabled for performance.
• Powerful query language – Hibernate provides the object-oriented version of
SQL i.e. Hibernate Query Language (HQL) that creates database-independent
queries. Any database change would not lead to a maintenance problem as the
queries are not database-specific.
• Automatic Table Creation - It creates automatic database tables.
• Simplifies Complex Join - Hibernate framework provides ease in the data
fetching from multiple tables.
• Query Statistics - It provides query statistics and database status.
• Transaction management - Hibernate offers transaction management to avoid
any data inconsistency.

5.5.3 Java Persistence API


Java Persistence API is a Java specification that offers functionality and standard to
Object Relational Mapping tools that manage relational data in Java applications. The
JPA facilitates the mapping, storing, updating and retrieving data from the java
objects to the relational database and vice versa. The javax.persistence package
contains the Java Persistence API classes and interfaces to bridge the relational
database and object-oriented programming gap. For the database access applications,
the JPA automate the implementation as it requires only a repository interface and
custom finder methods that reduce the code complexity and improves efficiency.

JPA Object Relational Mapping

Hibernate automatically manipulates domain model entities using ORM tools, and
thus it doesn't require modifying all associated insert and update command upon
adding a new column.
Object Relational Mapping (ORM) facilitates developing and maintaining a relation
between an object state and a relational database column. Hibernate ORM automates
the Object-relational mapping task process, where the ORM layer converts the java
classes and objects to interact with the relational database. It provides various
database operations smoothly and efficiently, like insert, update, deletes etc. The
persisted object name becomes the table name, and the fields become the columns.
There are different ORM mapping types but before discussing them, let us understand
the persistent objects, also called entities.

18
Frameworks for J2EE
Entities

An entity is a databases table is associated with a group of states, and each instance
correspondingly represents a row in the table. JPA Entities is an application-defined
object which persists in the database. The persistent entity state may represent using
persistent fields or persistent properties. The object/relational mapping annotations are
used by these persistent fields or persistent properties for mapping the entities and
entity relationships to the relational database.

• EntityManager - The model class objects or instances form the persistence


context and interact with the database, we need an EntityManager instance.
Generally, the EntityManager manages the entity instances like creating,
updating, removing or finding entities and managing their life cycle.
• EntityManagerFactory - EntityManagerFactory is linked with a persistence
unit, and it creates an EntityManager.
An entity must follow the property of persistability with unique Persistent Identity,
and it should support Transactionality. It means object can be accessed any time after
storing in the database through the object identity and the changes in the database are
all atomic following transactionality. Each Entity is associated with some metadata
represented through annotation that form tags that persist inside the Class and XML
persist outside the class in an XML file.
A Java class transform into an entity using No-argument Constructor and Annotation
by adding @Entity and @Id annotation. @Entity is placed on the class name to
indicate that this class is an entity. @Id is placed on a specific field treated as a
primary key holding the persistent identifying properties.
The important characteristics requirement that an entity class must have:
• The class must annotate with the javax.persistence.Entity annotation
• The class, methods or even the persistent instance variables must not be
declared final.
• The class must have a no-argument constructor that may be public or
protected.
• The class must have a Serializable interface if an entity instance is passed by
value through a remote interface.
• The abstract and concrete classes can be annotated with the Entity annotation,
and the Entities and non-entity classes can extend each other.

Entity Primary Keys

An Entity must have a corresponding unique object identifier or primary key that
enables locating a particular entity instance. Based on the persistent properties, an
entity may have a simple denoted by javax.persistence.Id annotation or a composite
key denoted by javax.persistence.EmbeddedId and javax.persistence.IdClass
annotations.

Types of ORM Mapping

The various ORM mappings are as follows:


• One-to-one – The @OneToOne Annotation represents association of one
entity instance to single instance of another entity.
• One-to-many – The @OneToMany Annotation represents association of one
entity instance to many Entity instance on another entity.

19
Introduction to J2EE • Many-to-one – The @ManyToOne Annotation represents association of many
Frameworks entity instance to one Entity instance of another entity.
• Many-to-many – The @ManyToMany Annotation represents association of
many entity instance to many Entity instance of another entity.

The JPA simplify the database programming by importing interfaces and classes from
the javax.persistence package. JPA defines object-oriented query language, Java
Persistence Query Language (JPQL) is very similar to SQL. Unlike SQL, which
operates directly with the database tables, the JPQL interacts through the java objects.
Let us take an example to understand a simple database program using Hibernate
framework with JPA annotation.
Step1: create a database named empdb using MYSQL,
create database empdb;
Then create a table
CREATE TABLE EMP (id INTEGER not NULL, first VARCHAR(30), last
VARCHAR(30), age INTEGER, city VARCHAR(30), salary INTEGER, PRIMARY
KEY ( id ));
Step 2: We Simplify the process of project building using Maven project in Eclipse.
The details about Maven will be discussed in the next unit.
In the Eclipse IDE, we will go to through the File->New->Project->Maven->Maven
Project to open a New project and click next.
We only provide the following project information on the New Project screen
- Group Id: net.codejava.hibernate
- Artifact Id: HibernateJPADemo
After clicking next, we will add Hibernate, JPA and MySQL Connector Java
dependencies in Maven's Project Object Model (pom.xml). By simply adding the
dependencies the Maven automatically downloads the required jar files. In the
pom.xml file, simply add the following XML before the </project> tag:

20
Step 3: Now let us create a net.codejava.hibernate java package under the folder Frameworks for J2EE
src/main/java to put our java classes.
First, we create a model class employee with some getter and setter methods. We add
JPA annotations in this mode class to map it with the corresponding database table.

package net.codejava.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class employee
{

private Integer userid;


private String firstname;
private String lastname;
private Integer age;
private String city;
private Integer salary;
@Column(name = "id")
@Id
public Integer getUserid()
{
return userid;
}
public void setUserid(Integer userid)
{
this.userid = userid;
}
@Column(name = "first")
public String getFirstname()
{
return firstname;
}
public void setFirstname(String firstname)
{
this.firstname = firstname;
}
@Column(name="last")
public String getLastname()
{
return lastname;
}
public void setLastname(String lastname)
{
this.lastname = lastname;
}
public Integer getAge()
{
return age;
}
public void setAge(Integer age)
21
Introduction to J2EE {
Frameworks this.age = age;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public Integer getSalary()
{
return salary;
}
public void setSalary(Integer salary)
{
this.salary = salary;
}
}

The annotation @Entity is placed before the class definition and maps the class with
the database table. The annotation @Table is also placed before the class definition
and is used if the class name and the table name are different. The @Column
annotation is placed before the getter method if the instance field of the class is
different to the database column name. The @Id map the primary key column in the
table.
Step 4: Next, create a persistence.xml configuration file for JPA, it will be placed in
the new folder named META-INF that is created under src/main/resources folder.
The Hibernate uses this configuration file to connect with the database. Let us add the
following XML code in the persistence.xml file.

The first property tag tells us about the JDBC URL value pointing to the database.
The second and third tags provide the username and password; the subsequent tag
specifies the JDBC driver and the last two property tags tell the Hibernate to show and
format the SQL statements.
Step 5: Finally, we write a test program to check the overall working of the example
by updating the employee entity instance using JPA. We create a new
22
employeeManager.java class under the src/main/java folder with the main() method. Frameworks for J2EE
We add the following code:
package net.codejava.hibernate;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EmployeesManager


{
public static void main(String[] args)
{
EntityManagerFactory factory =
Persistence.createEntityManagerFactory("empUnit");
EntityManager entityManager = factory.createEntityManager();
entityManager.getTransaction().begin();
employee newEmployee = new employee();
newEmployee.setUserid(702);
newEmployee.setFirstname("Vikash");
newEmployee.setLastname("Sharma");
newEmployee.setAge(38);
newEmployee.setCity("Vizag");
newEmployee.setSalary(7000);
entityManager.persist(newEmployee);
entityManager.getTransaction().commit();
entityManager.close();
factory.close();
}
}

In the main() method, we first create an EntityManager and begin the transaction;
subsequently, we save newEmployee, a new employee object using the persistent
(object) method. Finally, we close the EntityManager and EntityMangerFactory after
completing the transaction.
The output will show that the Hibernate print the SQL statement and the program
executed successfully and can be verified through MYSQL command line. Using
Hibernate/JPA we can add a new row without explicitly writing any SQL query.
Output:
Hibernate:
insert
into
employee
(age, city, first, last, salary, id)
values
(?, ?, ?, ?, ?, ?)
Apr 24, 2021 11:24:01 PM
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/emp]

23
Introduction to J2EE
Frameworks ☞ Check Your Progress 3:

1. Explain the different entity bean states.

2. What do you understand by Java Persistence API?

3. How do you differentiate between Hibernate and JPA?

4. How do you Create an Annotation?

5. What are the differenty types of ORM mapping?

24
Frameworks for J2EE
5.6 SUMMARY

In this unit, we have introduced various open-source J2EE frameworks. Apache


Struts 2.x is a free open source framework that offers an extensive programming
model. It supports the complete application development cycle from build to
maintenance based on the MVC design pattern. We have discussed various Struts2
features, mapped them with the core components, and elaborated on the working flow
of Struts2 from the clients' request to the View.

The spring framework is thought of as a framework of frameworks supporting other


frameworks like struts, hibernate etc., through extensive programming and
configuration model. The fundamental design principle of this framework is "Open
for extension, closed for modification" and is achieved with the concept of
Dependency Injection (DI), Inversion of Control (IoC) and Aspect-oriented
programming (AOP). The Spring Dependency Injection facilitates the reusability and
enables unit testing. The inversion of control principle behind DI states that class
dependencies need not be hard-coded. The Spring Aspect-oriented
programming module intercepts an application through interceptors and facilitates
adding extra functionality during method executing before or after method execution.
Spring MVC and Spring Boot frameworks provide more flexibility to the developers.
Spring MVC provides default configurations to build a Spring-powered framework.
Sprint boot framework offers an efficient solution, with minimal efforts to develop the
production-ready stand-alone spring-based application. Spring Boot module builds on
top of the spring framework, and it gives the Rapid Application Development to the
new Spring-based web-based or straightforward applications. Spring Boot reduces the
code length in developing a web application using annotation configuration and
default codes.
Java Annotations is a form of syntactic metadata that add additional information about
a program. They do not have a direct effect on the behaviour of the code they
annotate. Java annotations are used for various purposes, such as Compiler
instructions, Build-time instructions, Runtime instructions, etc. Annotations start with
'@'. They are mainly used for instructions during Compile time, Build-time and
Runtime.
Java Persistent API (JPA) is a specification that provides object-relational mapping
standards in java applications. JPA is considered as a link between ORM and
relational databases. Object Relational Mapping (ORM) facilitates developing and
maintaining a relation between an object state and a relational database column. ORM
tools like Hibernate, iBatis and TopLink implements JPA specifications for data
persistence. We will be discussing these topics in more details in the subsequent units.

5.7 SOLUTIONS/ ANSWER TO CHECK YOUR


PROGRESS

Check Your Progress 1

Answer 1: The Struts2 core components are Action, Interceptors, View,


VALUESTACK, Object Graph Navigation Language (OGNL) and Configuration
Files.
25
Introduction to J2EE Answer 2: The client request is sent to the server through the browser. After matching
Frameworks the request pattern, the server loads the web.xml and forwards it to the
FilterDispatcher. The request passed through the interceptor before the appropriate
action class is executed. Based on the business logic function, the action class or the
Controller gets the processed data from the database. The Controller decides on the
rendered View depending on the result, and only after the interceptor execution result
is generated.

Answer 3: Action component contains an action class that controls the user's
interaction, the Model, and the View. It holds the complete business logic and
prepares the response based on the client request.

Answer 4: A ValueStack store action and all the data related to action where the
OGNL facilitates manipulating the data available at ValueStack.

Answer 5: The Interceptor component is a crucial part of the Controller and is mostly
responsible for framework processing. These are like servlet filters and executes
before and after the processing of the request. Generally, perform common actions
like session logging, validation etc., for different actions.
Check Your Progress 2
Answer 1: Dependency Injection implements the principle of Inversion of Control
(IoC), allowing creating and binding the dependent objects outside of a class. It
separates object creation from its usage and thus reduces the boilerplate code based on
business logic.

Answer 2: Aspect-oriented programming – Aspect-oriented programming (AOP) is a


programming style where aspects are used instead of OOPS objects. An aspect is a
class that contains advice and joinpoints. It spans multiple application nodes
distributed across methods, classes, object hierarchies, and object models, such as
logging, security, transaction etc. AOP defines specific policies and offers modularity,
and in this paradigm, the program logic is broken down into distinct parts called
concerns, enabling the application to adapt to changes dynamically. The Spring
Aspect-oriented programming module intercepts an application through interceptors
to add extra functionality during method executing before or after method execution.

Answer 3: The spring framework aids in developing simple, reliable, and scalable
Java applications. It follows the MVC design pattern implementing all the basic
features of a core spring framework. Spring MVC provides default configurations to
build a Spring-powered framework. Sprint boot framework offers an efficient
solution, with minimal efforts to develop the production-ready stand-alone spring-
based application. Spring Boot module builts on top of the spring framework, and it
gives the Rapid Application Development to the new Spring-based web-based or
straightforward applications. Spring Boot reduce the code length in developing a web
application using annotation configuration and default codes.

Answer 4: The essential Spring Boot components are:


1. Spring Boot Starter: It includes a set of convenient descriptors to make
application development much more manageable. The spring framework
offers many dependencies, and the Spring Boot Starter aggregates them
together to enhance productivity.
2. Spring Boot autoconfiguration: It automatically configures the Spring
application based on classpath parameter dependencies and makes the fast and
easy development.

26
3. Spring Initializer: It is a web application that helps create an internal project Frameworks for J2EE
structure, i.e. a skeleton project, automatically reducing development time.
4. Spring Boot Actuator: It allows us to monitor and manage the application
while pushing it for production and helps us in debugging. It controls the
application using HTTP endpoints. We may enable the actuator simply by
adding the dependency to the starter, i.e. spring-boot-starter-actuator, and it is
disabled if we don't add the dependency.
5. Spring Boot CLI: It allows us to write Groovy Spring Boot application with
concise code.

Check Your Progress 3


Answer 1: The three states where an entity bean instance exists are:

• Transient: It is a state when an object is not associated with any session or


is not persisted.
• Persistent: It is a state when an object is linked with a unique session.
• Detached: It is a state when a previously persistent object is currently not
associated with any session.

We may switch instance from Transient to persistent by calling save(), persist(), or


saveOrUpdate() and switching Persistent instances to Transient by calling delete().
We may switch instance from Detached to persistent by calling update(),
saveOrUpdate(), lock() or replicate(). The transient or detached instance state may
convert to a new persistent instance by calling merge().

Answer 2: Java Persistence API is a Java specification that offers functionality and
standard to Object Relational Mapping tools for managing relational data in Java
applications. It acts as an interface to bridge the relational database and object-
oriented programming gap. For the database access applications, the JPA automate the
implementation as it requires only a repository interface and custom finder methods
that reduce the code complexity and improving efficiency.

Answer 3: Java Persistence API (JPA) is the interface defined in javax.persistence


package and the Hibernate is the implementation-defined in org.hibernate package. In
the JPA, we use Entity Manager for handling the data persistence through the Java
Persistence Query Language (JPQL). But in Hibernate, we use the Sessions for the
persistence of data through the Hibernate Query Language (HQL).

Answer 4: Java Annotations is a form of syntactic metadata that adds supplement


information into our source code. The annotation representation @Entity, where @
sign specifies to the compiler that following @ is an annotation.

Answer 5: The various ORM mappings are as follows:

• One-to-one – The @OneToOne Annotation represents one to one Entity


instance association.
• One-to-many – The @OneToMany Annotation represents one to many Entity
instance association.
• Many-to-one – The @ManyToOne Annotation represent many to one Entity
instance association.
• Many-to-many – The @ManyToMany Annotation represent many to many
Entity instance association.

27
Introduction to J2EE
Frameworks 5.8 REFERENCES/FURTHER READING

1. Craig Walls, “Spring Boot in action” Manning Publications, 2016.


(https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)
2. Paul Deck, “Spring MVC: a Tutorial”, Brainy Software, 2016.
3. Ian Roughley,”Practical Apache Struts 2 Web 2.0 Projects”, Dreamtech Press,
2008.
4. Cazzola, Walter, and Edoardo Vacchi, "@ Java: Bringing a richer annotation
model to Java”, Computer Languages, Systems & Structures 40(1), pp.2-
18,2014.
5. https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html

28
UNIT 6 FRAMEWORKS AVAILABLE FOR
J2EE DEVELOPMENT –STRUTS,
SPRING BOOT AND HIBERNATE
6.0 Introduction
6.1 Objectives
6.2 Struts: Features
6.2.1 Model 1 Vs Model 2 (MVC) Architecture
6.2.1.1 Model 1 Architecture
6.2.1.2 Model 2 (MVC) Architecture
6.2.2 Struts2 Architecture
6.2.3 Struts2 Features
6.2.3 Struts2 Example
6.3 Spring Boot and MVC: features
6.3.1 Spring MVC features
6.3.2 Spring Boot features
6.4 Hibernate with JPA: Features
6.5 Compare among these frameworks
6.5.1 Struts Vs Spring
6.5.2 Spring Boot Vs Spring MVC
6.5.3 Spring Vs Hibernate
6.6 Maven: Introduction, Overview and Configuration
6.6.1 Maven Installation
6.6.2 Maven Core Concepts
6.6.2.1 Basic Structure of the POM File
6.6.2.2 Maven Build Life Cycles, Phases and Goals
6.6.2.3 Maven Build Profiles
6.7 Create First Project using Maven
6.8 Summary
6.9 Solutions/ Answer to Check Your Progress
6.10 References/Further Reading

6.0 INTRODUCTION

A conventional website mainly delivers only static pages, while a web application has
the ability to create dynamic responses. A web application receives input from users,
interacts with the database and executes the business logic to customize the view as a
response to the users.

Web applications use Servlet and JSP technologies for dynamic response. The Servlet
and JSP may contain page design code, control execution code and database code.
Mixing design code, control execution, and database code together make a large
application difficult or impossible to maintain.

The Model-View-Controller (MVC) architecture provides the separation of concerns


and makes the application easy to maintain and develop. The model represents the
business logic, view represents the page design, and controller represents the
navigational code. The Spring MVC and Struts are based on MVC architecture which
helps developers to create a maintainable web application efficiently.

Build process of a software project involves a series of processes such as downloading


required dependencies, putting jars on classpath, generating source code (for auto-

1
Frameworks Available For
J2ee Development –Struts,
generated code), source code compilation, tests execution, packaging compiled code
Spring Boot and Hibernate along with the dependencies into deployable artifacts such as WAR, EAR or JAR. All
processes can be done manually by developers but it's time consuming and error
prone.

Apache Maven simplifies the build process and automates all the involved processes.
Maven is a popular open-source build tool developed by the Apache Group to build,
publish, and deploy several projects at once for better project management.

6.1 OBJECTIVES

After going through this unit, you will be able to:


● explain Model1 and Model2(MVC) architecture,
● describe Struts architecture and execution flow,
● describe Spring Boot and Spring MVC feature,
● describe features of Hibernate/JPA,
● differentiate among Spring, Spring MVC and Spring Boot,
● use Maven tool to automate the build process, and
● describe Maven build life cycles, build phases and build goals

6.2 STRUTS: FEATURES

The Struts framework was developed by Craig McClanahan and he donated it to


Apache foundation in May, 2000. In June, 2001 Apache released the first version of
Struts as Struts 1.0. Struts 2.5.22 is the most current version of the Struts framework
in April, 2021.

Apache Struts2 is an elegant, popular Java Model-View-Controller (MVC) framework


to develop MVC based web applications. Struts2 is a complete rewrite of Struts
architecture. Struts2 is completely different from Struts1, and it is not the next version
of Struts1 framework. The Webwork framework was started with Struts as base in
order to provide a simplified and enhanced framework based on Struts to develop the
MVC based web application easily. After a while Webwork framework and Struts
community joined hands together to work on this enhanced framework which became
famous as Struts2 framework.

The Struts2 is enriched with many important features such as support to POJO based
actions, Configurable MVC Components, Integration support to various frameworks
such as Spring, Tiles, Hibernate etc., AJAX support, Validation support, support to
various theme and Template such as JSP, Velocity, Freemarker etc.

6.2.1 Model 1 Vs Model 2 (MVC) Architecture


The knowledge about design models helps us to decide the architecture of a web
application. There are two types of design models.

● Model 1 Architecture
● Model 2 (MVC) Architecture

2
Frameeworks for J2E
EE
6.2.11.1 Model 1 Architecture

In eaarlier days, web


w applicatioon developmment using Serrvlet had muultiple issues like
mixin nd recompilaation of Servllet if any design
ng Business and Presentaation logic an
code changed.
In model
m 1 architeecture, JSP paages were thee focal point ffor the entire web applicattion.
JSP provides the solutions to the problem ms of Servlet technology. JSP providees a
betteer separation of concern not n to mix business
b logicc and presenttation logic. Re-
Deplloyment of webw applications is not reequired if thee JSP page is i modified. JSP
supports JavaBeaan, custom tag gs and JSTL to keep the Business loggic separate from f
JSP. Model 1 arch hitectural diaggram is shownn below.

Figu
ure 6.1 : Model 1 Architectture

Noticce that there is no Servlet involved in i the processs. The cliennt request is sent
direcctly to a JSP page,
p which may
m communnicate with JavvaBeans or otther services,, but
ultim
mately the JSPP page selectss the next page for the cliennt.
Advaantages

● Quick and
d easy way too develop a web applicationn

Disa
advantages

● Decentraalized naviga ation Controll: There is noo central control to determ mine
the navigation since evvery JSP pag ge contains thhe logic to deetermine the nnext
page.
● Hard to maintain:
m If a JSP is renaamed, then evvery other JSP P which referrs to
the renam
med JSP, need ds to be modiffied.
● Time Coonsuming: Reusable
R com
mponents likke custom taags developm ment
requires more
m time.
● Difficult to extend: Model1
M architeecture is not ssuitable for laarge and compplex
ons.
applicatio

6.2.11.2 Model 2 (MVC) Architectur


A re

In Model
M 2 architecture contrrast to the Model
M 1 archhitecture, a Servlet
S knownn as
Conttroller Servleet intercepts all
a client requuests. The Controller Serv vlet performss all
the in
nitial request processing annd determines which JSP tto display nexxt.

3
Frameworks Available For
J2ee Development –Struts,
Spring Boot and Hibernate

Figure 6.1: Model 2 (MVC) Architecture

In this architecture, the client never sends requests directly to the JSP. This
architecture enables us to perform authentication and authorization, centralized
logging etc. Once request processing is finished, the servlet directs the request to the
appropriate JSP page.
As it can be observed that the key difference between the two architectures is the
Controller Servlet introduced into Model 2, which provides a single point of entry and
encourages more reuse and extensibility than the Model 1 architecture. The Model 2
architecture clearly provides the separation of business logic, presentation logic, and
request processing. This separation is commonly known as Model-View-Controller
(MVC) pattern.
Advantages

● Centralized navigation Control


● Easy to maintain
● Separation of concern
● Easy to extend
● Easy to test

Disadvantages

● Developer writes the Controller Servlet code and it needs to be compiled and
redeployed if any logic changes for Controller Servlet.
Struts provides the configurable MVC support with declarative approach for defining
view components, request mapping in order to resolve the drawbacks of Model2
architecture. In Struts 2, we define all the action classes and view components in
struts.xml file.

6.2.2 Struts2 Architecture


Struts2 is a Pull-MVC (MVC2) based architecture, in which the view layer pulls data
stored into Value Stack to render. Struts2 implements the Model-View-Controller
architecture with the following five components.
● Interceptors
● Actions
● Results/ Result Types
● Value Stack / OGNL
● View Technologies
Struts2 architectural diagram is shown below.

4
Frameworks for J2EE

Figure 6.2: Struts2 Architecture

Interceptors: Interceptors are conceptually similar to servlet filters. The Interceptors


are used to implement the cross-cutting functionality such as validation, exception
handling, internationalization etc. The Struts2 provides many preconfigured and ready
to use interceptors out-of-the-box.
Actions: Actions are the core of Struts2 framework. These are used to provide the
business logic which executes to serve the client request. Each URL is mapped to a
specific action.
In Struts2, the action class is simply POJO (Plane Old Java Object). The only
prerequisites for a POJO to be an action is that there must be a no-argument method
that returns either a String or Result Object. If the no-argument method is not
specified, the execute() method is used to perform business logic processing.
Results / Result Types: The next step after execution of an action is to display a
view. The <results> tag plays the role of a view in the Struts2 MVC framework.
Some navigation rules are associated with the results. For example, if the action
method is to register a user, there are three possible results.
1. Successful registration
2. Unsuccessful registration
3. Already registered
For the above, the action method will be configured with three possible outcome
strings and three different views to render the outcome. Struts2 does not force us to
use JSP as view technology. Struts2 is based on the MVC paradigm, which makes the
components configurable.
Struts2 has many predefined result types, and the default result type is dispatcher to
dispatch to JSP pages. Struts2 defines different result types for different view
technologies such as Velocities, Tiles, XSLT, Freemarker.
ValueStack / OGNL: A ValueStack represents a stack that contains application-
specific objects such as action objects and other model objects. The objects in the
ValueStack are available to the response on UI pages. There are various tags available
for JSP, Velocity and Freemarker to access the ValueStack. The ValueStack allows us
to put objects, query objects and delete objects using OGNL.
The Object-Graph Navigation Language (OGNL) is a very powerful expression
language similar to the JSP Expression Language. Struts2 OGNL performs two
important tasks – data transfer and type conversion. The OGNL in Struts2 takes the
5
Frameworks Available For
J2ee Development –Struts,
request parameters from servlet context, performs the type conversion using the in-
Spring Boot and Hibernate built type converters to the corresponding type in bean and transfers it to
corresponding java variable.

6.2.3 Struts2 Features


The Struts2 is enriched with many important features, and some of them are listed as
follows.
1. Decoupling of view from action classes: Struts2 allows us to associate a
view with multiple action classes.
2. Ready to use view components: Struts2 provides many ready to use view
components such as stylesheet driven tags which reduces the lines of code
into the application for form design and form validation.
3. Intelligent defaults in all configuration files: One of the important features
of the Struts2 is the default value for the configurable properties. Hence,
developers do not need to specify the obvious default values into
configuration files.
4. Use of OGNL: Struts2 uses the expression language OGNL, which is more
powerful and flexible than JSTL.
5. Type conversion mechanism: Struts2 supports any type of properties with
the help of OGNL, while in Struts1 all the properties are mostly of string type.
6. Strong validation support: Struts2 provides a strong validation mechanism
with the support of Xwork validation framework, which provides both client-
side and server-side validation. It also supports custom validation with the
support of Validate() method.

6.2.3 Struts2 Example


The concepts and the components of Struts have been explained in previous sections.
This section explains step by step to create a simple Struts2 web application. The
required tools and software are as follows.
● Eclipse IDE
● Maven
● Java 8 or above
● Struts 2.x
Step 1: Create a maven project in eclipse with the following group id and artifact id.

Figure 6.3: Create Maven Project Into Eclipse

6
Step 2: Right click on the project and go to properties of the project. Check the Java Frameworks for J2EE
Build Path. If some error is there, select the JRE System Library as shown in the
screenshot.

Figure 6.4: Fix Build Path Error

Step 3: Right click on Project folder and click on New option to add a Source Folder
as src/main/resources into the project. Final folder structure of the project is as
follows.

Figure 6.5: Project Structure into Eclipse

Step 4: Add the following maven dependency into pom.xml

<!‐‐ https://mvnrepository.com/artifact/javax.servlet/servlet‐
api ‐‐>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet‐api</artifactId>

7
Frameworks Available For
J2ee Development –Struts,
<version>2.5</version>
Spring Boot and Hibernate <scope>provided</scope>
</dependency>
<!‐‐
https://mvnrepository.com/artifact/org.apache.struts/struts2‐
core ‐‐>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2‐core</artifactId>
<version>2.5.26</version>
</dependency>

Step 5: Configure the Controller Servlet into web.xml


<?xml version="1.0" encoding="UTF‐8"?>
<web‐app xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web‐app_3_0.xsd"
id="apache‐struts‐config‐example" version="3.0">
<display‐name>Struts2 Example</display‐name>

<filter>
<filter‐name>struts2</filter‐name>
<filter‐class>

org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteF
ilter
</filter‐class>
</filter>
<filter‐mapping>s
<filter‐name>struts2</filter‐name>
<url‐pattern>/*</url‐pattern>
</filter‐mapping>

</web‐app>

Step 6: Create an Action class. UserAction class extends ActionSupport class in order
to implement the validation with Validate() method.
public class UserAction extends ActionSupport
{
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
private String message;
@Override
public String execute() throws Exception
{
int timeOfDay =
Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if(timeOfDay >= 0 && timeOfDay < 12)
{
message = "Good Morning";
}
else if(timeOfDay >= 12 && timeOfDay < 16)
{

8
message = "Good Afternoon"; Frameworks for J2EE
}
else if(timeOfDay >= 16 && timeOfDay < 21)
{
message = "Good Evening";
}
else if(timeOfDay >= 21 && timeOfDay < 24)
{
message = "Good Morning";
}
return ActionSupport.SUCCESS;
}
@Override
public void validate()
{
if (null == firstName || firstName.length() == 0)

addActionError(getText("error.firstName.required"));
if (null == lastName || lastName.length() == 0)

addActionError(getText("error.lastName.required"));
}

// getter setter...
}

Step 7: Configure the request mapping and view in struts.xml.


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

<!DOCTYPE struts PUBLIC


"‐//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts‐2.0.dtd">

<struts>
<include file="struts‐default.xml"/>

<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.custom.i18n.resources"
value="Application" />

<package name="default" extends="struts‐default">


<action name="">
<result>/WEB‐INF/jsp/index.jsp</result>
</action>
<action name="user"
class="org.ignou.struts2.action.UserAction">
<result name="error">/WEB‐INF/jsp/index.jsp</result>
<result name="input">/WEB‐INF/jsp/index.jsp</result>
<result name="success">/WEB‐INF/jsp/success.jsp</result>
</action>
</package>

</struts>

9
Frameworks Available For
J2ee Development –Struts,
Step 8: Add the required properties into Application.properties.
Spring Boot and Hibernate label.welcome = Struts 2 Hello World!!!
label.firstName = First Name
label.lastName = Last Name
error.firstName.required = First Name is required!
error.lastName.required = Last Name is required!

submit = Go!!

Step 9: Add the jsp file inside folder /WEB-INF/jsp.


index.jsp
<%@ page language="java" contentType="text/html; charset=ISO‐8859‐
1" pageEncoding="ISO‐8859‐1"%>
<%@ taglib prefix="s" uri="/struts‐tags" %>
<?xml version="1.0" encoding="UTF‐8" ?>
<!DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1‐transitional.dtd">
<html>
<head>
<title>Struts 2 Maven Hello world!!!</title>
<s:head/>
</head>

<body>
<h1 style="color: green;text‐align: center;"><s:text
name="label.welcome" /></h1>
<s:if test="hasActionErrors()">
<div id="fieldErrors">
<s:actionerror/>
</div>
</s:if>

<s:form action="user" namespace="/" method="post"


name="strutsForm">
<s:textfield name="firstName" size="30" maxlength="50"
key="label.firstName"/>
<s:textfield name="lastName" size="30" maxlength="50"
key="label.lastName"/>
<s:submit key="submit" align="right"/>
</s:form>
</body>
</html>

success.jsp
<%@ page language="java" contentType="text/html; charset=ISO‐
8859‐1"
pageEncoding="ISO‐8859‐1"%>
<%@ taglib prefix="s" uri="/struts‐tags" %>
<?xml version="1.0" encoding="UTF‐8" ?>
<!DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1‐transitional.dtd">
<html>
<head>
<title>Struts 2 Maven Welcome page!</title>
10
</head> Frameworks for J2EE
<body>
<h2 style="color: green"><s:property
value="message"/>,</h2>
<h3 style="color: green">&emsp; &emsp; Mr./Mrs.
<s:property value="lastName" /> <s:property value="firstName"
/></h3>
</body>

</html>

Step 10: Run the application in eclipse by right clicking on project > Run As > Run
on Server. Configure tomcat server into eclipse in order to execute the web
application.
Step 11: Access the URL http://localhost:8080/struts2-hello-world/. Outputs of the
execution are as followings.

Figure6. 6: Execution Result 1

Validation has been implemented for both the fields. Hence, if any field validation
fails, the user will be notified with error messages.

Figure 6.7: Execution Result 2

11
Frameworks Available For
J2ee Development –Struts,
Success response after valid form submission is as follows.
Spring Boot and Hibernate

Figure 6.8: Execution Result 3

☞ Check Your Progress 1:

1) Explain Model 1 architecture with its advantages and disadvantages.

2) Explain Model 2 architecture with its merits and demerits.

3) What are Actions in Struts2?

4) List down the features of Struts.

12
Frameworks for J2EE

6.3 SPRING BOOT AND MVC: FEATURES

Spring, Spring MVC and Spring Boot do not compete for the same space; instead,
they solve the different problems very well. This section briefs about Spring, Spring
MVC and Spring Boot. Later it explains the features of Spring MVC and Spring Boot.

6.3.1 Spring MVC features


The dependency injection (DI) is the core concept of the Spring framework, which
enables the development of loosely coupled and easily unit testable applications.
Based on the DI, Spring framework created various modules such as Spring MVC,
Spring JDBC, Spring Test, Spring ORM, Spring AOP etc. These modules do not
bring any new functionality since we can do all these with J2EE. These modules
simply bring in abstraction and the abstraction aims-
● Reduce Duplication/ Reduce Boilerplate Code
● Promote Decoupling/ Increase Unit testability
Spring Web MVC framework enables us to develop decoupled web applications. It
introduces the concepts of Dispatcher Servlet, ModelAndView and View Resolvers to
develop loosely coupled web applications. Spring MVC holds many unique features
listed below.
● Clear separation of responsibility: The DispatcherServlet, controller,
handler mapping, view resolver, form object, model object, command object,
validation and so on are specialized to perform a single responsibility.
● Adaptability and flexibility: Spring MVC is very flexible and adaptable.
One of the features to define the controller method signature as per need,
possibly using one of the parameter annotations such as @PathVaribale,
@RequestParam, @RequestHeader etc.
● Reusable business code: It allows us to reuse the existing business object as
a form object or command object instead of creating a duplicate business
object.
● Flexible model transfer: It supports model transfer as name/ value map,
which can be easily integrated with any view technology.
● Customizable handler mapping and view resolution: Spring Web MVC
supports various Handler mapping and View resolution strategies ranging
from simple URL-based configuration to sophisticated, purpose-built
resolution strategies.
● Robust JSP form tag library: Spring 2.0 introduced a powerful JSP form tag
library that simplifies the form design in JSP.

6.3.2 Spring Boot features


Spring MVC requires lots of configurations such as dispatcher servlet, component
scan, handler mapping, view resolver and many more. When an application uses
Hibernate/JPA, it requires configurations such as data source, entity manager,
transaction manager etc.
Spring Boot project aims at simplifying and make it easier to develop a Spring based
web application. Spring Boot brings intelligence and provides auto configuration
features. Spring Boot looks at the framework / jars available in the classpath and

13
Frameworks Available For
J2ee Development –Struts,
existing configuration of the application in order to provide the basic configuration
Spring Boot and Hibernate needed to configure the application. Features of Spring Boot are as follows.
● The guiding principle of Spring Boot is convention over configuration.
● Spring Boot starter simplifies dependency management.
● It also supports the development of stand-alone Spring applications.
● Supports auto-configuration wherever possible.
● It supports production-ready features such as metrics, health checks, and
externalized configuration.
● XML configuration is not required any more.
● It supports embedded servers such as Jetty, Tomcat or Undertow.

6.4 HIBERNATE WITH JPA: FEATURES

Object-relational mapping (ORM, O/RM, and O/R mapping tool) in computer science
is a programming technique for converting data between incompatible type systems
using object-oriented programming languages. ORM makes it possible to perform
CRUD operations without considering how those objects relate to their data source. It
manages the mapping details between a set of objects and the underlying database. It
hides and encapsulates the changes in the data source itself. Thus, when data sources
or their APIs change, only ORM change is required rather than the application that
uses ORM.
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework
which maps the POJOs to relational database tables. The usage of Hibernate as a
persistence framework enables the developers to concentrate more on the business
logic instead of making efforts on SQLs and writing boilerplate code. Hibernate is
having many features as listed below –
● Open Source
● High Performance
● Light Weight
● Database independent
● Caching
● Scalability
● Lazy loading
● Hibernate Query Language (HQL)
Java Persistence API (JPA) is a specification that defines APIs for object relational
mappings and management of persistent objects. JPA is a set of interfaces that can be
used to implement the persistence layer. JPA itself doesn’t provide any
implementation classes. In order to use the JPA, a provider is required which
implements the specifications. Hibernate and EclipseLink are popular JPA providers.
Spring Data JPA is one of the many sub-projects of Spring Data that simplifies the
data access for relational data stores. Spring Data JPA is not a JPA provider; instead it
wraps the JPA provider and adds its own features like a no-code implementation of
the repository pattern. Spring Data JPA uses Hibernate as the default JPA provider.
JPA provider is configurable, and other providers can also be used with Spring Data
JPA. Spring Data JPA provides a complete abstraction over the DAO layer into the
project.

6.5 COMPARISON AMONG THESE


FRAMEWORKS
Spring, Struts and Hibernate are parts of MVC architecture. These frameworks serve
different purposes and can exist independently or together. It depends on the
project requirement to choose the combination of frameworks. This section gives an
14
overview of comparison among the various frameworks such as Spring Vs Struts, Frameworks for J2EE
Spring Boot Vs Spring MVC and Spring Vs Hibernate. In the subsequent units Spring,
Spring Boot and Hibernate have been explained in detail.

6.5.1 Struts Vs Spring

Struts Spring

An open source framework which enables An open source framework to implement


to extend Java Servlet API and MVC inversion of Control (IOC) and dependency
framework. Injection (DI).

It is a Heavyweight framework. It is a Lightweight framework.

It is less flexible than Spring. It is more flexible than Struts.

It has non layered architecture. It has layered architecture.

It is tightly coupled. It is loosely coupled.

It also provides integration with ORM and It provides an easy integration with ORM and
JDBC but manual coding is required. JDBC technologies.

6.5.2 Spring Boot Vs Spring MVC

Spring Boot Spring MVC

Spring Boot removes all boilerplate code Spring MVC requires a lot of configuration and
and supports the auto configuration based it contains a lot of boilerplate code.
on jars available into classpath.

Spring Boot provides many spring boot Dependency management is a tough process
starters. Spring boot starter is a unit of since every dependency with the correct version
related dependencies wrapped together. It needs to be declared.
solves the problem of dependency
management.

Spring Boot makes the application Spring MVC requires a lot of configurations and
development easier and faster. dependency management is time consuming.
Hence, development is slow.

Spring Boot supports embedded servers to A lot of manual configuration is required to


be packaged along with applications to run attain the same level of packaging.
the jar stand alone.

Spring Boot supports many production Spring MVC does not support any production
ready features such as Actuators, Process ready feature.
monitoring out-of-box.

Spring Boot is very flexible and provides Spring MVC is designed only for the
many modules which can be used to build development of dynamic web pages and
many different other applications. RESTful web services.

15
Frameworks Available For
J2ee Development –Struts, 6.5.3 Spring Vs Hibernate
Spring Boot and Hibernate
Spring Hibernate

Spring is an open source, complete and Hibernate is an ORM framework specialized in


modular application framework to develop data persisting and data retrieval from DB.
enterprise applications in java.

Spring provides many useful features such Hibernate provides Object-Relational


as transaction management, aspect-oriented Persistence and Query service for applications.
programming and dependency injection
(DI).

Spring framework has many modules such Hibernate does not have modules like Spring
as Spring-Core, Spring-MVC, Spring-Rest, framework.
Spring-Security and many more.

Spring framework has support for Hibernate supports robust connection pooling
connection pooling by changing the features. Hibernate supports two levels of cache
configuration in the spring configuration which improves the application performance.
file.

☞ Check Your Progress 2:

1) What are the advantages of Spring Web MVC?

2) Discuss the features of Spring Boot.

3) Explain Hibernate with its advantages.

4) Compare the Struts and Spring frameworks.

16
Frameworks for J2EE

5) Compare Spring Boot and Spring MVC.

6.6 MAVEN: INTRODUCTION, OVERVIEW AND


CONFIGURATION

Building the process of a software project may involve a series of tasks among
downloading required dependencies, putting jars on classpath, generating source code
(for auto generated code), generating documentation from source code, source code
compilation, tests execution, packaging compiled code along with the dependencies
into deployable artifacts such as WAR, EAR or JAR and deploying the generated
artifacts to the application server or repository.
Maven is a simple and powerful build automation and management tool used
primarily for Java Projects. It can also be used to build and manage other language
projects such as C#, Scala, Ruby, etc. A manual build process is error prone and time
consuming. Maven minimizes the risk of humans making errors and speeds up the
build process of a software project.

6.6.1 Maven Installation


JDK installation is the prerequisite to execute maven into the system. Visit
http://maven.apache.org/download.cgi to download the maven. Extract the
downloaded file and perform the following configurations in order to execute maven.
● Set JAVA_HOME environment variable pointing to valid JDK installation
path.
● Set M2_HOME environment variable pointing to the directory of extracted
maven.
● Add the executable maven path into PATH variable as %M2_HOME%\bin
on Windows and %M2_HOME%/bin on Unix.
Open a command prompt and execute the command mvn –version to check the maven
installation and configuration. You will get the output similar to below.

Figure 6.9: Maven Version Verification

17
Frameworks Available For
J2ee Development –Struts, 6.6.2 Maven Core Concepts
Spring Boot and Hibernate
POM file (Project Object Model) is the focal point of a maven project. A maven
project is configured using a POM file known as pom.xml. A POM file is an XML file
which describes the project and contains all the references of project resources like
source code, test code, dependencies etc. Maven execution and the main content of the
POM file has been illustrated below.

Figure 6.10: Maven Execution Flow

6.6.2.1 Basic Structure of the POM File


Basic structure of a typical POM file contains project identifiers, dependencies,
properties, build etc. POM file also supports the concept of profile. Profiles are used
to customize the build configuration for different environments such as dev, test and
prod. A sample POM file example is shown below.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven‐v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>DemoWebApp</artifactId>
<version>1.0‐SNAPSHOT</version>
<packaging>war</packaging>
<name>DemoWebApp Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF‐
8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet‐api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>

18
<groupId>junit</groupId> Frameworks for J2EE
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>Demo WebApp</finalName>
</build>
</project>

● Project Identifiers: Maven combines groupId:artifactId:version (GAV) to form


the unique identifier to identify a project uniquely.
⮚ groupId – a unique base name of the group or company of the project
creator
⮚ artifactId – a unique name for the project
⮚ version – a version of the project
⮚ packaging – a packaging format of the project such as JAR, WAR, EAR,
ZIP. If the packaging type is pom, Maven does not create anything for
this project since it is just meta-data.
● Dependencies: A mid-scale or large scale project uses external Java APIs or
frameworks which are packaged in their own JAR files. These Jar files for Java
APIs or frameworks are known as dependencies. A dependency JAR may again
depend on other dependencies. Keeping projects up-to-date with the correct
version of external dependencies a comprehensive task. Downloading all these
external dependencies (JAR files) recursively and making sure that the right
versions are downloaded is cumbersome.
Maven has a built-in powerful dependency management feature. To make the
project dependencies available into classpath, we just need to specify all the
required dependencies with GAV (groupId, artifactId, version) as shown in
sample pom.xml. Maven downloads all the dependencies recursively and puts
them into the local maven repository.
● Maven Repositories: Maven repositories are directories of packaged JAR files
with extra Meta data. There are three types of repository in Maven.
⮚ Local Repository – As the name indicates, it’s a repository located on the
developer's machine itself. Maven downloads the dependencies from
Central repository, Remote repositories and stores it into the Local
Repository. By default, the Local Repository location is user-home/.m2.
⮚ Central Repository – The Central Repository is maintained and provided
by the maven community. The Central Repository access does not require
any specific configuration. It can be accessed at
https://mvnrepository.com/ and maven dependencies can be searched.
19
Frameworks Available For
J2ee Development –Struts,
⮚ Remote Repository – A Remote Repository is like the Central
Spring Boot and Hibernate Repository from where maven can download the dependencies and store
it into Local Repository. It may be located on any web server on the
internet or the local network. It can be configured into pom.xml by
putting the following contents just after <dependencies> element.

<repositories>
<repository>
<id>test.code</id>
<url>http://myremote.maven.com/maven2/lib</url>
</repository>
</repositories>

● Properties: Custom properties make the pom file readable and maintainable.
Example to use custom properties is shown below.

<properties>
<spring.version>4.3.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
If we want to upgrade the spring to a newer version, we just need to change the
version at one place only for custom property <spring.version> to update all
required dependencies versions for spring.
● Build: The build section provides information about the default maven goal, the
final name of the artifact and the directory for the compiled project. The default
build section is like shown below.

<build>
<defaultGoal>install</defaultGoal>
<finalName>${artifactId}-${version}</finalName>
<directory>${basedir}/target</directory>
//...
</build>

⮚ Default goal is install


⮚ Final name of the artifact contains artifactId and version. It can be
modified at any time into the build section.
⮚ The default output folder for the generated artifact is target folder.

20
Frameworks for J2EE
6.6.2.2 Maven Build Life Cycles, Phases and Goals
Maven follows a build life cycle while building an application. The build life cycle
consists of phases and phase consists of build goals.
● Build Life Cycle: Maven has 3 built-in build life cycles which are responsible for
different aspects of building a software project. These build life cycles execute
independent of one another. For two different build life cycles, you have to use
two different maven commands and these build life cycles will execute
sequentially. The build life cycles are as followings-
⮚ default - The default build lifecycle is of most interest since this is what
builds the code. It is responsible to handle everything related to compiling
and packaging the software project. This build life cycle can’t be
executed directly. You need to execute a build phase or goal from the
default build life cycle.
⮚ clean - The clean build life cycle performs the tasks related to cleaning
such as deleting compiled classes, removing previous jar files, deleting
the generated source codes, removing temporary files from the output
directory etc. The command mvn clean cleans the project.
⮚ site - The site build life cycle performs the task related to generating
documents for the project.
● Build Phases: A Maven phase represents a stage in the Maven build life cycle.
Each phase performs a specific task. The most commonly used build phases
defined for default build life cycle are as follows.

Build Phase Description

validate Verifies the correctness of the project and make sure that all required
dependencies are downloaded.

Compile Compiles the source code to produce the binary artifacts

Test Executes the unit test cases using a suitable unit testing framework
without packaging the binary artifacts

Package Packs the binary artifacts into distributable format such as


JAR,WAR,EAR

intergration- Executes integration test cases which require packaging.


test

Verify Verifies the correctness of package

Install Installs the package into local maven repository

Deploy Copies the final package to the remote repository for sharing with other
developers and projects.

Maven allows us to execute either a whole build life cycle such as clean or site, a
build phase like deploy which is a phase of default build life cycle, or a build goal
like sunfire:test.
Note: The execution of a phase using command mvn <phase> does not execute
only the specified phase. Instead it executes all the preceding phases as well. The
execution of mvn install will execute all other phases in the above table.

21
Frameworks Available For
J2ee Development –Struts,
● Build Goals: The finest step in the maven build process is a Goal. A goal can be
Spring Boot and Hibernate bound to zero or more build phases. A phase helps to determine the order in
which the goals are executed.
⮚ Command mvn <goal> executes a goal which is not bound to any phase.
⮚ Command mvn <phase>:<goal> executes a goal which is bound to a
phase.
6.6.2.3 Maven Build Profiles
Different build configurations are required for different environments such as
production, test, dev. The concepts of Maven Build Profiles enable us to keep the
multiple environments build configuration into a single pom.xml file. A sample
example to create the configuration based on profiles is shown below.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>maven-demo</artifactId>
<version>1.0.0</version>
<profiles>
<profile>
<id>production</id>
<build>
<plugins>
<plugin>
//...
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>development</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
//...
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

In the above configuration development profile is set as default. If we want to execute


production profile build, it can be executed as mvn clean install –Pproduction. The
flag –P is used to provide the profile to be used for the build process.

22
Frameworks for J2EE
6.7 CREATE FIRST PROJECT USING MAVEN
This section describes how to create a simple Hello World java application using
Maven. The Maven project will be created using the command line, and pom.xml will
be modified to execute the jar file using maven plug-in. Perform the following steps
and execute the application using maven command.
Step 1: Create a simple Hello World Java project using the below command. The
command will generate the directory structure and pom.xml file. The generated
directory structure is shown in the screenshot.
mvn archetype:generate -DgroupId=org.test -DartifactId=hello-world -
DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Figure 6.11: Maven Project Folder Structure

Step 2: Simple Hello World application is ready to be compiled and packaged.


Update the pom.xml as below.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>hello-world</artifactId>
<name>hello-world</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
23
Frameworks Available For
J2ee Development –Struts,
Execute the following commands and check the output on the console.
Spring Boot and Hibernate ⮚ mvn compile : Maven will execute all the required phases for compile
phase and build the binary artifact.
⮚ mvn test: Only test phase can be executed with this command.
⮚ mvn package : It packages the binary artifact with the specified package
type such as jar, war, ear etc. Default packaging type is jar and the
generated jar file is located into the target folder.
Step 3: Add the following plug-in into the build section after compiling the plug-in.
The plugin requires the main class into configuration. Update the main class. This
added plug-in will enable the jar file execution from maven command.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<mainClass> org.test.App</mainClass>
</configuration>
</plugin>

The command mvn exec:java will execute the jar file. The output for the command
execution is shown below:

Figure 6.12: Maven Execution Result

☞ Check Your Progress 3:

1) What is Maven? Discuss its usage.

2) Explain about Maven repositories.

24
Frameworks for J2EE

3) Explain the different build life cycles available in the Maven tool.

4) Write down the command to execute a build goal into Maven.

6.8 SUMMARY

The unit has explained the Model 1 and Model 2 architecture of a web application
with its advantages and disadvantages. Model 2 fixes the concerns into Model 1
architecture and Struts fixes the issues into Model 2 architecture and provides Pull-
MVC (MVC2) based framework to develop enterprise web applications. The features
of different frameworks such as Struts, Spring Boot, Spring MVC and Hibernate have
been explained and these frameworks have been compared. The last section of this
unit has explained Maven as a simple and powerful build and deployment
management tool. The highlights of this unit are as follows.
● The Model-View-Controller (MVC) architecture provides the separation of
concerns and makes the application easy to maintain and easy to develop.
● The Struts2 is enriched with many important features such as support to POJO
based actions, Configurable MVC Components, Integration support to various
frameworks such as Spring, Tiles, Hibernate etc, AJAX support, Validation
support, support to various themes and Template such as JSP, Velocity,
Freemarker etc.
● In model 1 architecture, JSP pages were the focal point for the entire web
application.
● In Model 2 architecture contrast to the Model 1 architecture, a Servlet known
as Controller Servlet intercepts all client requests. The Controller Servlet
performs all the initial request processing and determines which JSP to
display next.
● Spring, Spring MVC and Spring Boot do not compete for the same space
instead, they solve the different problems very well.
● Spring Web MVC framework enables us to develop decoupled web
applications. It introduces the concepts of Dispatcher Servlet,
ModelAndView and View Resolvers to develop loosely coupled web
applications.
● Spring Boot project aims at simplifying and making it easier to develop a
Spring based web application. Spring Boot brings intelligence and provides
25
Frameworks Available For
J2ee Development –Struts,
auto-configuration features. Spring Boot looks at the framework / jars
Spring Boot and Hibernate available in the classpath and existing configuration of the application in order
to provide the basic configuration needed to configure the application.
● Maven is a simple and powerful build automation and management tool used
primarily for Java Projects. Maven minimizes the risk of humans making
errors and speeds up the build process of a software project.
● The concepts of Maven Build Profiles enable us to keep the multiple
environments build configuration into a single pom.xml file.

6.9 SOLUTIONS/ ANSWER TO CHECK YOUR


PROGRESS

Check Your Progress 1

1) In model 1 architecture, JSP pages are the focal point for entire web applications.
JSP provides the solutions to the problems of Servlet technology. JSP provides
better separation of concern not to mix business logic and presentation logic. Re-
Deployment of web applications is not required if the JSP page is modified. JSP
supports JavaBean, custom tags and JSTL to keep the Business logic separate
from JSP. Refer section 6.2.1.1 for architecture diagram and advantages and
disadvantages.
2) In Model 2 architecture contrast to the Model 1 architecture, a Servlet known as
Controller Servlet intercepts all client requests. The Controller Servlet performs
all the initial request processing and determines which JSP to display next. Refer
section 6.2.1.2 for architecture diagram and advantages and disadvantages.
3) Actions are the core of Struts2 framework. These are used to provide the business
logic which executes to serve the client request. Each URL is mapped to specific
action. In Struts2, the action class is simply POJO (Plane Old Java Object). The
only prerequisites for a POJO to be an action is that there must be a no-argument
method that returns either a String or Result Object. If the no-argument method is
not specified, the execute() method is used to perform business logic processing.
Refer section 6.2.3
Check Your Progress 2

1) Spring Web MVC framework enables us to develop decoupled web applications.


It introduces the concepts of Dispatcher Servlet, ModelAndView and View
Resolvers to develop loosely coupled web applications. Spring MVC holds many
unique features listed below.
o Clear separation of responsibility
o Adaptability and flexibility
o Reusable business code
o Flexible model transfer
o Customizable handler mapping and view resolution
o Robust JSP form tag library
2) Spring Boot project aims at simplifying and making it easier to develop a Spring
based web application. Spring Boot brings intelligence and provides auto
configuration features. Spring Boot looks at the framework / jars available into the
classpath and existing configuration of the application in order to provide the
basic configuration needed to configure the application. Features of Spring Boot
are as follows.
o The guiding principle of Spring Boot is convention over
configuration.
o Spring Boot starter simplifies dependency management.
o It also supports the development of stand-alone Spring applications.
26
o Supports auto-configuration wherever possible. Frameworks for J2EE
o It supports production-ready features such as metrics, health checks,
and externalized configuration.
o XML configuration is not required anymore.
o It supports embedded servers such as Jetty, Tomcat or Undertow.

3) Hibernate is a pure Java object-relational mapping (ORM) and persistence


framework which maps the POJOs to relational database tables. The usage of
Hibernate as a persistence framework enables the developers to concentrate more
on the business logic instead of making efforts on SQLs and writing boilerplate
code. Hibernate is having many features as listed below –

o Open Source
o High Performance
o Light Weight
o Database independent
o Caching
o Scalability
o Lazy loading
o Hibernate Query Language (HQL)
4) Refer the section 6.5.1
5) Refer the section 6.5.2
Check Your Progress 3

1) Maven is a simple and powerful build automation and management tool used
primarily for Java Projects. It can also be used to build and manage other
language projects such as C#, Scala, Ruby, etc. Manual build process is error
prone and time consuming. Maven minimizes the risk of human making errors
and speeds up the build process of a software project. Maven is used to perform
many tasks like:
o We can easily build a project using maven.
o We can add jars and other dependencies of the project easily using the
help of maven.
o Maven provides project information (log document, dependency list, unit
test reports etc.)
o Maven is very helpful for a project while updating the central repository
of JARs and other dependencies.
o With the help of Maven, we can build any number of projects into output
types like the JAR, WAR etc, without doing any scripting.
o Using maven, we can easily integrate our project with source control
systems (such as Subversion or Git).

2) Maven repositories are directories of packaged JAR files with extra Meta data.
There are three types of repositories in Maven.
o Local Repository
o Central Repository
o Remote Repository
Refer the section 6.6.2.1

3) Refer Build life cycle in section 6.6.2.2

4) The finest step in the maven build process is a Goal. A goal can be bound to zero
or more build phases. A phase helps to determine the order in which the goals are
executed.
o Command mvn <goal> executes a goal which is not bound to any phase.
o Command mvn <phase>:<goal> executes a goal which is bound to a
phase.
27
Frameworks Available For
J2ee Development –Struts,
Spring Boot and Hibernate
6.10 REFERENCES/ FURTHER READING

● Craig Walls, “Spring Boot in action” Manning Publications, 2016.


(https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)
● Christian Bauer, Gavin King, and Gary Gregory, “Java Persistence with
Hibernate”, Manning Publications, 2015.
● Ethan Marcotte, “Responsive Web Design”, Jeffrey Zeldman Publication,
2011(http://nadin.miem.edu.ru/images_2015/responsive-web-design-2nd-
edition.pdf)
● Tomcy John, “Hands-On Spring Security 5 for Reactive Applications”, Packt
Publishing,2018
● https://mkyong.com/tutorials/struts-2-tutorials/
● https://www.tutorialspoint.com/struts_2/struts_overview.htm
● https://www.javatpoint.com/struts-2-tutorial
● https://www.codejava.net/frameworks/struts/introduction-to-struts-2-
framework#vsStruts1
● https://stackoverflow.com/questions/17441926/push-vs-pull-model-in-mvc
● https://www.baeldung.com/maven
● http://tutorials.jenkov.com/maven/maven-tutorial.html#maven-pom-files
● https://howtodoinjava.com/maven/maven-dependency-management/
● https://www.quora.com/Whats-the-difference-between-J2EE-Struts-with-
Hibernate-and-J2EE-Hibernate-with-Spring-framework

28
UNIT 7 SPRING MVC CONCEPTS
Structure Page no.

7.0 Introduction 1
7.1 Objectives 2
7.2 Setting up Development Environment for Spring MVC 3
7.3 First Hello World Project using Spring MVC 5
7.4 Inversion of Control (IoC) and Dependency Injection 9
7.5 Creating Controllers and Views 10
7.6 Request Params and Request mapping 13
7.7 Form Tags and Data binding 14
7.8 Form Validation 18
7.9 Summary 20
7.10 Solutions/ Answer to Check Your Progress 20
7.11 References/Further Reading 22

7.0 INTODUCTION

The Spring MVC framework is an open source Java platform. This framework was
developed by Rod Johnson and it was first released in June 2003 under the Apache
2.0 license. In web based applications, the size of code plays a vital role.This
framework is lightweight when it comes to size. This leads this framework to reach
its heights. The basic version of this framework is of around 2MB. It follows the
MVC (Model-View-Controller) design pattern. Spring Framework gears all the basic
features of a core spring framework like Inversion of Control, and Dependency
Injection.
MVC is a software structural design - the building of the system - that separates the
business logic (domain/application/business) (whatever the way business prefers) from
the rest of the user interface. The MVC does it by separating the whole application
into three parts: the model, the view, and the controller.

The Spring MVC Dispatcher servlet acts as glue and this act makes it the most
important component. It finds the correct methods and views for received incoming
URL. This can be considered as a middleware as it receives the URL via HTTP
request and it communicates with two ends – the sender of HTTP request and the
Spring application. The Dispatcher servlet allows the use of all the features of Spring
and it is completely integrated in the IoC container.

A the Spring Framework is modular in nature, it can be used in parts instead of using
the whole of it. Java & Web applications can be built by using Spring Framework.

7.1 OBJECTIVES

After study this unit you should be able to:


• explain Spring MVC Framework,
• setup Spring MVC Development Environment,
• develop simple projects using Spring MVC,
• create control and views using MVC,and
• perform forms validation.
1
Spring MVC Concepts

7.2 SETTING UP DEVELOPMENT


ENVIRONMENT FOR SPRING MVC

Spring Framework is used widely in the market and there are many Solution that have
been developed by keeping Spring Framework as core architecture. It is widely used
in the market as well and SAP Hybris is one such example.

Spring Framework is used to build almost anything, it's make coding in Java much
easy as it takes care of most of boilerplate (Boilerplate term refers to standardized
text, methods, or procedures that can be used again without making any major
changes to the original. It is mainly used for efficiency and to increase standardization
in the structure and language of written or digital documents) code and let developer
work on business logic.
Spring can be used to build any kind of applications (web application, enterprise
application, REST APIs and distributed systems) with spring cloud and Angular
framework which makes it more useful/popular.

As we discussed above Spring Framework is modular in nature which suggests that


Spring Framework it’s not a single entity. It has been divided into several modules
which serve their own functionality:

• Spring Framework allows application to integrate with various other


backend technologies.
• Spring Framework allows the development of standalone applications.
• Spring Framework becomes very useful while using distributed
architecture.
• Due to lightweight in nature it reduces the complexity while using EJBs.
• Spring Security make the applications more secure.
• Spring Batch competently manage long running tasks.
• IoC and DI adds up to the flexibility and modularity of the application.

Spring offers a one-stop shop for all the business needs to develop applications. Due
to its nature of modularity, it allows to pick and choose the modules which are more
suitable to the business and technical demand without resorting to the whole stack.
The following diagram provides details about all the modules available in Spring
Framework.
As all the below modules are the part of Spring Framework libraries hence we need to
download all these libraries and need setup to take all the below modules’ advantage.

2
Frameworks for J2EE

Figure 7.1: Spring Framework


Core Container: The Core Container contains the Core, Beans, Context, and
Expression Language modules, the details of which are as follows −
• IoC and DI features are the main features of the Framework which comes
under the core container as it provides the fundamental parts of the
framework.
• BeanFactory comes under Bean module, it helps in the implementation of the
factory pattern.
• Core and Beans module provides the strong base to build the Context module
and it becomes the middleman to access any defined and configured object.
The Context module works as a focal point of Application Context.
• A powerful expression language for querying and manipulation an object
graph at runtime is provided by SpEL module,
The Data Access/Integration:This layer involves the JMS, OXM, ORM, & JDBC
and Transaction modules and below are the details −
• It eliminates the need of religious JDBC related coding efforts of the
developer as this JDBC module provides a JDBC-abstraction layer.
• The ORM Module takes care integration layer for some popular object-
relational mapping APIs like iBatis, Hibernate, JDO and JPA.
• Object/XML mapping implementations for some APIs like XStream, JiBX,
XMLBeans, Castor and JAXB are supported by the OXM Module.
• The Java Messaging Service JMS module holds features for producing and
consuming messages.

3
Spring MVC Concepts
• The Programmatic and declarative transaction management for classes that
implement special interfaces and for all your POJOs are done by the
Transaction Module.

Web: The Web layer holds of the following modules (Web, Web-MVC, Web-
Socket, and Web-Portlet) and the details of these are as follows:
• Basic featurs for multipart file-upload functionality and the initialization of
the IoC container using servlet listeners and a web-oriented application
context provided by the Web Module.
• Spring's Model-View-Controller (MVC) implementation for web applications
is covered under Web-MVC.
• The Web-Socket module takes responsibility of communication (support for
WebSocket-based, two-way communication between the client and the
server in web applications).
• The Web-Portlet module covers the MVC implementation to be used in a
portlet setup and emulates the functionality of Web-Servlet module.
Miscellaneous:AOP, Aspects, Instrumentation, Web and Test modules are also some
other important modules and the details of these are as follows −
• To decouple code, there is a need to define method-interceptors and pointcuts
and this is achieved by AOP Module as it provides an aspect-oriented
programming implementation.
• AspectJ integration is achieved by the Aspects Module and AspectJ is mature
and powerful AOP Framework.
• This module is basically based on application servers as class loader and
class instrumentation is used and supported by The Instrumentation Module.
• Support of Streaming Text Oriented Messaging Protocol (STOMP) as the
WebSocket sub-protocol to use in applications is provided by
the Messaging Module.
• JUnit or TestNG frameworks are used for Spring Components Testing and all
this is done by Test Module

Java IDE Setup

It is always good to use integrated development environment (IDE) for any kind of
java development as it increases the efficiency of the developer. An IDE is used for
programming in Java or any other language provided by any IDE. IDE basically
provides the functionality like debugging of the code, compilation of the code,
interpreter for java like languages with code editor. Developer perform all the above
mentioned activities with the help of graphical interface (GUI).

We would like to suggest you to use latest version of Eclipse or Netbean for your
programming exercises.

Suppose you install Eclipse or other IDE on your syste. For example once IDE
downloaded the installation, unpack the binary distribution into a convenient
location. For example, in C:\eclipse. Eclipse can be started by double-click on
eclipse.exe

4
Frameworks for J2EE

Figure 7.2: Eclipse IDE Setup

Setup Spring Framework Libraries

Once IDE setup is done then download the latest version of Spring framework
binaries from https://repo.spring.io/release/org/springframework/spring.

Figure7.3: Downloading Spring IDE

7.3 FIRST HELLO WORLD PROJECT USING


SPRING MVC

We will see in the example given below how to write a simple Hello World
application in Spring MVC Framework. First thing to notice is to have Eclipse or
some other IDE in place and follow the steps to develop a Dynamic Web Application.
Here Eclip IDE is used for explanations.

Step 1:

Create a Dynamic Web Project with a name HelloIGNOU and create a package
com.ignou the src folder in the created project.

Step 2:

Drag and drop below mentioned Spring and other libraries into the folder
WebContent/WEB-INF/lib.
5
Spring MVC Concepts

Step 3:

Create a Java class HelloController under the com.ignou.springmvc package.

Step 4:

Create Spring configuration files web.xml and HelloWeb -servlet.xml under the
WebContent/WEB-INF folder.

Step 5:
Create a sub-folder with a name jsp under the WebContent/WEB-INF folder. Create a
view file hello.jsp under this sub-folder.

Step 6:
The final step is to create the content of all the source and configuration files. Once it
is done then you have to export the application as explained below.

Web.xml

HelloWeb -servlet.xml

6
Frameworks for J2EE

HelloController.java

Hello.jsp

Need to include the below list of Spring and other libraries in our web application.
We can do this by drag and drop them in in WebContent/WEB-INF/lib folder.

7
Spring MVC Concepts

Finally, Project Explorer looks as below

Once the source and configuration files are created then you have to export the
application. Do right click on the application and use Export > WAR File option for
saving HelloWeb.war file in Tomcat’s webapps folder or deploy this war file to any
web/app server via admin role.
8
Frameworks for J2EE
There is another options to run the app directly on the server from Eclipse.
You can check the working by using URL http://localhost:8080/HelloWeb/hello in
your browser. For this you have to first start the Tomcat Server and using a standard
browser check if you have access to other web pages from webapps folder.

7.4 INVERSION OF CONTROL (IOC)


DEPENDENCY INJECTION

Inversion of Control (IoC): Inversion of Control (IoC) is considered as a design


principle but some of the developer society consider it as a pattern. This is designed to
achieve loose coupling as its name suggests that is used to invert controls on Object-
Oriented design. It also controls the flow of an application and also controls over the
flow of dependent object or an object creation and binding.

Tightly Coupled Classes


Step1

Implement IoC using


Factory Patten
Step2

Implement DIP by
Creating abstraction
Step3

Implement DI
Step4

Use IoC Container


Result

Loosely Coupled Classes

Figure 7.4: Inversion of Control Flow

IoC is all about overturning the control. In other words you can understand this by
this example. Let us assume that you drive your car daily to your work place. This
means you are controling the car. The IoC principle suggests to overturn the control,
meaning that instead of you drive your car yourself, you hire a cab, where driver will
be driving the car. Thus, this is called inversion of the control from you to the cab
driver. Now you don’t need to drive a car yourself but you can let the driver do the
driving so that you can focus on your office work.

Classes of Spring IoC container are part of org.springframework.beans and


9
Spring MVC Concepts
org.springframework.context packages. Spring IoC container provides us different
ways to decouple the object dependencies.

BeanFactory as the root Interface of Spring IoC Container. ApplicationContext is the


child interface of BeanFactory and it provides Spring AOP features, i18n etc.

Dependency Injection:
The Dependency Injection is a design pattern that removes the dependency of the
programs. To removes the dependency of the programs, Dependency Injection design
pattern do this job. In that kind of scenario, information is provided by the external
sources such as XML file. Dependency Injection plays a vital role to make the code
loosely coupled and easier for testing. In such a case we write the code as:

class Ignou
{
Student student;
Ignou(Student student)
{
this.student =student;
}
public void setStudent(Student student)
{
this.student =student;
}
}

We can perform Dependency Injection via following two ways in Spring framework

By Constructor – In the above code, the below snapshot of the code uses the
constructor

Ignou(Student student)
{
this.student =student;
}

By Setter method – In the above code, the below snapshot of the code uses the Setter
method

public void setStudent(Student student)


{
this.student =student;
}

☞ Check you progress 1:


Q1: What do mean by IDE and its benefits?

10
Frameworks for J2EE
Q2: Is Spring Framework open source?

Q3: What is the use of IoC?

Q4: What is DI?

7.5 CREATING CONTROLLERS AND VIEWS


In Spring MVC, controller classes are used to handle the request which are coming
from the client. After getting the request from client then controller starts its task by
invoking a business class to process business-related tasks, and once it gets fulfilled
then it redirects the client request to a logical view name, and now it is resolved by
Spring’s dispatcher servlet in order to render results or output.
Below are the main responsibilities:

• Controllers main task is to intercept the incoming requests.

• Controller Converts the payload of the request to the internal structure of the data
(mapping basically).

• After getting response from above two steps then it sends the data to Model for
further processing,

• Once it gets the processed data from the Model then that data is referred to the
View for rendering/display.

11
Spring MVC Concepts

Below diagram for the high level flow in Spring MVC:

Figure 7.5: High Level Flow in Spring MVC

There are basically two kind of constructors as typical MVC controllers as well as
RESTful controllers and the above diagram caters to both with some small
differences.

In the traditional approach, MVC applications are not service-oriented hence these
applications rely on View technology as data is finally redirected to the views
received from a Controller.
RESTful applications are designed as service-oriented and return raw/response data in
the form of JSON/XML typically.
As data is returned in the form of JSON/XML hence these applications do not have
Views, then the Controller is expected to send data directly via the HTTP response as
per the designed structure.

Below is the example of controller from the above given.

packagecom.ignou;

importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
publicclassHelloIngnouController
{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMapmodel)
{
model.addAttribute("message", "Hello Spring MVC Framework!");
return"hello";
}
}

Views: FrontController design pattern is a fundamental design pattern to any MVC


design and Spring MVC architecture also uses the “FrontController” design pattern.
The DispatcherServlet is considered as the heart of this design as the process of

12
Frameworks for J2EE
dispatching the request to the right cpontroller is achieved by configuring the
DispatcherServlet. This class handles the complete request handling process. It is a
regular servlet as others and can be configured along with any custom handler
mappings.

Spring MVC framework empowers parting of modules namely Model, View, and
Controller and seamlessly handles the application integration. This permits the
developer to develop complex applications also using plain java classes. The model
object is passed between controller and view using Maps objects. Moreover, it also
provides types mismatch validations and two-way data-binding support in the user
interface. Data-binding and form-submission in the user interface becomes possible
with spring form tags, model objects, and annotations.

In this article. We are discussing the steps involved in developing a Spring web MVC
application, it explains the initial project setup for an MVC application in Spring. We
have multiple options to use view technology but in this example we are using
JSP(Java Server Pages) is used as a view technology.

Please find the below example which explains this whole concept of Controllers and
Views.

DispatcherServlet is the root Servlet, or we can say that it is the front controller class
to handle all requests and then to start processing. This needs to configure first in
web.xml file. DispatcherServlet's primary duty is to pass the request to appropriate
controller class and send the response back.

First step towards updating the web.xml.

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


xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns="https://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
https://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd"id="WebApp_ID"version="3.0">
<display-name>IGNOU_Example</display-name>
<!-- Adding DispatcherServlet as front controller -->
<servlet>
<servlet-name>ignou-serv</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class><init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ignou-serv</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

13
Spring MVC Concepts
Second step is to create spring bean configuration file as ignou-serv-servlet.xml.

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


<beans:beansxmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines processing infrastructure -->
<!-- Enables @Controller programming model -->
<annotation-driven />
<context:component-scanbase-package="com.ignou" />
<!-- Resolves views -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:propertyname="suffix"value=".jsp" />
</beans:bean>
</beans:beans>

There are basically three important configurations.

1. @Controller annotation tells DispatcherServlet to look for controller.

2. Where to look for controller classes, it is updated by context:component-scan to


DispatcherServlet.

3. Location of view pages is handled in the configuration of


InternalResourceViewResolver bean.

Third step is to write the controller class.

packagecom.ignou.controller;
importjava.text.DateFormat;
importjava.util.Date;
importjava.util.Locale;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.Model;
importorg.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importcom.journaldev.spring.model.User;
@ControllerpublicclassIgnouController
{
/** * Simply selects the home view to render by returning its name. */
@RequestMapping(value = "/", method = RequestMethod.GET) public String ignou(Locale
locale, Model model)
{
System.out.println("LandingIGNOU Page Requested = " + locale); Date date = newDate();
DateFormatdateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date); model.addAttribute("serverTime",
formattedDate);
return"ignou";
}
14
Frameworks for J2EE
@RequestMapping(value = "/ignoustudent", method = RequestMethod.POST) public String
user(@Validated User user, Model model)
{
System.out.println("IGNOUStudent Page Requested"); model.addAttribute("studentName",
ignoustudent.getStudentName());
return"ignoustudent";
}
}

Fourth step is to define Model. This class can be represented by many names like
Bean Class, POJO Class or Model Class.

packagecom.ignou.model;
publicclassIgnoustudent
{
private String studentName;
public String getStudentName()
{
returnstudentName;
}
publicvoidsetStudentName(String studentName)
{
this.studentName = studentName;
}
}

Now the last step is to create the View Pages.

Ignou.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%@ tagliburi="https://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
<title>IGNOU Landing Page</title>
</head>
<body>
<h1>Spring MVC Example For IGNOU</h1>

<P>The time on the server is ${serverTime}.</p>

<form action="user" method="post">


<input type="text" name="studentName"><br> <input
type="submit" value="Login">
</form>
</body>
</html>

Student.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
15
Spring MVC Concepts
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>IGNOU Student Home Page</title>
</head>
<body>
<h3>Hello ${studentName}</h3>
</body>
</html>

This above example basically explains that what configurations are needed to do in
web.xml and how do we define root servlet (DispatcherServlet) and defining of
controllers, models, and views.

Lastly, we have to always remember below three important configurations.

1. @Controller annotation tells DispatcherServlet to look controller.

2. Where to look for controller classes, it is updated by context:component-scan to


DispatcherServlet.

3. Location of view pages is handled in the configuration of


InternalResourceViewResolver bean.

☞ Check you progress 2:


Q1. What is an Init Binder?

Q2. What is the front controller class of Spring MVC?

Q3.What is the difference between @Component, @Controller, @Repository &


@Service annotations?

Q4.What is does the ViewResolver class?

16
Frameworks for J2EE

7.6 REQUEST PARAMS AND REQUEST


MAPPING
Request parameters can be read in controller class with the help of RequestParam
annotation. Or we can say that views are sending some parameters with keys.

We can explain this with the help of student details which we want to add into
database.

Student_ID
Student_FirstName
Student_LastName
Student_DOB

Just imagine that we have filled the below details.

Student_ID=1001 (depends upon requirement as it may be system generated)


Student_FirstName=Dharmendra
Student_LastName=Singh
Student_DOB =21.01.1979

So, we have the below code for this

@Controller
@RequestMapping("/ignoustudent/*")
public class IgnouStudentController
{
@GetMapping("/fill")
public String fill()
{
return "studentForm";
}
@PostMapping("/fill/process")
public String processForm(ModelMap model, @RequestParam("Student_ID")
intstud_id, @RequestParam("Student_FirstName") String stud_firstName,
@RequestParam("Student_LastNAme") String stud_lastName,
@RequestParam("Student_DOB") Date stud_dob)
{
model.addAttribute("Student_ID ", stud_id);
model.addAttribute("Student_FirstName", stud_firstName);
model.addAttribute("Student_LastName", stud_lastName);
model.addAttribute("Student_DOB", stud_dob);
return "index";
}
}

We just binded web request parameters to method parameters (Student_id,


Student_firstName, Student_lastName, Student _DOB).

In the above example, values are passed to request params, as


@RequestParam(“Student_id”). Though this could have not worked if the targent
variable name is same as the param, we could have done it in the way given below:

17
Spring MVC Concepts
@Controller
@RequestMapping("/ignoustudent/*")
public class IgnouStudentController
{
@GetMapping("/fill")
public String fill()
{
return "studentForm";
}
@PostMapping("/fill/process")
public String processForm(ModelMap model, @RequestParamint_id,
@RequestParam("FirstName") String firstName, @RequestParam("LastName")
String lastName)
{
model.addAttribute("Student_id", id);
model.addAttribute("Student_firstName", firstName);
model.addAttribute("Student_lastName", lastName);
model.addAttribute("Student_DOB", dob);
return "index";
}
}

Request Mapping:

Spring Controller supports the three levels of request mapping and it depends on the
different @RequestMapping annotations declared in its handler methods and
controller class.
Please find below the different mapping types:

By path
@RequestMapping(“path”)
By HTTP method
@RequestMapping(“path”, method=RequestMethod.GET).
Other Http methods such as POST,
PUT, DELETE, OPTIONS, and TRACE are also supported.
By query parameter
@RequestMapping(“path”, method=RequestMethod.GET,
params=”param1”)
By the presence of request header
@RequestMapping(“path”, header=”content-type=text/*”)

7.7 FORM TAGS AND DATA BINDING

For the Web Pages, Spring MVC has provided the form tags which are configurable
and reusable building blocks. These Tags are very helpful for easy development, easy
to read and maintain. These Tags can be used as data binding tags where these tags
can set data to java objects (Bean or POJO).

These Tags provide support for corresponding HTML tags.

The form tag library comes under the spring-webmvc.jar. To get the support from the
form tag library,you requires to reference some configuration So, you have to add the
following directive at the beginning of the JSP page:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>


18
Frameworks for J2EE

Some of the below frequently used Spring MVC form tags.

Form Tag Description


form:form It is a container tag that contains all other form tags.
form:input This tag is used to generate the text field.
form:radiobutton This tag is used to generate the radio buttons.
form:checkbox This tag is used to generate the checkboxes.
form:password This tag is used to generate the password input field.
form:select This tag is used to generate the drop-down list.
form:textarea This tag is used to generate the multi-line text field.
form:hidden This tag is used to generate the hidden input field.

Spring data binding mechanism provides the functionality to bound the user inputs
dynamically to the beans. It can explained as it allows the setting property values into
a target object and this functionality is provided by DataBinder class though
BeanWrapper also provides the same functionality but DataBinder additionally
supports field formatting, binding result analysis and validation.

Where DataBinder works on high level and BeanWrapper works on low level. Both
Binders are used in PropertyEditors to parse and format the property values. We
should use the DataBinder as it works on high level and internally it uses the
BeanWrapper only.

Data binding from web request parameters to JavaBean/POJO objects are done by
WebDataBinder.We use it for customizing request param bindings.

We can understand better these topics with the help of the below example:

First, we are going to create a request page (Welcome.jsp)

<html>
<body>
<h2> Spring MVC Form Tag with Data Binding Example for IGNOU Students </h2>
<a href = "home_page">Home page | </a>
<a href = "about_us"> About Us | </a>
<a href = "student_form"> Student Detail Form</a>
</body>
</html>

Create model (getter/setter) class (Student.java)

package com.ignou.studentdetails;
public class Student
{
private String fname;
private String lname;
public Student()
{
}
public String getFname()
{
return fname;
}
public void setFname(String fname)
{
19
Spring MVC Concepts
this.fname = fname;
}
public String getLname()
{
return lname;
}
public void setLname(String lname)
{
this.lname = lname;
}
}

Create the controller (StudentDetailController.java) now

package com.ignou.studentdetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class StudentDetailController
{
@RequestMapping("/student_form")
public String showStudentForm( Model m)
{
Student student = new Student();
m.addAttribute("student", student);
return "studentform" ;
}
@RequestMapping("/studentregis")
public String showStudentData(@ModelAttribute("student") Student student)
{
System.out.println("student:" + student.getFname() +" "+ student.getLname());
return "student-data" ;
}
}

Add the entry of controller in Web.xml

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


<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id = "WebApp_ID" version = "3.1">
<display-name>spring-mvc-demo</display-name>
<absolute-ordering />
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
20
Frameworks for J2EE
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Define model in spring-servlet.xml

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


<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package = "com.app.SpringMVC5" />
<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Step 5: Define Spring MVC view resolver -->
<bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/view/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>

Create the view pages

StudentDetailForm.jsp

<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>


<html>
<head>
<title>Student Detail Form</title>
</head>
<body>
<form:form action = "studentdetail" modelAttribute = "student" >
FIRST NAME: <form:input path = "fname" />
<br></br>
LAST NAME: <form:input path = "lname" />
<br></br>
<input type = "submit" value = "Submit"/>
</form:form>
</body>
</html>

StudentDetailData.jsp

21
Spring MVC Concepts
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1">
<title>Student Detail Data</title>
</head>
<body>
The student name is ${student.fname} ${student.lname}
</body>
</html>

7.8 FORM VALIDATION

Spring Validation is very important as it is used for validating the @Controller


inputs. Using Spring validation, the user input on the server-side can be validated. It
is used for checking and subsequently accepting the user input in any web application.
From Spring framework version 4 and above, the Spring framework supports Bean
Validation 1.0 (JSR-303) and Bean Validation 1.1 (JSR-349).

BindingResult is an an interface that represents the binding results. It extends an


interface for error registration for allowing a validator to be applied, and adds
binding-specific analysis.

In Spring MVC form Validation, a variety of annotations are used. These annotations
are available in javax.validation.constraints package. Below is a list of commonly
used Validation annotations:

Annotations Description

@Valid This annotation is used on a model object that we want to validate

@Size It specifies that the size of the annotated element must be between
thespecified boundaries.
@Pattern It specifies that the annotated CharSequence must match the
regularexpression.
@Past It specifies that the annotated element must be a date in the past.
@Null It specifies that the annotated element must be null.
@NotNull It specifies that the annotated element should not be null.
@Min It specifies that the annotated element must be a number whose value
mustbe equal or greater than the specified minimum number.
@Max It specifies that the annotated element must be a number whose value
mustbe equal or smaller than the specified maximum.
@Future It specifies that the annotated element must be a date in the future.
@Digits It specifies that the annotated element must be a digit or number
within thespecified range. The supported types are short, int, long,
byte, etc.
@DecimalMin It specifies that the annotated element must be a number whose
value must be equal or greater than the specified minimum. It is very
similar to @Minannotation, but the only difference is it supports
CharSequence type.
@DecimalMax It specifies that the annotated element must be a number whose
value should be equal or smaller than the specified maximum. It
is very similarto @Max annotation, but the only difference is it
supports CharSequence type.
22
Frameworks for J2EE
@AssertTrue It determines that the annotated element must be true.
@AssertFalse It determines that the annotated element must be false

We can use the model (Student.java) from previous example and put the validations
inside form class as below

package com.ignou.studentdetails;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student
{
@NotNull
@Size(min =1, message ="You can't leave this empty.")

private String fname;


@NotNull
@Size(min =1, message ="You can't leave this empty.")
private String lname;
public Student()
{
}
public String getFname()
{
return fname;
}
public void setFname(String fname)
{
this.fname = fname;
}
public String getLname()
{
return lname;
}
public void setLname(String lname)
{
this.lname = lname;
}
}
☞ Check you progress 3:
Q1: What do you understand by Tag libraries?

Q2: What are the @RequestBody and the @ResponseBody?

23
Spring MVC Concepts

Q3:State the difference between Request Param & Request Mapping

Q4: What is the Role of the @Autowired Annotation?

7.9 SUMMARY
Spring's Web MVC Framework is very popular and used framework due to its
request-driven, designed around a central Servlet that dispatches requests to
controllers and offers other functionality that facilitates the development of web
applications. It also facilitates fast and parallel development. It Reuses business code -
instead of creating new objects. It allows us to use the existing business objects. It
provides easy to test functionality as we create JavaBeans classes that enable us to
inject test data using the setter methods. This framework is used in many products
development like Hybris and banking domain products.

7.10 ANSWER TO CHECK YOUR PROGRESS

Check you progress 1:

1. An IDE stands for integrated development environment for programming in Java


or any language. It is typically an application software which provide a code
editor, a compiler or interpreter and a debugger that can be accessed by the
application developer using unified graphical user interface (GUI). Also many
Java IDEs includes language-specific elements such as Ant and Maven build
tools and TestNG and JUnit testing.

2. Spring Framework is an open-source framework used for developing web


applications with Java as a programming language. It is a powerful lightweight
application development framework used for Java Enterprise Edition (JEE). We
can also say that it is a framework of frameworks because it provides support to
various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc.

3. The IoC container is responsible to instantiate, configure and assemble the objects.
The IoC contains gets informations from the XML file and works accordingly and
its primary tasks performed by IoC container are:

To instantiate the application class


To configure the object
To assemble the dependencies between the objects

24
Frameworks for J2EE
There are two types of IoC containers. They are:

BeanFactory
ApplicationContext

4. Dependency Injection (DI) is a design pattern which removes the dependency


from the programming code so that it can be easy to manage and test the
application. Dependency Injection makes our programming code loosely coupled.

Check you progress 2:

1. The Init Binder is an annotation that is used to customize the request being sent to
the controller. It is used to to control and format those requests that come to the
controller.

2. A controller is used to handl all requests for a Web Application is called as


Front Controller. DispatcherServlet (actually a servlet) is the front controller in
Spring MVC that not only intercepts every request but also dispatches/forwards
requests to an appropriate controller.

3. One of the major difference between these stereotypes is that these are used for
different classification. You may have different layers like presentation, service,
business, data access etc. in a multitier application. When you try to annotated a
class for auto-detection by Spring, then you should have to use the respective
stereotype as below:

@Component – generic and can be used across application.


@Service – annotate classes at service layer level.
@Controller – annotate classes at presentation layers level, mainly used in Spring
MVC.
@Repository – annotate classes at persistence layer, which will act as database
repository.

4. ViewResolver is an interface wich is to be implemented by objects. This is used


to resolve views by name. There are many other ways also, using which you can
resolve view names. These ways are supported by various in-built
implementations of ViewResolve.

Check you progress 3:


1. Custom tags are implemented and distributed using taglib. It is a structure which
is known as a tag library. A tag library is nothing but a a collection of classes and
meta-information that includes:

• Tag Handlers Java classes. This class implement the functionality of custom
tags.
• Tag Extra Information Classes. These classes are used to supply the JSP
container with logic for validating tag attributes and creating scripting
variables.
• A Tag Library Descriptor (TLD). It is an XML document, used to describe
the properties of the individual tags and the tag library as a whole.

2. @RequestBody and @ResponseBody annotations are used to convert the body of


the HTTP request and response with java class objects. Both these annotations
will use registered HTTP message converters in the process of
converting/mapping HTTP request/response body with java objects.
25
Spring MVC Concepts

3. @RequestMapping is a class or method annotation is used to map the request url


to the java method.
@RequestParam is a (Method) field annotation is used to bind a request parameter
to a method parameter

4. The @Autowired annotation can be used to autowire (placing an instance of one


bean into the desired field of another bean) bean on the setter method just like
@Required annotation, constructor, a property or methods with arbitrary names or
multiple arguments.

7.11 FURTHER READINGS/ REFERENCES

1. Craig Walls, “Spring Boot in action” Manning Publications, 2016.


(https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)
2. Paul Deck, “Spring MVC: a Tutorial”, Brainy Software, 2016.
3. Ian Roughley,”Practical Apache Struts 2 Web 2.0 Projects”, Dreamtech Press,
2008.
4. Ethan Marcotte, “Responsive Web Design”, Jeffrey Zeldman Publication, 2011
5. https://www.oracle.com/java/technologies/java-technology-
6. reference.html#documentation
7. https://spring.io/projects
8. https://www.tutorialandexample.com/spring-mvc-form-validation/

26
UNIT 8 SPRING MVC WITH BOOTSTRAP
CSS
8.0 Introduction
8.1 Objectives
8.2 Configuration of Bootstrap in Spring Application
8.2.1 Different ways to configure Bootstrap
8.3 Apply custom CSS in pages
8.4 Setting UP Database using Hibernate
8.4.1 Java based configuration for Spring and Hibernate Integration
8.5 Create, Read, Update, and Delete (CRUD)
8.5.1 Mapping CRUD to SQL Statements
8.5.2 Mapping CRUD to REST
8.6 CRUD examples in Spring MVC and Hibernate
8.7 Summary
8.8 Solutions/ Answer to Check Your Progress
8.9 References/Further Reading

8.0 INTRODUCTION

Nowadays, huge traffic comes from mobile devices, and most of the internet searches
like google are done on mobile devices, whether smartphones or tablets. The internet
users who search a company to buy food or items, visit the company’s website from
the google link on the mobile devicesthemselves. If a company's website is not
flexible across all screen resolutions and devices, it risks missing out on a large group
of buyers. A responsive website prevents this loss and leads to substantial revenue
gains.
Responsive web design improves user experience and creates a positive perception for
a company or business. If your customers can access your website easily on all
platforms, they’re more likely to return to you for more business in the future.
It is a big challenge for website developers to keep the design responsive as the web
evolves more and more. Bootstrap is the solution to this big challenge and makes
things a whole lot easier. Bootstrap takes care of everything related to responsiveness
without the user need to do the responsive bit. Bootstrap automatically scales in and
out among the devices such as mobile phones, tablets, laptops, desktop computers,
screen readers, etc.
Spring is the most popular and widely used Java EE framework, while Hibernate is
the most popular ORM framework to interact with databases. Spring supports
integrating Hibernate very easily, which makes the Hibernate thefirst choice as an
ORM with Spring.
CRUD is an acronym for CREATE, READ, UPDATE and DELETE operations which
are used in relational database applications and executed by mapping to a SQL
statement or by standard HTTP verbs such as POST, GET, PUT, DELETE. CRUD is
thus data-oriented and uses standardized HTTP action verbs.

8.1 OBJECTIVES

After going through this unit, you will be able to:


● Describe responsive web design and show its advantages,
1
Spring MVC with
● use Bootstrap integration with Spring MVC,
Bootstrap CSS
● apply different approaches to include Bootstrap into Spring MVC,
● include custom CSS into Spring applications,
● do Spring and Hibernate integration,
● do CRUD execution mapping to SQL and Rest Web Service, and
● develop a complete Spring MVC web application with Bootstrap, custom CSS
and Hibernate.

8.2 CONFIGURATION OF BOOTSTRAP IN


SPRING APPLICATION
Bootstrap was originally created by a designer and developer at Twitter in mid 2010.
Prior to being an open-sourced framework, Bootstrap was known as Twitter Blueprint.
Bootstrap is a free, popular and open-source CSS framework directed at
responsive, mobile-first front-end web development. Unlike many web frameworks, it
concerns itself with front-end development only. It contains HTML and CSS based
design templates for various interface components such as typography, forms, buttons,
modals, image carousels, navigation etc., as well as optional JavaScript extensions.
Bootstrap provides the ability to create responsive designs faster and easily.
Responsive Web Design (RWD) is an approach to web design that makes web pages
adjust automatically to look good and render well on a variety of devices and window
or screen sizes from minimum to maximum display size. The various factors which
support learning Bootstrap are as follows.
● Browser Support: Bootstrap supports all popular web browsers such as
Chrome, Safari, Firefox, Opera, and Internet edge.
● Responsive Design: Bootstrap enables us to write responsive websites very
easily. Its responsive CSS adjusts automatically to Desktops, Tablets and
Mobiles.

● Uniform solution to build interface: Bootstrap provides a clean and uniform


solution to build an interface for the developers.
● Customization: Bootstrap provides a simple and easy way to customize the
CSS.
● Functional built-in components: Bootstrap contains beautiful and functional
built-in components which can be customized very easily.

8.2.1 Different ways to configure Bootstrap

The Bootstrap 5 is the most recent version of the Bootstrap framework.There are two
ways to include Bootstrap into JSP or HTML.The required configurations for
Bootstrap 4 and Bootstrap 5 has been described as follows.
1. Bootstrap through Content Delivery Network (CDN)

Bootstrap CDN is an efficient and faster way to deliver the content from your
website to the users. Bootstrap CDN speeds up the websites as CDN servers are
intelligent enough to serve the resources based on proximity.

2
Introduction to J2EE
Including Bootstrap 4 into JSP/HTML. Frameworks

For some of the functionalities Bootstrap 4 JavaScript file requires jQuery and
Popper JavaScript, and these two must be loaded before loading of
bootstrap.min.js file.
● CSS: Include the below link to the <head> tag of your desired HTML/JSP
file.
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/boots
trap.min.css" integrity="sha384‐
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">

● JS: Place the following <script>s near the end of your pages, right before
the closing </body> tag, to enable them. jQuery must come first, then
Popper.js, and then our JavaScript plugins.
<script src="https://code.jquery.com/jquery‐3.3.1.slim.min.js"
integrity="sha384‐
q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/p
opper.min.js" integrity="sha384‐
UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>

<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstr
ap.min.js" integrity="sha384‐
JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>

Including Bootstrap 5 into JSP/HTML

Bootstrap 5 no longer needs jQuery as a dependency since JavaScript can provide


the same functionality. Add the following CSS and JS through Bootstrap 5 CDN
to JSP/HTML:
● CSS: Copy-paste the below Stylesheet link to the <head> tag of your
desired HTML/JSP file.
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootst
rap.min.css" rel="stylesheet" integrity="sha384‐
EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">

● JS: Place the following <script>s near the end of your pages, right before
the closing </body> tag.
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/po
pper.min.js" integrity="sha384‐
IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstra
p.min.js" integrity="sha384‐
cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF"
crossorigin="anonymous"></script>

3
Spring MVC with
2. Custom configuration of Bootstrap with Spring MVC (Offline by
Bootstrap CSS
downloading files locally)
Another approach to include Bootstrap is to directly download the Bootstrap CSS
and JS files locally to the project folder and then include the local copy into
JSP/HTML. The following links can be used to download the Bootstrap.
● Bootstrap 4: https://getbootstrap.com/docs/4.3/getting-started/download/

● Bootstrap 5: https://v5.getbootstrap.com/docs/5.0/getting-started/download/

Download the Bootstrap and perform the following steps to configure Bootstrap
in the Spring application.
i. Put static resources CSS and JS files into webapp/resources/static
directory. To segregate CSS and JS, keep them into respective folders
webapp/resources/static/js and webapp/resources/static/css into the
eclipse project.
ii. Create the resource mapping into Spring using either XML configuration
or Java configuration.

XML configuration

<mvc:resources mapping="/js/**" location="/resources/static/js/" />


<mvc:resources mapping="/css/**" location="/resources/static/j=css/" />

Java configuration

@Configuration
@EnableWebMvc
public class MyApplication implements WebMvcConfigurer
{
public void addResourceHandlers(final ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/js/**").addResourceLocations("/resources/static/js/");
registry.addResourceHandler("/css/**").addResourceLocations("/resources/static/css/");
}
}

iii. Include the Bootstrap CSS and JS into JSP page via JSTL tag c:url or
Spring tag spring:url.
JSTL tag c:url
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="<c:url value="/css/bootstrap.css" />" rel="stylesheet">
<script src="<c:url value="/js/jquery.1.10.2.min.js" />"></script>
<script src="<c:url value="/js/bootstrap.js" />"></script>
</head>
<body>
</body>
</html>

Spring tag spring:url

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>


<!DOCTYPE html>
<html lang="en">
<head>

4
<spring:url value="/css/bootstrap.css" var="bootstrapCss" /> Introduction to J2EE
<spring:url value="/js/jquery.1.10.2.min.js" var="jqueryJs" /> Frameworks
<spring:url value="/js/bootstrap.js" var="bootstrapJs" />

<link href="${bootstrapCss}" rel="stylesheet" />


<script src="${jqueryJs}"></script>
<script src="${bootstrapJs}"></script>
</head>
<body><body>
</body>
</html>

☞Check Your Progress 1


1) What is Bootstrap and what factors make Bootstrap a popular choice to use in
web applications?
…………………………………………………………………………………

…………………………………………………………………………………

……………………………………………............................…………………

…………………………………………………………………………………

2) What are the different ways to configure Bootstrap in Spring MVC?


…………………………………………………………………………………

…………………………………………………………………………………

……………………………………………............................…………………

…………………………………………………………………………………

3) What are the obvious reasons to use Bootstrap CDN to configure it with
Spring?
…………………………………………………………………………………

…………………………………………………………………………………

……………………………………………............................…………………

…………………………………………………………………………………

8.3 APPLY CUSTOM CSS IN PAGES

CSS or Cascading Style Sheets is a method of adding stylistic instructions for your
website to its back-end code. The HTML (hypertext markup language) is the most
common coding language for a website. CSS is an extension of HTML that outlines
specific stylistic instructions to style websites. It allows you to customize the look of
your website and apply stylistic decisions across its entirety. It also allows you to
separate the style from the structure of a web page. CSS is used to specify the color of

5
Spring MVC with
a heading or what font your content should be written in. CSS can be embedded into
Bootstrap CSS
HTML elements, as shown below.

<p style="color: green;">


This is Green Color Text.
</p>

The above changes the style of the text for a particular <p> tag. This style can be
separated from <p> tag with following instructions.
<head>
<style type="text/css">
p
{
color: green;
}
</style>
</head>
<body>
<p>
This is Green Color Text.
</p>
<p>
This is another paragraph with a green color.
</p>
</body>

The above separated embedded style instructions change all the text within <p> tags
on a page to green. A website generally consists of multiple pages, and the pages
should be uniform and consistent in terms of font-size, font-color, font-family etc. To
keep the style uniform across the pages, a separate CSS file with any name e.g.
custom.css can be created, and custom styles can be added to this file. The required
configuration for custom css, in Spring MVC is like using the Bootstrap downloading
the files locally described into section 8.2.1. The custom css can be included at the top
of each webpage inside the <head> tag using the below instruction.

<link rel="stylesheet" type="text/css" href="css/custom.css">

There are three main components that must be understood clearly to proceed with
adding customized CSS language to the website. The components are selectors,
properties and values.
The selector uses HTML to identify the part of your website that you want to style.
For example, the HTML code for a paragraph is “p” and if you want to use CSS to
change the style of the paragraph, “p” becomes your selector.
Properties and values are then used to apply stylistic instructions to the selectors. If
you want your paragraphs to be written in red text, the property will come first and
will indicate the specific attribute that you’re trying to change (color in this case).
The value is what you want to change that attribute to, which is red in our example.
The section 8.6 describes the CRUD application using Spring MVC and Hibernate.
Custom CSS and configuration code have been described there. Check the impact of
custom CSSon the following screens.

6
Introduction to J2EE
Frameworks

Figure 8.1: CRUD Application Page Using Bootstrap

Figure 8.2: CRUD Application Page Using Bootstrap And Custom CSS

8.4 SETTING UP DATABASE USING


HIBERNATE(Database configuration using
Hibernate)

Spring supports bootstrapping the Hibernate SessionFactory in order to set up the


database using Hibernate. The database setup can be done with a few lines of Java
code or XML configuration. Spring provides two key beans to support the Hibernate
integration, available in the org.springframework.orm.hibernate5 package:
● LocalSessionFactoryBean: creates a Hibernate’s SessionFactory which is
injected into Hibernate-based DAO classes.
● PlatformTransactionManager: provides transaction support code for
a SessionFactory. Programmers can use @Transactional annotation in DAO
methods to avoid writing boiler-plate transaction code explicitly.
The following section describes how these concepts are implemented in a real project
with the required maven dependencies and Java configuration for Hibernate.

7
Spring MVC with
Maven Dependencies
Bootstrap CSS
The necessary dependencies for pom.xml to integrate Hibernate with Spring are as
follows.

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>

<!--Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.5.Final</version>
</dependency>

<!-- MySQL -->


<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>

8.4.1 Java based configuration for Spring and Hibernate Integration

The required beans such as LocalSessionFactoryBean, DataSource,


and PlatformTransactionManager, as well as some Hibernate-specific properties have
been defined into HibernateConfig.
packagecom.ignou.mvcapp;
importjava.util.Properties;
importjavax.sql.DataSource;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.PropertySource;
importorg.springframework.core.env.Environment;
importorg.springframework.jdbc.datasource.DriverManagerDataSource;
importorg.springframework.orm.hibernate5.HibernateTransactionManager;
importorg.springframework.orm.hibernate5.LocalSessionFactoryBean;
importorg.springframework.transaction.PlatformTransactionManager;
importorg.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@PropertySource(value = { "classpath:application.properties" })
publicclassHibernateConfig
{
@Autowired
private Environment environment;

@Bean
publicLocalSessionFactoryBeansessionFactory()
{
LocalSessionFactoryBeansessionFactory = newLocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(newString[] { "com.ignou.mvcapp.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
returnsessionFactory;
}

@Bean
publicDataSourcedataSource()
{
DriverManagerDataSourcedataSource = newDriverManagerDataSource();

8
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); Introduction to J2EE
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
Frameworks
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
returndataSource;
}

private Properties hibernateProperties()


{
Properties properties = newProperties();
properties.put("hibernate.dialect", environment.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getProperty("hibernate.hbm2ddl.auto"));
returnproperties;
}
@Bean
publicPlatformTransactionManagergetTransactionManager()
{
HibernateTransactionManagerhtm = newHibernateTransactionManager();
htm.setSessionFactory(sessionFactory().getObject());
return htm;
}

Property file inside src/main/resources. File name can be any with extension as
properties.

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/schoolDB
jdbc.username = root
jdbc.password = root

hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

☞Check Your Progress 2


1) What is custom CSS and how can these be included into a JSP?
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………............................…………………
…………………………………………………………………………………
2) Write the custom CSS to make all the paragraphs of a page to red color. Write
the sample JSP page for it.
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………............................…………………
…………………………………………………………………………………
3) What are the key beans provided by Spring to integrate with Hibernate?
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………............................…………………
…………………………………………………………………………………
9
Spring MVC with
4) Write the skeleton code for Hibernate Configuration code into Spring.
Bootstrap CSS
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………............................…………………
…………………………………………………………………………………

8.5 CREATE, READ, UPDATE, AND DELETE


(CRUD)

Within computer programming, the acronym CRUD stands for CREATE, READ,
UPDATE and DELETE. The CRUD paradigm is common in constructing web
applications. While constructing the APIs, the model should provide four basic types
of functionality such as Create, Read, Update and Delete the resources. CRUD
operations are also often used with SQL.
It can also describe user-interface conventions that allow viewing, searching and
modifying information through computer-based forms and reports. Most applications
have some form of CRUD functionality. Let's consider that we have a student
database that stores information for students and grades. When programmers provide
interactions with this database (often through stored procedures), the steps of CRUD
are carried out as follows:
● Create: A new student is entered into the database.
● Read: The student's information is displayed to the users.
● Update: Already, existing student’s attributes are being updated with new
values.
● Delete: If the student is not part of the institute, the student can be deleted
from the records.

8.5.1 Mapping CRUD to SQL Statements

The previous section explained the concept of CRUD and defined it based on
different contexts. The following table maps CRUD to database sql operation with
an example.
Function SQL Statement Example
C(reate) Insert Insert into student (name,grade) values(‘Prasoon’,10);
R(ead) Select Select * from student
U(pdate) Update Update student set grade=10 where id=1;
D(elete) Delete Delete from student where id=1;

8.5.2 Mapping CRUD to REST

In REST context, CRUD corresponds to Rest web service POST, GET, PUT and
DELETE respectively. The following table maps CRUD to REST with example.

Function Rest web service Example


C(reate) POST POST http://teststudent.com/students/
R(ead) GET GET http://teststudent.com/students/
U(pdate) PUT PUT http://teststudent.com/students/1
D(elete) DELETE DELETE http://teststudent.com/students/1

10
The following sections explain the CRUD operations in the REST environment for the Introduction to J2EE
system, Student Management System (SMS), to keep the student records with their Frameworks
grade.
• Create
To create a resource in a REST environment, HTTP Post method is used. Post
method creates a new resource of the specified resource type. To create a new
student record for the Student Management System, HTTP POST request and
response are shown below.
o Request: POST http://teststudent.com/students/
o Request Body:
{
"firstName": "Anurag",
"lastName": "Singh",
"grade": 10
}
o Response: Status Code – 201(Created)
{
"id": 1,
"firstName": "Anurag",
"lastName": "Singh",
"grade": 10
}

• Read
To read resources in a REST environment, HTTP GET method is used. Read
operation should not change the resource. The Get method returns the same
response irrespective of number of times of execution. HTTP GET method is
idempotent. A HTTP method is called idempotent if an identical request can be
made once or several times in a row with the same effect while leaving the server
in the same state. To retrieve all student records from the Student Management
System, HTTP GET method request and response is shown below.
o Request: GET http://teststudent.com/students/
o Response: Status Code – 200 (OK)
[
{"id": 1, "firstName": "Anurag", "lastName": "Singh", "grade": 10},
{"id": 1, "firstName": "Dinesh", "lastName": "Chaurasia", "grade": 10}
]
• Update
To update a resource in a REST environment, HTTP PUT or PATCH method is
used. This operation is idempotent. Request and response to update the grade of
student id 1, is shown below.
o Request: PUT http://teststudent.com/students/1
o Request Body:
{
"id": 1,
"firstName": "Anurag",
"lastName": "Singh",
"grade": 8
}
o Response: Status Code – 200 (OK). The response includes a Status
Code of 200 (OK) to signify that the operation was successful, but it
need not return a response body.

11
Spring MVC with
Bootstrap CSS
• Delete
To delete a resource in a REST environment, HTTP DELETE method is used. It
is used to remove a resource from the system. This operation is also idempotent.
Request and response to delete a student with id 1, is shown below.

o Request: DELETE http://teststudent.com/students/1


o Response: Status Code – 204 (No Content). Successful delete
operation returns a response code of 204 (NO CONTENT), with no
response body.

8.6 CRUD EXAMPLES IN SPRING MVC AND


HIBERNATE

The previous section has explained the CRUD operation for the REST environment.
This section is full of code to integrate Spring MVC and Hibernate to implement the
CRUD operation at the database level usingMysql database. Givenbelow is described
the Student Management System application implements which were explained in
previous sections.These include the following:
● BootStrap configuration into Spring MVC using CDN
● Custom CSS
● Spring and Hibernate integration
● CRUD operation implementation with Mysql
The required tools and software to complete the implementations of Student
Management System application are as follows:
● Eclipse IDE
● Maven
● Tomcat 9
● MySql 8
● Java 8 or Higher
Perform the following steps to get a good hands-on in Spring MVC and Hibernate
integration along with Bootstrap and custom CSS.
Step 1: Create a maven project for a web application using the below maven
command and import the project into eclipse. Maven project creation is described in
unit 6 section 6.7.
mvnarchetype:generate -DgroupId=com.ignou.springcrud -DarchetypeGroupId=org.apache.maven.archetypes -
DarchetypeArtifactId=maven-archetype-webapp -DarchetypeVersion=1.4 -DartifactId=springmvc-crud-app -
DinteractiveMode=false

If you get any error like missing folder into eclipse project, go to Java Build Path into
project properties. Select the JRE and Maven Dependencies into Order and export tab.
Project folder structure is shown below.

12
Introduction to J2EE
Frameworks

Figure 8.3: CRUD Application Folder Structure In Eclipse

Add the maven dependencies into pom.xml, which is given in section 8.4
Step2: Create the configuration classes into the package com.ignou.mvcapp
WebMvcConfig.java

packagecom.ignou.mvcapp;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.ignou.mvcapp")
publicclassWebMvcConfigimplementsWebMvcConfigurer
{
@Bean
publicViewResolverviewResolver()
{
InternalResourceViewResolverviewResolver = newInternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB‐INF/views/");
viewResolver.setSuffix(".jsp");
returnviewResolver;
}

@Bean
publicMessageSourcemessageSource()
{
ResourceBundleMessageSourcemessageSource = newResourceBundleMessageSource();
messageSource.setBasename("messages");
returnmessageSource;
}

@Override
publicvoidaddResourceHandlers(ResourceHandlerRegistryregistry)
{
registry.addResourceHandler("/js/**").addResourceLocations("/resources/static/js/");
registry.addResourceHandler("/css/**").addResourceLocations("/resources/static/css/");
registry.addResourceHandler("/images/**").addResourceLocations("/resources/static/images/");
}
}

HibernateConfig.java
The Hibernate integration with Spring MVC configuration code has been given into
section 8.4.1.
13
Spring MVC with
AppInitializer.java
Bootstrap CSS
packagecom.ignou.mvcapp;
publicclassAppInitializerextendsAbstractAnnotationConfigDispatcherServletInitializer
{

@Override
protected Class<?>[] getRootConfigClasses()
{
returnnewClass[] { HibernateConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses()
{
returnnewClass[] { WebMvcConfig.class };
}

@Override
protectedString[] getServletMappings()
{
returnnewString[] { "/" };
}
}

Step 3: Create the controller into package com.ignou.mvcapp.controller


AppController.java
packagecom.ignou.mvcapp.controller;
@Controller
@RequestMapping("/")
publicclassAppController
{

@Autowired
StudentServicestudentService;

@Autowired
MessageSourcemessageSource;

/**
* This Method will list All existing Students
*/
@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
publicModelAndViewwelcome(ModelMapmodel)
{
ModelAndViewmv = newModelAndView();
List<Student>list = studentService.listAllStudents();
model.addAttribute("allstudents", list);
mv.setViewName("allStudents");
returnmv;
}

/**
* This Method will provide way to Add New Student
*/
@RequestMapping(value = { "/new" }, method = RequestMethod.GET)
public String newStudentForm(ModelMapmodel)
{
Student newStudent = newStudent();
model.addAttribute("student", newStudent);
model.addAttribute("edit", false);
return"addStudentForm";
}

@RequestMapping(value = { "/new" }, method = RequestMethod.POST)


publicModelAndViewsaveStudent(@Valid Student student, BindingResultresult, ModelMapmodel)
{
ModelAndViewmv = newModelAndView();
Integer grade = student.getGrade();
if (grade == null)
{
model.addAttribute("student", student);
model.addAttribute("error", "Grade must be Numeric.");
mv.setViewName("addStudentForm");

14
} Introduction to J2EE
else
Frameworks
{
studentService.saveStudent(student);
List<Student>list = studentService.listAllStudents();
model.addAttribute("allstudents", list);
model.addAttribute("success", "Student " + student.getName() + " added successfully.");
mv.setViewName("allStudents");
}
returnmv;
}

/**
* This Method will provide the way to update an existing Student
*
* @param id
* @param model
* @return
*/
@RequestMapping(value = { "/edit‐{id}" }, method = RequestMethod.GET)
public String editStudent(@PathVariable Long id, ModelMapmodel)
{
Student student = studentService.getStudent(id);
model.addAttribute("student", student);
model.addAttribute("edit", true);
return"addStudentForm";
}

/**
* This method will be called on form submission, handling POST request for
* updating Student in database. It also validates the user input
*
* @param Student
* @param result
* @param model
* @param id
* @return
*/
@RequestMapping(value = { "/edit‐{id}" }, method = RequestMethod.POST)
publicModelAndViewupdateStudent(@Valid Student student, BindingResultresult, ModelMapmodel,
@PathVariable Long id)
{
ModelAndViewmv = newModelAndView();
Integer grade = student.getGrade();
if (grade == null)
{
model.addAttribute("student", student);
model.addAttribute("edit", true);
model.addAttribute("error", "Grade must be Numeric.");
mv.setViewName("addStudentForm");
}
else
{
studentService.update(id, student);
List<Student>list = studentService.listAllStudents();
model.addAttribute("allstudents", list);
model.addAttribute("success", "Student " + student.getName() + " updated successfully.");
mv.setViewName("allStudents");
}
returnmv;
}

/**
* This method will Delete a Student by Id
*
* @param id
* @return
*/
@RequestMapping(value = { "/delete‐{id}" }, method = RequestMethod.GET)
publicModelAndViewdeleteStudent(@PathVariable Long id, ModelMapmodel)
{
ModelAndViewmv = newModelAndView();
Student student = studentService.getStudent(id);
studentService.delete(id);
List<Student>list = studentService.listAllStudents();
model.addAttribute("allstudents", list);
model.addAttribute("success", "Student " + student.getName() + " deleted successfully.");

15
Spring MVC with mv.setViewName("allStudents");
Bootstrap CSS returnmv;
}

Step 4: Create the service layer into package com.ignou.mvcapp.service package with
the following classes.

StudentService.java
packagecom.ignou.mvcapp.service;
publicinterfaceStudentService
{
Student getStudent(Long id);
Long saveStudent(Student st);
List<Student>listAllStudents();
voidupdate(Long id, Student st);
voiddelete(Long id);
booleanisStudentUnique(Long id);
}

StudentServiceImpl.java

packagecom.ignou.mvcapp.service;
@Service("studentService")
publicclassStudentServiceImplimplementsStudentService
{

@Autowired
privateStudentDaostudentDao;

@Override
public Student getStudent(Long id)
{
returnstudentDao.getStudent(id);
}

@Override
public Long saveStudent(Student st)
{
returnstudentDao.saveStudent(st);
}

@Override
public List<Student>listAllStudents()
{
returnstudentDao.listAllStudents();
}

@Override
publicvoidupdate(Long id, Student st)
{
Student stEntity = studentDao.getStudent(id);
if (stEntity != null)
{
stEntity.setFirstName(st.getFirstName());
stEntity.setLastName(st.getLastName());
stEntity.setGrade(st.getGrade());
studentDao.updateStudent(stEntity);
}
}

@Override
publicvoiddelete(Long id)
{
Student stEntity = studentDao.getStudent(id);
if (stEntity != null)
{
studentDao.deleteStudent(stEntity);
}
}

16
@Override Introduction to J2EE
publicbooleanisStudentUnique(Long id)
Frameworks
{
Student student = studentDao.getStudent(id);
return (student == null || (id != null& !id.equals(student.getId())));
}

Step 5: Create the model into package com.ignou.mvcapp.model.

packagecom.ignou.mvcapp.model;
@Entity
@Table(name = "students")
publicclass Student
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
privateLongid;

@Column(name = "first_name", nullable = false)


private String firstName;

@Column(name = "last_name", nullable = false)


private String lastName;

@Column(name = "grade", nullable = false)


private Integer grade;

public Long getId()


{
returnid;
}

publicvoidsetId(Long id)
{
this.id = id;
}

public String getFirstName()


{
returnfirstName;
}

publicvoidsetFirstName(String firstName)
{
this.firstName = firstName;
}

public String getLastName()


{
returnlastName;
}

publicvoidsetLastName(String lastName)
{
this.lastName = lastName;
}

public Integer getGrade()


{
returngrade;
}

publicvoidsetGrade(Integer grade)
{
this.grade = grade;
}

public String getName()


{
returnthis.firstName + " " + this.lastName;
}

17
Spring MVC with
Bootstrap CSS
Step 6: Create the DAO layer into the package com.ignou.mvcapp.dao. DAO layer is
responsible for interacting with the database.

StudentDao.java
packagecom.ignou.mvcapp.model;

publicinterfaceStudentDao
{

Student getStudent(Long id);

Long saveStudent(Student st);

List<Student>listAllStudents();

voidupdateStudent(Student st);

voiddeleteStudent(Student st);

StudentDaoImpl.java

packagecom.ignou.mvcapp.model;

@Repository("studentDao")
@Transactional
publicclassStudentDaoImplimplementsStudentDao
{
@Autowired
privateSessionFactorysessionFactory;

@Override
public Student getStudent(Long id)
{
Session session = sessionFactory.getCurrentSession();
Student s =session.get(Student.class, id);
returns;
}

@Override
public Long saveStudent(Student st)
{
Session session = sessionFactory.getCurrentSession();
session.save(st);
returnst.getId();
}

@Override
public List<Student>listAllStudents()
{
Session session = sessionFactory.getCurrentSession();
CriteriaBuildercb = session.getCriteriaBuilder();
CriteriaQuery<Student>cq = cb.createQuery(Student.class);
Root<Student>root = cq.from(Student.class);
cq.select(root);
Query query = session.createQuery(cq);
@SuppressWarnings("unchecked")
List<Student>students = query.getResultList();
returnstudents;
}

@Override
publicvoidupdateStudent(Student st)
{
Session session = sessionFactory.getCurrentSession();
session.update(st);
}

@Override
publicvoiddeleteStudent(Student st)

18
{ Introduction to J2EE
Session session = sessionFactory.getCurrentSession();
Frameworks
session.delete(st);
}

Step 7: Create the hibernate properties into src/main/resources/application.properties


file. Change the username and password for the Mysql installed into your
environment.
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/schoolDB
jdbc.username = root
jdbc.password = root

hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true

hibernate.hbm2ddl.auto = update

Step 8: Create the views (JSP) inside src/main/webapp/WEB-INF/views.


addStudentForm.jsp
<%@pagelanguage="java"contentType="text/html; charset=ISO‐8859‐1"
pageEncoding="ISO‐8859‐1"%>
<%@taglibprefix="form"uri="http://www.springframework.org/tags/form"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>

<html>

<head>
<metahttp‐equiv="Content‐Type"content="text/html; charset=ISO‐8859‐1">
<title>Add New Student Form</title>

<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<scriptsrc="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></
script>
<styletype="text/css">
<
style>.error
{
color: #ff0000;
}
</style>

</head>

<body>
<navclass="navbar navbar‐light bg‐light">
<divclass="container">
<divclass="navbar‐brand mx‐auto text‐success"href="#">
<h1>Student Management System (SMS)</h1>
</div>
</div>
</nav>
<divclass="container">
<divclass="text‐secondary text‐center">
<h2>Student Form</h2>

</div>

<c:iftest="${not empty error}">


<divclass="alert alert‐danger alert‐dismissible fade show"
role="alert">${error}
<buttontype="button"class="btn‐close"data‐bs‐dismiss="alert"
aria‐label="Close"></button>
</div>
</c:if>
<hr/>
<form:formmethod="POST"modelAttribute="student"

19
Spring MVC with cssClass="form‐horizontal">
Bootstrap CSS <form:inputtype="hidden"path="id"id="id"/>

<divclass="form‐group">
<labelfor="firstName">First Name</label>
<form:inputpath="firstName"id="firstName"cssClass="form‐control"/>
</div>

<divclass="form‐group">
<labelfor="lastName">Last Name</label>
<form:inputpath="lastName"id="lastName"cssClass="form‐control"/>
</div>

<divclass="form‐group">
<labelfor="grade">Grade</label>
<form:inputpath="grade"id="grade"cssClass="form‐control"/>
</div>
<hr/>
<c:choose>
<c:whentest="${edit}">
<buttontype="submit"class="btnbtn‐
primary">Update</button>
</c:when>
<c:otherwise>
<buttontype="submit"class="btnbtn‐
primary">Save</button>
</c:otherwise>
</c:choose>

<aclass="btnbtn‐secondary"href="<c:urlvalue='/list'/>">List
of All Students</a>

</form:form>
</div>
</body>

</html>

allStudents.jsp

<%@taglibprefix="form"uri="http://www.springframework.org/tags/form"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metahttp‐equiv="Content‐Type"content="text/html; charset=ISO‐8859‐1">
<title>All Students</title>

<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<scriptsrc="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></
script>
<linkhref="<c:urlvalue="/css/custom.css"/>"rel="stylesheet">

</head>
<body>
<navclass="navbar navbar‐light bg‐light">
<divclass="container">
<divclass="navbar‐brand mx‐auto text‐success"href="#">
<h1>Student Management System (SMS)</h1>
</div>
</div>
</nav>
<divclass="container">
<divclass="text‐secondary text‐center">
<h2>Registered Students</h2>
</div>

<c:iftest="${not empty success}">


<divclass="alert alert‐success alert‐dismissible fade show"
role="alert">${success}
<buttontype="button"class="btn‐close"data‐bs‐
dismiss="alert"
aria‐label="Close"></button>

20
</div> Introduction to J2EE
</c:if>
Frameworks
<hr/>
<tableclass="table">
<theadclass="thead‐dark">
<tr>
<td>Student ID</td>
<td>Student Name</td>
<td>Grade</td>
<td>Modify</td>
<td>Delete</td>
</tr>
<c:forEachitems="${allstudents}"var="student">
<tr>
<td>${student.id}</td><td>${student.firstName}&nbsp;${student.lastName}</td>
<td>${student.grade}</td>
<td><ahref="<c:urlvalue='/edit‐${student.id}'/>"class="btnbtn‐success">Modify</a></td>
<td><ahref="<c:urlvalue='/delete‐${student.id}' />"class="btnbtn‐danger">Delete</a></td>
</tr>
</c:forEach>
</table>
<hr/>
<divclass="form‐group">
<aclass="btnbtn‐primary"href="<c:urlvalue='/new'/>">Add
New Student</a>
</div>
</div>
</body>
</html>

Step 9: Create the custom css inside folder src/main/webapp/resources/static/css.


custom.css

.btn{font‐size:10px }

tr:first‐child{font‐size:20px; color:maroon; font‐weight:bold;}

Step 10: Build the project using maven with goal clean install and then deploy the
generated war file inside the target directory to the external tomcat. You can directly
execute the project into the eclipse by using the Run on Server option. Once the
application is up and running, access the URL http://localhost:8080/spring-mvc-crud-
app/ and perform the CRUD operation provided by the application.

Output:
Home screen renders all existing students by executing read operation into the
database.

Figure 8.4: CRUD Application Home Screen

21
Spring MVC with
Click on the Add New Student button, and a form will be opened to create a new
Bootstrap CSS
student record. Fill the form and click the save button. This operation performs create
operation into the database, and a new student record will be created.

Figure 8.5: CRUD Application Create Form

A student record can be either modified or deleted from the home screen. The click of
modifying button will render the student record in editable mode. Any attribute can be
updated. This operation will perform an update operation into the database. While on
click of the delete button will delete the student record from the database.

Figure 8.6: CRUD Application Delete Screen

☞Check Your Progress 3


1) Define CRUD within computer programming.
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………............................…………………
…………………………………………………………………………………
2) Define the mapping of the CRUD operations with SQL statements with
suitable examples.
…………………………………………………………………………………
…………………………………………………………………………………
22
……………………………………………............................………………… Introduction to J2EE
Frameworks
…………………………………………………………………………………
3) Define the mapping of CRUD in the Rest context.
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………............................…………………
…………………………………………………………………………………

8.7 SUMMARY

The unit has briefly explained the Bootstrap CSS framework. Bootstrap is a feasible
solution to tackle the challenges of making a responsive website as it evolves more
and more. The Bootstrap makes things a lot easier to make the website responsive.
Bootstrap CSS framework configuration into Spring MVC web application has been
described in detail. Custom CSS can be used to override the Bootstrap styles in order
to customize the Bootstrap and match the theme of a website. Hibernate is a very
popular ORM framework to interact with databases, and Spring provides the required
implementation to integrate Hibernate and Spring. The highlights of this unit are as
follows.
● Bootstrap is a free, popular and open-source CSS framework directed at
responsive, mobile-first front-end web development.
● There are two ways to include Bootstrap into JSP or HTML.
o Bootstrap through Content Delivery Network (CDN)
o Including by downloading files
● CSS allows you to customize the style of your website and apply stylistic
decisions across its entirety.
● CSS allows you to separate the style from the structure of a web page.
● There are three main components for adding customized CSS language to the
website. The components are selectors, properties and values.
● Spring supports bootstrapping the Hibernate SessionFactory in order to set up
the database using Hibernate.
● Spring provides two key beans in order to support the hibernate integration.
o LocalSessionFactoryBean
o PlatformTransactionManager
● Within computer programming, the acronym CRUD stands for CREATE,
READ, UPDATE and DELETE.
● In SQL context, CRUD corresponds to Insert, Select, Update and Delete,
respectively.
● In REST context, CRUD corresponds to Rest web service POST, GET, PUT
and DELETE, respectively.

8.7 SOLUTIONS/ ANSWER TO CHECK YOUR


PROGRESS

Check Your Progress 1


1) Bootstrap is a free, popular and open-source CSS framework directed at
responsive, mobile-first front-end web development. Unlike many web
frameworks, it concerns itself with front-end development only. It
contains HTML and CSS based design templates for various interface
23
Spring MVC with
components such as typography, forms, buttons, modals, image carousels,
Bootstrap CSS
navigation etc, as well as optional JavaScript extensions. Bootstrap provides
the ability to create responsive designs faster and easier. The various factors
which make Bootstrap a popular choice for CSS framework are as follows.
(i) All popular web browser support
(ii) Responsive design
(iii) Uniform Solution to build an interface
(iv) Functional built-in components

2) The Bootstrap 5 is the most recent version of the Bootstrap framework. There
are two ways to include Bootstrap into JSP or HTML.
(i) Bootstrap through Content Delivery Network (CDN): Bootstrap
CDN is an efficient and faster way to deliver the content from your
website to the users. Bootstrap CDN speeds up the websites as CDN
servers are intelligent enough to serve the resources based on
proximity.
(ii) Offline or Downloading files locally: Another approach to include
Bootstrap is to directly download the Bootstrap CSS and JS files
locally to the project folder and then include the local copy into
JSP/HTML.

3) For the development environment, offline usage of Bootstrap is suitable. For


the production environment, CDN is better, and the following obvious reasons
support to prefer CDN configuration for Bootstrap-
o CDN servers are intelligent enough to serve the resources based on
proximity
o They are super-fast at serving the content
o The CDN network is spread across the world.
o If you think that your server will challenge the above, then go for it
Check Your Progress 2
1) CSS is an extension of HTML that outlines specific stylistic instructions to
style websites. CSS allows you to customize the look of your website and
apply stylistic decisions across its entirety. CSS allows you to separate the
style from the structure of a web page. CSS is used to specify the color of a
heading or what font your content should be written in. To keep the style
uniformly across the pages, a separate CSS file with any name e.g. custom.css
can be created and custom styles can be added to this file. The custom
CSScan be included at the top of each webpage inside the <head> tag using
the below instruction.
<link rel="stylesheet" type="text/css" href="css/custom.css">

2) The below style instructions change all of the text within <p> tags on a page
to red.

<head>
<style type="text/css">
p
{
color: red;
}
</style>
</head>
<body>
<p>
This is Red Color Text.
24
</p> Introduction to J2EE
<p> Frameworks
This is another paragraph with red color.
</p>
</body>
3) Spring supports bootstrapping the Hibernate SessionFactory in order to set up
the database using Hibernate. The database setup can be done with a few lines
of Java code or XML configuration. Spring provides two key beans, in order
to support the hibernate integration, available in
the org.springframework.orm.hibernate5 package:
o LocalSessionFactoryBean: creates a
Hibernate’s SessionFactory ,which is injected into Hibernate-based
DAO classes.
o PlatformTransactionManager: provides transaction support code
for a SessionFactory. Programmers can
use @Transactional annotation in DAO methods to avoid writing
boiler-plate transaction code explicitly.

4) The Java configuration to integrate Hibernate with Spring is as follows.

packagecom.ignou.mvcapp;

@Configuration
@EnableTransactionManagement
@PropertySource(value = { "classpath:application.properties"
})
publicclassHibernateConfig
{

@Autowired
private Environment environment;

@Bean
publicLocalSessionFactoryBeansessionFactory()
{
LocalSessionFactoryBeansessionFactory =
newLocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(newString[] {
"com.ignou.mvcapp.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
returnsessionFactory;
}

@Bean
publicDataSourcedataSource()
{
DriverManagerDataSourcedataSource =
newDriverManagerDataSource();
// set datasource properties
returndataSource;
}

private Properties hibernateProperties()


{
Properties properties = newProperties();
//set Hibernate properties
returnproperties;
}

25
Spring MVC with @Bean
Bootstrap CSS publicPlatformTransactionManagergetTransactionManager()
{
HibernateTransactionManagerhtm =
newHibernateTransactionManager();
htm.setSessionFactory(sessionFactory().getObject());
return htm;
}
}

Check Your Progress 3


1) Within computer programming, the acronym CRUD stands for CREATE,
READ, UPDATE and DELETE. The CRUD paradigm is common in
constructing web applications. While constructing the APIs, the model should
provide four basic types of functionality such as Create, Read, Update and
Delete the resources. CRUD operations are also often used with SQL.
It can also describe user-interface conventions that allow viewing, searching
and modifying information through computer-based forms and reports. Most
applications have some form of CRUD functionality. When programmers
provide interactions with this database (often through stored procedures), the
steps of CRUD, for a Student Management System, are carried out as follows:
o Create: A new student is entered into the database.
o Read: The student's information is displayed to the users.
o Update: Already existing student’s attributes are being updated with
new values.
o Delete: If the student is not part of the institute, the student can be
deleted from the records.
2) CRUD to database SQL operation mapping with examples are as follows.
Function SQL Statement Example
C(reate) Insert Insert into student (name,grade) values(‘Prasoon’,10);
R(ead) Select Select * from student
U(pdate) Update Update student set grade=10 where id=1;
D(elete) Delete Delete from student where id=1;

3) In REST context, CRUD corresponds to Rest web service POST, GET, PUT
and DELETE respectively. The following table maps CRUD to REST with an
example.
Function Rest web service Example
C(reate) POST POST http://teststudent.com/students/
R(ead) GET GET http://teststudent.com/students/
U(pdate) PUT PUT http://teststudent.com/students/1
D(elete) DELETE DELETE http://teststudent.com/students/1

8.9 REFERENCES/FURTHER READING

• Craig Walls, “Spring Boot in action” Manning Publications, 2016.


(https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)

26
• Christian Bauer, Gavin King, and Gary Gregory, “Java Persistence with Introduction to J2EE
Frameworks
Hibernate”,Manning Publications, 2015.
• Ethan Marcotte, “Responsive Web Design”, Jeffrey Zeldman Publication,
2011.(http://nadin.miem.edu.ru/images_2015/responsive-web-design-2nd-
edition.pdf)
• Tomcy John, “Hands-On Spring Security 5 for Reactive Applications”,Packt
Publishing,2018.
• https://www.creative-tim.com/blog/web-design/add-bootstrap-html-guide/
• https://getbootstrap.com/docs/5.0/getting-started/introduction/
• https://getbootstrap.com/docs/5.0/examples/
• https://wordpress.com/go/web-design/what-is-css/
• https://getbootstrap.com/docs/5.0/customize/overview/
• https://www.baeldung.com/hibernate-5-spring
• https://stackoverflow.com/questions/22693452/bootstrap-with-spring-
mvc/22765275
• https://www.quora.com/Is-it-better-to-use-Bootstrap-offline-or-just-include-a-
link-to-the-CDN

27
UNIT 9 INTRODUCTION TO SPRING BOOT

Structure Page No.

9.0 Introduction
9.1Objectives
9.2 Spring Boot: An Overview
9.2.1 Spring Boot Working and Annotations
9.2.2 Spring Boot Starter
9.2.3 Spring Boot Project Structure
9.2.4 Spring Boot Runners
9.2.5 Spring Boot Web Application Using Thymeleaf
9.3 Spring Boot DevTools and Spring Boot Actuator
9.3.1 Spring Boot DevTools
9.3.2 Spring Boot Actuator
9.3.3 Spring Boot Actuator Example
9.4 Spring Boot- Application Properties
9.4.1 Command Line Properties
9.4.2 Properties File
9.4.3 YAML File
9.4.4 Externalized Properties
9.4.5 @Value annotation
9.4.6 Active Profile
9.4.7 Spring Active Profile in application.yml
9.5 Running Spring Boot Apps from command line
9.5.1 Running the Code with Maven in Exploded Form
9.5.2 Running the Code as a Stand-Alone Packaged Application
9.5.3 Application Packaging as WAR and Deployment on Tomcat
9.6 Summary
9.7 Solutions/Answer to Check Your Progress
9.8 References/Further Reading

9.0 INTRODUCTION

Fast, secured and cost-effective development of software plays a vital role in the
growth of an organization. Java has been the popular choice for many enterprises and
programmers since the mid 90’s for designing and developing software. Hence, lots of
frameworks are being developed to ease the software development using Java.

In order to make the software development easy, fast and effective several
frameworks have been introduced such as Struts, Spring and ORM tools such as
Toplink, Hibernate, Eclipse Link, Ibatis.

Spring based enterprise application requires many configurations and complicated


dependency management which make the set up tedious and error-prone. Each time
spring-based enterprise application requires repetition of the same configuration
steps:

• Based on application type, import the required dependencies such as spring


mvc, spring jpa, spring jdbc, spring rest etc.

1
Introduction To Spring • Import the specified Spring version compatible third-party libraries such as
Boot hibernate, Jackson etc.

• Configure web layer beans such as view resolver, resource manager etc.

• Configure DAO layers such as data source, transaction management, entity


manager etc.

• Import web container libraries in the case of web applications.

The spring team considered simplifying the routine configuration and facilitating the
developers with some utility that automates the configuration process and speeds up
the spring-based application's build and deployment process. Spring has evolved a lot
in recent years and introduced many new modules such as Spring Boot, Spring
Security, Spring Cloud, Spring Data etc.

Spring Boot is a utility project which enables an organization to develop production-


ready spring-based applications and services with less effort, reduced cost and
minimal configuration. Spring Boot facilitates the developers to create a Spring based
web application with minimum lines of code since it provides auto-configuration out-
of-the-box. In this unit Tomcat and Tomcat are used interchangeably.

9.1 OBJECTIVES

After going through this unit, you will be able to:


• describeSpring Boot and its features,
• describeSpring Boot starters and runners,
• use Spring Boot annotations,
• set application properties and profile-based application properties,
• use DevTools and Actuator,
• perform command line Spring Boot application execution, and
• perform step by step development and execution of Spring Boot web app.

9.2 SPRING BOOT:AN OVERVIEW

Spring Boot is an extension of the Spring framework that takes one step ahead and
simplifies the configuration in order to fasten the development and execution of the
spring application. It eliminates the boilerplate configuration required for a spring
application. It is a module that enriches the Spring framework with Rapid Application
Development (RAD) feature. It provides an easy way to create a stand-alone and
production ready spring application with minimum configurations. Spring Boot
provides comprehensive infrastructure support for the development and monitoring of
the enterprise-ready applications based on micro services. Spring Boot is a
combination of Spring framework with auto-configuration and embedded Servers.

Spring Boot provides a vast number of features and benefits. A few of them are as
follows:

1) Everything is auto-configured in Spring Boot.

2
2) Spring Boot starter eases the dependency management and application Spring Boot and Hibernate
(ORM)
configuration
3) It simplifies the application deployment by using an embedded server
4) Production ready features to monitor and manage applications, such as health
checks, metrics gathering etc.
5) Reduces the application development time and run the application
independently
6) Very easy to understand and develop Spring application
7) Increases productivity and reduces the cost

9.2.1 Spring Boot Working and Annotations

A class with the main method and annotated with @SpringBootApplication is the
entry point of the Spring Boot application. Spring Boot auto-configures all required
configurations. It performs auto-configuration by scanning the classes in class-path
annotated with @Component or @Configuration. @SpringBootApplication
annotation comprising the following three annotations with their default values-

• @EnableAutoConfiguration
• @ComponentScan
• @Configuration

@EnableAutoConfiguration
As the name implies, it enables auto-configuration. It means Spring Boot looks for
auto-configuration beans on its class-path and automatically applies them. For
example, if H2 dependency is added and you have not manually configured any
database connection beans, then Spring will auto-configure H2 as an in-memory
database.
The @EnableAutoConfiguration annotation should be applied in the root package so
that every sub-packages and class can be examined.
@ComponentScan
The @ComponentScan annotation enables Spring to scan for things like
configurations, controllers, services, and other components we define. By default, the
scanning starts from the package of the class declaring @ComponentScan. The
component scanning can be started from specified packages by defining
basePackageClasses, basePackages attributes into @ComponentScan. The
@ComponentScan annotation is used with @Configuration.

@Configuration
The @Configuration annotation is used for annotation-based configuration into the
Spring application. A class annotated with @Configuration indicates that the class
declares one or more @Bean methods and can be processed by Spring container to
generate bean definitions and service requests for those beans at runtime.

Other available annotations in the Spring Boot are described below:

@ConditionalOnClass and @ConditionalOnMissingClass


Spring @ConditionalOnClass and @ConditionalOnMissingClass annotations
let @Configuration classes be included based on the presence or absence of specific

3
Introduction To Spring classes. Hence, @ConditionalOnClass loads a bean only if a certain class is on the
Boot classpath and @ConditionalOnMissingClass loads a bean only if a certain class is not
on the classpath.

@CoditionalOnBean and @ConditionalOnMissingBean


These annotations are used to define conditions based on the presence or absence of
a specific bean.

@ConditionalOnProperty
The annotation is used to conditionally create a Spring bean depending on the
configuration of a property.

@Bean

@ConditionalOnProperty(name = "usepostgres", havingValue = "local")

DataSourcedataSource()

// ...

The DataSource bean will be created only if property usepostgres exists and it has
value as local.

@ConditionalOnResource
The annotation is used to conditionally create a Spring bean based on the presence or
absence of resources. The SpringConfig class beans will be created if the resource
log4j.properties file is present.

@Configuration

@ConditionalOnResource(resources = { "log4j.properties" })

class SpringConfig

{
@Bean
public Log4j log4j()
{
return new Log4j();
}
}

9.2.2 Spring Boot Starter

Before describing Spring Boot Starter, the following section explains all the required
things to develop a web application.

4
Development of a web application using Spring MVC will require identifying all the Spring Boot and Hibernate
required dependencies, compatible versions and how to connect them together. (ORM)
Followings are some of the dependencies which are used in Spring MVC web
application. For all the dependencies we need to choose the compatible version
dependencies.

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>4.2.2.RELEASE</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.5.3</version>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-validator</artifactId>

<version>5.0.2.Final</version>

</dependency>

<dependency>

<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>1.2.17</version>

</dependency>

5
Introduction To Spring Dependency management is a very important and complex process in any project.
Boot Manual dependency management is error-prone, non-ideal and non-suggestible. To
focus more on aspects apart from dependency management in web application
development will require some solution that addresses compatible dependency
management problems.

Spring Boot starters are the dependency descriptor that addresses the problem of
compatible versions of dependency management. Spring Boot Starter POMs are a set
of convenient dependency descriptors that you can include in your application. You
get a one-stop-shop for all the Spring and related technology that you need from
Spring Boot starters. Spring Boot provides a number of starters that make
development easier and rapid. Spring Boot starters follow a similar naming pattern as
spring-boot-starter-*, where * denotes a particular type of application. For instance,
developing a rest service that requires libraries like Spring MVC, Tomcat, Log and
Jackson, a single Spring Boot starter named spring-boot-starter-web needs to be
included. Spring Boot provides many numbers starter, and a few of them are listed
below-

spring-boot-starter-web It is used for building web applications, including RESTful


applications using Spring MVC. It uses Tomcat as the default
embedded container.

spring-boot-starter-jdbc It is used for JDBC with the Tomcat JDBC connection pool.

spring-boot-starter- It is used for Java Bean Validation with Hibernate Validator.


validation

spring-boot-starter-security It is used for Spring Security.

spring-boot-starter-data-jpa It is used for Spring Data JPA with Hibernate.

spring-boot-starter It is used as a core starter, including auto-configuration support,


logging etc.

spring-boot-starter-test It is used to test Spring Boot applications with libraries,


including JUnit, Hamcrest, and Mockito.

spring-boot-starter- It is used to build MVC web applications using Thymeleaf


thymeleaf views.

9.2.3 Spring Boot Project Structure

Spring Boot provides a high degree of flexibility in code layout. However, there are
certain best practices that will help to organize the code for better readability.

In Spring Boot, default package declaration is not recommended since it can cause
issues such as malfunctioning of auto-configuration or Component Scan. Spring Boot
annotationslike:

@ComponentScan,

@EntityScan,

6
@CoonfigurationP
PropertiesScan, and Spring Booot and Hibernatte
(ORM)
@SppringBootAppplication

use packages to define scannning location


ns. Thus, thee default pacckage shouldd be
avoid
ded.

The @SpringBoot
@ tApplication annotation
a triiggers compoonent scanninng for the currrent
packkage and its suub-packages. Therefore, thhe main class of the projectt should residde in
the base
b package tot use the impplicit componnents scan of Spring Boot.

Figurre 9.1: SpringB


Boot Project Structure
S Forr Default Scan
nning

In thhe above codee structure, coontroller, mod del, repositoryy and servicee are sub-packkage
of base
b packagge com.igno ou.springbooot.learning. All the components
c and
confifigurations aree eligible for implicit
i scann
ning with maiin class as below:

pack
kage com.ignou.springb
boot.learning;

impo k.boot.SpringApplicati
ortorg.springframework ion;

impo
ortorg.springframework
k.boot.auto
oconfigure.S
SpringBootA
Application;

@Spr
ringBootApplication

publ
lic class SpringbootLe
earningApplication

{
public static
s void main(Strin
ng[] args)
{

pplication.run(Springb
SpringAp bootLearnin
ngApplicatio
on.class,
args
s);
}
}

7
Introduction To Spring Spring Boot has a high degree of flexibility. Thus, it allows us to relocate the
Boot scanning elsewhere by specifying the base package manually.

Figure9.2: SpringBoot Project Structure For Custom Scan Package

package com.ignou.springboot.learning;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages= {"com.ignou.springboot"})

public class SpringbootLearningApplication


{
public static void main(String[] args)
{
SpringApplication.run(SpringbootLearningApplication.class, args);
}
}

In above package structure, component and configuration packages are not sub-
package of main class. Thus, scanning location has been explicitly defined as
@SpringBootApplication(scanBasePackages= {"com.ignou.springboot"})

9.2.4 Spring Boot Runners

Spring Boot provides two runner interfaces named as ApplicationRunner and


CommandLineRunner. These interfaces enable you to execute a piece of code just
after the Spring Boot application is started.

Both interfaces are Functional Interface. If any piece of code needs to be executed
when Spring Boot Application starts, we can implement either of these functional
interfaces and override the single methodrun.

8
Application Runner Spring Boot and Hibernate
(ORM)
Spring bean which implements the ApplicationRunnerinterfaces in a Spring Boot
Application, the bean gets executed when application is started. ApplicationRunner
example is as following-

packagecom.ignou.springboot.learning;

importorg.springframework.boot.ApplicationArguments;

importorg.springframework.boot.ApplicationRunner;

importorg.springframework.stereotype.Component;

@Component

publicclassApplicationRunnerImplimplementsApplicationRunner
{
@Override
publicvoid run(ApplicationArgumentsargs) throws Exception
{
System.out.println("Application Runner Executed.");
}
}

The execution result of Spring Boot application having the above component is shown
below, and you can observe that the bean implementing ApplicationRunner is
executed just after the application starts.

Figure 9.3: Execution Result of ApplicationRunner

Command Line Runner

The Command LineRunner interface is also meant for the same purpose as
ApplicationRunner interface. Spring bean which implements the
CommandLineRunner interface in a Spring Boot Application, the bean gets executed
when the application is started. CommandLineRunner example is as following-

packagecom.ignou.springboot.learning;

importorg.springframework.boot.CommandLineRunner;

importorg.springframework.stereotype.Component;

@Component

9
Introduction To Spring publicclassCommandLineRunnerImplimplementsCommandLineRunner
Boot
{
@Override
publicvoid run(String... args) throws Exception
{
System.out.println("Command Line Runner executed");
}
}

Execution result of Spring Boot application with the above component is shown
below and you can observe that the bean implementing ApplicationRunner is executed
just after application starts.

Figure 9.4: Execution Result Of CommandLineRunner

9.2.5 Spring Boot Web Application Using Thymeleaf

The previous sections have described the basic concepts of Spring Boot. This section
explains the process of creating a “Hello World” website using the Spring Boot
concepts. Required tools and software are as follows:
• Eclipse
• Maven
• Spring Boot
• JDK 8 or above
Step 1: Create a Spring Boot Project using Spring Initializr. Visit at
https://start.spring.io/ and generate the Spring Boot project with added dependency.
For the project,Spring Web and Thymeleaf dependency will be used.

Figure 9.5: SpringBoot Project Initialization Using Spring Initializr

10
Step 2: Extract the generated project and Import this into eclipse as maven project. Spring Boot and Hibernate
Project structure is shown below. (ORM)

Figure 9.6: SpringBoot Project Structure

The controller is a sub-package of the base package. Thus, implicit scanning of


components and configuration will be used.
Step 3: Add a HomeController into the controller package. HomeController has two
endpoints:
• “/”
• “/greeting?name=Jack”

packagecom.example.demo.controller;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.Model;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
@Controller

publicclassHomeController
{
@RequestMapping(value="/")
public String home()
{
return"home";
}
@GetMapping("/greeting")
public String greeting(@RequestParam(name="name",
required=false,defaultValue="World") String name, Model model)
{
model.addAttribute("name", name);
return"greeting";
11
Introduction To Spring }
Boot }

Step 4: Thymeleaf is used as a view technology in this example. For both the end
point, add the corresponding HTML template file into src/main/resources/templates

home.html
<!DOCTYPEhtml>

<html>

<head>

<metacharset="ISO‐8859‐1"/>

<title>Spring Boot Web Application</title>

</head>

<body>

<h1>Welcome to Thymeleaf Spring Boot web application</h1>

</body>

</html>

greeting.html
<!DOCTYPEHTML>

<htmlxmlns:th="http://www.thymeleaf.org">

<head>

<title>Getting Started: Serving Web Content</title>

<metahttp‐equiv="Content‐Type"content="text/html; charset=UTF‐8"/>

</head>

<body>

<pth:text="'Hello, ' + ${name} + '!'"/>

</body>

</html>

Step 5: Now the project is ready to run. Run DemoApplication.java file as Java
Application in eclipse as shown below.

12
Access the endpoints, as mentioned in step 3, into the browser. You will get the Spring Boot and Hibernate
(ORM)

Figure 9.6: SpringBoot Project Execution Into Eclipse

following output in the browser.

13
Introduction To Spring
Boot

Figure9.7: Execution Result 1

Figure 8.9: Execution Result 2

Figure 9.9: Execution Result 3

14
Check Your Progress 1 Spring Boot and Hibernate
(ORM)

1) What is Spring Boot?Explain its need.


…………………………………………………………………………………
…………………………………………………………………………………
………………………………………………....................................…………
…………………………………………………………………………………
……………………………….
2) Describe Spring Boot working with @SpringBootApplication.
…………………………………………………………………………………
…………………………………………………………………………………
………………………………………………....................................…………
…………………………………………………………………………………
……………………………….
3) What are the Spring Boot starters, and what are the available starters?
…………………………………………………………………………………
…………………………………………………………………………………
………………………………………………....................................…………
…………………………………………………………………………………
……………………………….
4) What do you understand by auto-configuration in Spring Boot and how to
disable the auto-configuration?
…………………………………………………………………………………
…………………………………………………………………………………
………………………………………………....................................…………
…………………………………………………………………………………
……………………………….
5) What is the need of a Spring Boot runner?
…………………………………………………………………………………
…………………………………………………………………………………
………………………………………………....................................…………
…………………………………………………………………………………
……………………………….

9.3 SPRING BOOT DEVTOOLS AND SPRING BOOT


ACTUATOR

15
Introduction To Spring Spring Boot DevTools and Spring Boot Actuators are very important modules that
Boot enhance the development experience and increase productivity. These modules reduce
the developers’ effort and thus reducethe cost of the project.

9.3.1 Spring Boot DevTools

Spring Boot DevTools was released with Spring Boot 1.3. DevTools stands for
developer tool. The aim of DevTools module is to enhance the application
development experience by reducing the development time of the Spring Boot
Application. During a web application development, a developer changes the code
many times and then restarts the application to verify the changed code.
DevToolsreduces the developer effort. It detects the code changes and restarts the
application automatically. DevTools can be integrated into a Spring Boot application
just by adding the following dependency into pom.xml.

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring‐boot‐devtools</artifactId>

<scope>runtime</scope>

<optional>true</optional>

</dependency>

Spring Boot DevTools provides the following important features –

• Automatic Restart
• Live Reload
• Property defaults

Automatic Restart: Auto-restart refers to the reloading of Java classes and configures
it at the server-side. While developing an application, a developer changes the code
frequently and to verify these changes, the steps build, deploy and restart of the server
is required. Spring Boot DevTools automates the build and deploys process, which
increases productivity. Files change in the class-path triggers Spring Boot DevTools
to restart the application. This auto-restart process reduces the time significantly to
verify the changes. Spring Boot uses two types of ClassLoaders:
• Base ClassLoader: This ClassLoader loads the classes which do not change.
E.g. Third-party jars
• Restart ClassLoader: This ClassLoader loads the classes which we are
actively developing
Live Reload: Live Reload or auto-refresh is also a very important feature provided by
Spring Boot DevTools. Spring Boot DevTools module also comes with an embedded
LiveReload server that can be used to trigger a browser refresh whenever a resource is
changed. For example, when a developer makes the changes into templates or other
resources, he/she has to refresh the browser to verify the changes. With the Live
Reload/Auto Refresh feature, developers do not need to press F5 to refresh the
browser. Thus, it enhances the development experience and increases productivity.
Enabling Live Reload in Spring Boot Application is pretty easy. Following steps are
required to enable it.
16
1) Add the dependency spring-boot-devtools to your project’s build file Spring Boot and Hibernate
(ORM)
(pom.xml).
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>

Once the application is started, one can verify the LiveReload server into log.

Figure 9.10: Live Reload

2) Install LiveReload extension for the browser. Go


to http://livereload.com/extensions/ and click on the link that relates to your

browser.
Figure 9.11: Live Reload Extension

You can enable and disable the live reload by clicking on LiveReload as shown in
screenshot.

17
Introduction To Spring
Boot

Figure 9.12: Enable/Disable Live Relaod

Update of home.html triggers the browser to auto-refresh. There is no need to press


F5. Output is shown below:

Figure9.13: Auto Refreshed Screen


LiveReload works on the following path:
• /static
• /public
• /resources
• /templates
• /META-INF/maven
• /META-INF/resources
The following properties can be used to disable and enable the LiveReload
feature.

# Disable LiveReload for following path

spring.devtools.restart.exclude=public/**, static/**, templates/**

# Enable LiveReload for additional path

spring.devtools.restart.additional-paths=/path-to-folder

18
Property Defaults: Spring Boot does a lot of auto configuration. It also includes Spring Boot and Hibernate
caching for performance improvement. Template technology Thymeleaf contains the (ORM)
property spring.thymeleaf.cache. DevTools disables the caching and allows us to
update pages without restarting the application. During the development, caching for
Thymeleaf, Freemarker, Groovy Templates are automatically disabled by DevTools.

9.3.2 Spring Boot Actuator

Spring Boot Actuator is a sub-project of the Spring Boot framework. The Actuator
provides production-ready features such as application monitoring, Network traffic,
State of database and many more. Without any implementation, Actuator provides
production-grade tools. In Spring Boot application, Actuator is primarily used to
expose operational information about the running application such as info, health,
dump, metrics, env etc. It provides HTTP and JMX endpoints to manage and monitor
the Spring Boot application. There are three main features of Spring Boot Actuator-
• Endpoints
• Metrics
• Audit
Endpoints: The actuator endpoints enable us to monitor and interact with the
application. In Spring Boot 2.x, most of the endpoints of the Actuator are disabled. By
default, only two endpoints /health and /info are available. Other required endpoints
can be enabled by adding management.endpoints.web.exposure.include property into
application.properties. By default, all Actuator endpoints are now placed under
the /actuator path. Some of the important endpoints are listed below –
• /health provides the health status of the application
• /info provides general information about the application. It might be build
information or the latest commit information.
• /metrics provides metrics of application. Returned metrics include generic
metrics as well as a custom metric.
• /env provides the current environment properties.
Metrics: Spring Boot integrates the micrometer to provide dimensional metrics. The
micrometer is the instrumentation library that empowers the delivery of application
metrics from Spring. Metrics of the application can be accessed by /metrics endpoint.
Audit: Spring Boot provides a flexible audit framework that publishes events to
an AuditEventRepository. It automatically publishes the authentication events if
spring-security is in execution.

9.3.3 Spring Boot Actuator Example

This section explains the required steps to integrate the Spring Boot Actuator into the
previously developed website into section 9.2.5. Add the spring-boot-starter-actuator
dependency into pom.xml –
<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring‐boot‐starter‐actuator</artifactId>

</dependency>

Start the web application and access the http://localhost:8080/actuator endpoint. By


default, only two end points are enabled. Result is as below:

19
Introduction To Spring
Boot

Figure 9.14: Default Enabled Actuator Endpoints

Add the following property in application.properties file and access the


http://localhost:8080/actuator to get all available endpoints.

management.endpoints.web.exposure.include= *

Figure 9.15: All Endpoints of Actuator

Output after adding above property is shown below:


Output for endpoint http://localhost:8080/actuator/metrics is shown below -

Figure 9.16: Autuator Metrics Result


20
Spring Boot and Hibernate
(ORM)
The above output shows all available metrics. Metric
http.server.requestsshow the following output :

Figure 9.17: Metric http.server.requests

Output for /health endpoint is shown below-

Figure9.18: Health Status of Server

Check Your Progress 2

1) What is the need of Spring Boot DevTools?


…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
……………………………….
2) Explain Spring Boot Actuator and its advantages.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………

21
Introduction To Spring …………………………………………………………………………………
Boot
……………………………….
3) Write a simple "Hello World" Spring Boot rest application.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
……………………………….

9.4 SPRING BOOT- APPLICATION PROPERTIES

Application Properties enable us to work in different environments such as Prod, Dev,


Test. This section explains how to set up and use properties in Spring Boot via Java
configuration and @PropertySource. Spring Boot application properties can be set
into properties files, YAML files, command-line arguments and environment
variables.

9.4.1 Command Line Properties

Spring Boot Environment properties can be passed via command-line properties.


Command-line properties take precedence over the other property sources. The
following screenshot shows the command line property –server.port=9090 to change
the port number

Note: Double hyphen (--) can be used as a delimiter to pass multiple


command-line properties.

9.4.2 Properties File

By default, Spring Boot can access configurations available in an


application.properties file kept under the classpath. The application.properties file
should be kept in src/main/resources directory. Thesample application.properties file
is shown below-

server.port = 9090

spring.application.name = demoservice

Property server.port changes the port number on which the web application runs.

22
9.4.3 YAML File Spring Boot and Hibernate
(ORM)
Spring Boot also supports YAML based properties configuration. Properties file
application.yml can be used instead of application.properties. YAML is a convenient
format for specifying hierarchical configuration data. The application.yml file also
should be kept in src/main/resources directory. Sample application.yml file is shown
below-

server:
port: 9090
spring:
application:
name: demoservice

9.4.4 Externalized Properties

Spring Boot supports keeping properties file at any location. We can externalize the
properties file so that if any property is changed, a new build is not required. Just
application restart will take effect on the changed property. While executing the
application jar file, the following command-line argument is used to specify the
location of the property file.

-Dspring.config.location = C:\application.properties

9.4.5 @Value annotation

Properties, defined for environment or application, can be fetched in java code using
@Value annotation. Syntax to use @Value annotation is shown below –

@Value(“${property_key}”)

If a property spring.application.name is defined into application.properties or


application.yml, it can be accessed into java code using as-

@Value("${spring.application.name}")

String appName;

While running, if the property is not found, an exception is thrown. The default value
can be set while fetching the value using @Value annotation as follows-

@Value(“${property_key:default_value}”)

9.4.6 Active Profile

An application is executed in multiple environments such as test, development,


production etc. To modify application.properties file based on the environment is not
23
Introduction To Spring an ideal approach. There must be multiple properties files corresponding to each
Boot environment. At run time, Spring Boot must be able to select the desired environment
properties file.
Spring Boot supports different properties based on the Spring active profile. Consider
that there are separate properties file for each environment as shown below:
application.properties
server.port = 9090

spring.application.name = demoservice

application-dev.properties
server.port = 9090

spring.application.name = demoservice

application-prod.properties
server.port = 9090

spring.application.name = demoservice

By default, Spring Boot uses application.properties file. But Spring Boot allows to set
the active profile and corresponding properties file that is used by Spring Boot. The
following command shows how to set an active profile while starting an application
from the command- line.

While running an application from eclipse IDE, the active profile can be set as shown
in the screenshot.

24
Spring Boot and Hibernate
(ORM)

Figure 9.19: Set Active Profile in Eclipse Project 1

Figure9.20: Set Active Profile in Eclipse Project 2

25
Introduction To Spring Active profile can be checked in the log while starting the application.
Boot

Figure 9.21: SpringBoot Application Execution Log

9.4.7 Spring Active Profile in application.yml

YAML file allows active profile parameters to be kept into a single application.yml
file. Unlike multiple application.properties files, there is a single application.yml.
Delimiter (---) is used to separate each profile in an application.yml file. Sample
application.yml file is shown with active profile dev and prod.

server:
port: 9090
spring:
application:
name: demoservice

‐‐‐
server:
port: 8080
spring:
config:
activate:
on‐profile: dev
application:
name: demoservice
‐‐‐
server:
port: 8080
spring:
config:
activate:
on‐profile: prod
application:
name: demoservice

26
Spring Boot and Hibernate
9.5 RUNNING SPRING BOOT APPS FROM (ORM)

COMMAND LINE

This section describes a couple of ways to run a Spring Boot app from a command
line in a terminal window. Later it explains how to package the app as war and which
can be deployed on any application server such as Apache Tomcat, WebLogic, JBoss,
etc.
The Spring Boot Maven plugin is the recommended tool to build, test and package
the Spring Boot Application code. The plugin is configured by adding it into
pom.xml.

<build>

<plugins>

...

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

...

</plugins>

</build>

The plugin comes with lots of convenient features such as –


• It can package all our dependencies (including an embedded application
server if needed) in a single, runnable fat jar/war
• It resolves the correct dependency versions

9.5.1 Running the Code with Maven in Exploded Form

The Spring Boot Maven plugin has the ability to automatically deploy the web
application in an embedded application server. If spring-boot-starter-web
dependency has been included, plugin knows that Tomcat is required to run the code.
On execution of mvnspring-boot:run command in the project root folder, the plugin
reads the pom configuration. If a web application container is required, the plugin
triggers the download of Apache Tomcat and initializes the startup of Tomcat. The
command to run the Spring Boot application using maven plugin is as following –

mvnspring-boot:run

27
Introduction To Spring Execution of the above command starts the Spring Boot application and the produced
Boot log is shown.

9.5.2 Running the Code as a Stand-Alone Packaged Application

Once the development phase is over, the application is moved to production, and we
need to package the application. Just include the Spring Boot Maven plugin and
execute the following command in order to package the application.

mvn clean package spring-boot:repackage

The execution of the above command packages the application and produces the jar

Figure 9.22: SpringBoot Application Execution From Command Line

file into the target folder. The generated jar file can be executed using the following
command.

java –jar <File Name>

As you can notice, that –cp option and main class has been skipped into java –jar
command because the Spring Boot Maven plugin takes care of all these configurations
into the manifest file.

9.5.3 Application Packaging as WAR and Deployment on Tomcat

By default, Spring Boot builds a standalone Java application that can run as a desktop
application. The standalone Java application is not suitable for the environment where
installation of a new service or manual execution of an application is not allowed,
such as Production environment.
The Servlet containers require the applications to meet some contracts to be deployed.
For Tomcat the contract is the Servlet API 3.0. This section considers the example
used in section 9.2.5 and explains how the application can be packaged as WAR and
deployed into Tomcat.
First, change the packaging type as war into pom.xml with the following content.

<packaging>war</packaging>

Initialize the Servlet context required by Tomcat by extending

the SpringBootServletInitializer class:

28
@SpringBootApplication Spring Boot and Hibernate
(ORM)
publicclassDemoApplicationextendsSpringBootServletInitializer

{
publicstaticvoid main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
}
}

By default, generated war file name includes version number also. The Name of the
generated war can be modified with following –

<build>

<finalName>${artifactId}</finalName>

...

</build>

Execute the following command in order to build the Tomcat deployable war if
artifact id is demo, war file generated at target/demo.war. Follow the below steps in
order to deploy the generated war file on Tomcat.

• Download Apache Tomcat and unpack it into the tomcat folder.


• Copy the generated war file from target/demo.war to
tomcat/webapps/demo.war
• Go to bin dir of Tomcat and start the tomcat using catalina.bat start (on
windows) or catalina.sh start (on Unix)
• Access the application using http://localhost:8080/demo

Check Your Progress 3

1) Mention the possible sources of external configuration.


…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………....................................……………
…………………………………………………………………………………
……………………………….
2) Can we change the port of the embedded Tomcat server in Spring boot?
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………....................................……………
…………………………………………………………………………………
……………………………….
3) Explain the concept of profile in Spring Boot and say how it is useful,

29
Introduction To Spring …………………………………………………………………………………
Boot
…………………………………………………………………………………
……………………………………………....................................……………
…………………………………………………………………………………
……………………………….
4) Explain the Spring Boot application execution with Maven.
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………....................................……………
…………………………………………………………………………………
……………………………….
5) What are the steps to deploy Spring Boot web applications as JAR and WAR
files?
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………....................................……………
…………………………………………………………………………………
……………………………….

9.6 SUMMARY

This unit has described Spring Boot facilitates the developers to create a Spring based
web application with minimum lines of code since it provides auto configuration out-
of-the-box. This unit has explained the following:

• A class with the main method and annotated with @SpringBootApplication


is the entry point of the Spring Boot application.
• Spring Boot starters are the dependency descriptor that addresses the problem
of compatible versions of dependency management. It is also a one-stop-shop
for all the Spring and related technology that you need.
• Spring Boot provides two runner interfaces named as ApplicationRunner and
CommandLineRunner. These functional interfaces enable you to execute a
piece of code just after the Spring Boot application is started.
• Spring Boot DevTools important features such as Automatic restart, Live
Reload, Property Defaults such as cache disable and allows us to update pages
without restarting the application
• Actuator provides production-ready features such as application monitoring,
Network traffic, State of database and many more. Without any
implementation, Actuator provides production-grade tools.
• By default, only two endpoints /health and /info are available. Other required
endpoints can be enabled by adding
management.endpoints.web.exposure.include property into
application.properties.
• Various ways to define application properties such as command-line
argument, application.properties file and application.yml file.

30
• Spring Boot supports keeping properties files at any location. We can Spring Boot and Hibernate
externalize the properties file so that if any property is changed, a new build is (ORM)
not required.
• Spring Boot supports the concept of an active profile. There can be multiple
properties files corresponding to each environment. At run time, Spring Boot
selects the desired environment properties file based on active profile.
• Spring Boot application can be executed from command line with Spring
Boot Maven plugin using mvnspring-boot:run and can be executed as a
standalone application by java -jar <fileName>

9.7 SOLUTIONS/ANSWER TO CHECK YOUR


PROGRESS

Check Your Progress 1

1) Spring Boot is a utility project which enables an organization to develop


production-ready spring-based applications and services with less effort,
reduced cost and minimal configuration. Spring Bootfacilitates the developers
to create a Spring based web application with minimum lines of code since it
provides auto configuration out-of-the-box.
It is a module that enriches the Spring framework with Rapid Application
Development (RAD) feature. It provides an easy way to create a stand-alone
and production ready spring application with minimum configurations. Spring
Boot is a combination of Spring framework with auto-configuration and
embedded Servers.

Spring Boot provides a vast number of features and benefits. A few of them
are as follows:

• Everything is auto-configured in Spring Boot.


• Spring Boot starter eases the dependency management and
application configuration
• It simplifies the application deployment by using an embedded server
• Production-ready features to monitor and manage applications such as
health checks, metrics gathering etc.
• Reduces the application development time and run the application
independently
• Very easy to understand and develop Spring application

2) Spring Boot auto configures all required configurations. It performs auto-


configuration by scanning the classes in classpath annotated with
@Component or @Configuration. @SpringBootApplication annotation
comprises the following three annotations with their default values-
o @EnableAutoConfiguration
o @ComponentScan
o @Configuration
For details, check section 9.2.1

3) Spring Boot starters are the dependency descriptor that addresses the problem
of compatible versions of dependency management. Starter POMs are a set of
convenient dependency descriptors that you can include in your application.
31
Introduction To Spring You get a one-stop-shop for all the Spring and related technology that you
Boot need from Spring Boot starters. Spring Boot provides a number of starters that
make development easier and rapid. Spring Boot provides many numbers
starter, and a few of them are listed below-
spring-boot-starter-web It is used for building web applications, including
RESTful applications using Spring MVC. It uses
Tomcat as the default embedded container.
spring-boot-starter-jdbc It is used for JDBC with the Tomcat JDBC
connection pool.
spring-boot-starter-validation It is used for Java Bean Validation with Hibernate
Validator.
spring-boot-starter-security It is used for Spring Security.
spring-boot-starter-data-jpa It is used for Spring Data JPA with Hibernate.

4) As the name implies, it is used to automatically configure the required


configuration for the application. It means Spring Boot looks for auto-
configuration beans on its classpath and automatically applies them. For
example, if H2 dependency is added and you have not manually configured
any database connection beans, then Spring will auto-configure H2 as an in-
memory database.
To disable the auto-configuration property, you have to use exclude attribute
of @EnableAutoConfiguration. For example, Data Source autoconfiguration
can be disabled as:
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.cla
ss})
The property spring.autoconfigure.exclude property can be used in
application.properties or application .yaml file to mention the exclude list of
auto-configuration classes.

5) Spring Boot provides two runner interfaces named as ApplicationRunner and


CommandLineRunner. These interfaces enable you to execute a piece of code
just after the Spring Boot application is started.
Both interfaces are Functional Interface. If any piece of code needs to be
executed when Spring Boot Application starts, we can implement either of
these functional interfaces and override the single method orun.
Check the details of ApplicationRunner and CommandLineRunner in
section 9.2.4

Check Your Progress 2

1) Spring Boot DevTools was released with Spring Boot 1.3. DevToolsstands for
developer tool. Aim of DevTools module is to enhance the application
development experience by improving the development time of the Spring
Boot Application. During a web application development, a developer
changes the code many times and then restarts the application to verify the
code changes. DevTools reduces the developer effort. It detects the code
changes and restarts the application. DevTools can be integrated into a Spring
Boot application just by adding the following dependency into pom.xml.

32
<dependency> Spring Boot and Hibernate
(ORM)
<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<scope>runtime</scope>

<optional>true</optional>

</dependency>

Spring Boot DevTools provides the following important features –


• Automatic Restart
• Live Reload
• Property defaults

2) Spring Boot Actuator is a sub-projectof the Spring Boot framework. The


Actuator provides production-ready features such as application monitoring,
Network traffic, State of database and many more. Without any
implementation, Actuator provides production-grade tools. In Spring Boot
application, Actuator is primarily used to expose operational information
about the running application such as info, health, dump, metrics, env etc. It
provides HTTP and JMX endpoints to manage and monitor the Spring Boot
application. There are three main features of the Spring Boot Actuator-
o Endpoints
o Metrics
o Audit
By default, only two endpoints /health and /info are available. Other required
endpoints can be enabled by adding
management.endpoints.web.exposure.include property into
application.properties. By default, all Actuator endpoints are now placed
under the /actuator path. Some of the important endpoints are listed below –
o /health provides the health status of application
o /info provides general information about the application. It might be
build information or the latest commit information.
o /metrics provides metrics of application. Returned metrics include
generic metrics as well as custom metric.
o /env provides the current environment properties.

3) To create a simple Hello World rest application using Spring Boot, we need to
perform the below steps:

o Create a Spring Boot Project using Spring Initializr. Visit at


https://start.spring.io/ and generate the Spring Boot project with
Spring Web dependency.
o Import the project in Eclipse IDE as a maven project.
o Create a controller package and add a HomeController class
annotated with @RestController.

33
Introduction To Spring @RestController
Boot
publicclassHomeController {

@GetMapping(value="/")

public String index() {

return"Hello World!!";

o From the root of the project, execute command mvnspring-


boot:run in order to run the application.
o Access the application with http://localhost:8080

Check Your Progress 3

1) Application Properties enable us to work in different environments such as


Prod, Dev, Test. Spring Boot application properties can be set into properties
files, YAML files, command-line arguments and environment variables.
Spring Boot supports keeping properties file at any location. We can
externalize the properties file so that if any property is changed, a new build is
not required. Just application restart will take effect on the changed property.
While executing the application jar file, the following command line
argument is used to specify the location of the property file.

-Dspring.config.location = C:\application.properties

2) Yes, we can change the port of the embedded tomcat server by using the
application properties file. In application.properties file, you must add a
property of “server.port” and assign it to any port you wish to. For example,
if you want to assign it to 8081, then you have to mention server.port=8081.
Once you mention the port number, the application properties file will be
automatically loaded by Spring Boot, and the required configurations will be
applied to the application.

3) An application is executed in multiple environments such as test,


development, production. To modify application.properties file based on the
environment is not an ideal approach. There must be multiple properties files
corresponding to each environment. At run time Spring Boot must be able to
select the desired environment properties file.
Spring Boot supports different properties based on the Spring active profile.
By default, Spring Boot uses application.properties file. But Spring Boot
allows to set the active profile and corresponding properties file that is used
by Spring Boot. Following command shows to set dev as active profile while
starting the application from command line, and the execution will read the
application-dev.properties file since active profile is set as dev.
java –jar demo.jar --spring.profiles.active=dev

4) Check section 9.5.1


5) Check section 9.5.3

34
Spring Boot and Hibernate
9.8 REFERENCES/FURTHER READING (ORM)

● Craig Walls, “Spring Boot in action” Manning Publications, 2016.


https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)
● Christian Bauer, Gavin King, and Gary Gregory, “Java Persistence with
Hibernate”,Manning Publications, 2015.
● Ethan Marcotte, “Responsive Web Design”, Jeffrey Zeldman Publication,
2011(http://nadin.miem.edu.ru/images_2015/responsive-web-design-2nd-
edition.pdf)
● Tomcy John, “Hands-On Spring Security 5 for Reactive Applications”,Packt
Publishing,2018
• https://spring.io/guides/gs/spring-boot/
• https://dzone.com/articles/introducing-spring-boot
• https://www.baeldung.com/spring-boot
• https://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/pdf/spring-
boot-reference.pdf
• https://www.baeldung.com/spring-boot-starters
• https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf
• https://www.baeldung.com/spring-boot-devtools
• https://docs.spring.io/spring-boot/docs/1.5.16.RELEASE/reference/html/using-
boot-devtools.html
• https://howtodoinjava.com/spring-boot/developer-tools-module-tutorial/
• https://www.baeldung.com/spring-boot-run-maven-vs-executable-jar

35
UNIT 10 CONFIGURATION OF
HIBERNATE(ORM)

Structure Page No.

10.0 Introduction
10.1 Objectives
10.2 Hibernate Overview
10.3 Hibernate Configuration with Annotation
10.3.1 A Complete Hibernate Example
10.4 Hibernate CRUD (Create, Read, Update, and Delete) Features
10.4.1 Hibernate Get Entity – get vs load
10.4.2 Hibernate Insert Entity – persist, save and saveOrUpdate
10.4.3 Hibernate Query Language (HQL)
10.5 Spring Data JPA Overview
10.6 Summary
10.7 Solutions/ Answer to Check Your Progress
10.8 References/Further Reading

10.0 INTRODUCTION

In computer science, object-relational mapping (ORM, O/RM, and O/R mapping tool)
is a programming technique for converting data between incompatible type systems
using object-oriented programming languages. ORM makes it possible to perform
CRUD (Create, Read, Update and Delete) operations without considering how those
objects relate to their data source. It manages the mapping details between a set of
objects and the underlying database. It hides and encapsulates the changes in the data
source itself. Thus, when data sources or their APIs change, only ORM change is
required rather than the application that uses ORM.
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework
which maps the POJOs to relational database tables. The usage of Hibernate as a
persistence framework enables the developers to concentrate more on the business
logic instead of making efforts on SQLs and writing boilerplate code. There are
several advantages of Hibernate, such as:
• Open Source
• High Performance
• Light Weight
• Database independent
• Caching
• Scalability
• Lazy loading
• Hibernate Query Language (HQL)

Java Persistence API (JPA) is a specification that defines APIs for object-relational
mappings and management of persistent objects. JPA is a set of interfaces that can be
used to implement the persistence layer. JPA itself doesn’t provide any
implementation classes. In order to use the JPA, a provider is required which
implements the specifications. Hibernate and EclipseLink are popular JPA providers.
Spring Data JPA is one of the many sub-projects of Spring Datathat simplifies the
data access to relational data stores. Spring Data JPA is not a JPA provider; instead, it
1
Configuuration of wraps the JP PA provider and adds its own features like a no-code implemen ntation of
Hibernaate (ORM) the reposittory pattern n. Spring Daata JPA usees Hibernate as the defaault JPA
provider. JPAJ provider is configuraable, and otheer providers can also be uused with
Spring Dataa JPA. Spring Data JPA provides a complete absttraction over the DAO
layer into thhe project.
This unit ex
xplains only HHibernate in detail
d with itss architecture and sample examples.
This unit allso covers thee relationshipp between Sprring Data JPA A, JPA and Hibernate.
H
There are many
m similar CCrud operatioons available in Hibernate,, such as savee, persist,
saveOrUpd date, get and d load. Hibeernate entity state definees the behaviior of the
operations. Thus, one shoould study thee Hibernate entity states ass transient, persistent,
p
detached an nd removed very carefully y in order to have
h in-depthh insights for Hibernate
CRUD operrations.

This unit also covers thhe overview of Spring Data D JPA wiith its advanntages and
w this reducees the effort of a developerr to implemennt the data acccess layer.
explains how
The next un
nit covers Spriing Data JPAA in detail.

10.1 OBJECT
O TIVES

After going through this unit, you willl be able to:


• desscribe Hibernaate as ORM tool,
• expplain Hibernatte architecturre,
• usee Annotations in Hibernatee and Java-bassed Hibernatee configuratioon,
• usee Hibernate C CRUD operatiions such as save,s persist, saveOrUpdatte,
• diffferenciate bettween same taask performinng operations such asget VsV load
etc..,
• estaablish the relaationship betw
ween Spring D Data JPA, JPA A and Hibernnate, and
• usee Spring Data JPA.

10.2 HIBERN
H ATE OV
VERVIEW
W

Hibernate iss an open-soource Java peersistence fram mework creaated by Gavinn King in
2011. It sim
mplifies the ddevelopment of Java appllications to innteract with databases.
d
Hibernate iss a lightweigght, powerful and high-perrformance OR RM (Object Relational
R
Mapping) toool that simpllifies data creation, data manipulation an
nd data accesss.
The Java Persistence
P A
API (JPA) is a specificatioon that defines how to persist data
in Java applications.
a . Hibernate is a popuular ORM which w is a standard
implementaation of the JJPA specificaation with a few additionnal features specific
s to
Hibernate. Hibernate
H liees between Jaava Objects and databasee servers to hhandle all
persistence and retrieval of those objeects using apppropriate mechanisms andd patterns.
A schematicc diagram is shown
s in Figuure 10.1

Figure1
10.1 Hibernate ORM
O

2
10.2
2.1 Hibernaate Architeecture Spring Booot and Hibernatte
(ORM)
Hibeernate has fouur-layered archhitecture. Thee Hibernate inncludes manyy objects suchh as
persiistent objects,, session factoory, session, connection
c faactory, transacction factory,
transsaction etc. Hiigh-level archhitecture diaggram is shownn in Figure 100.2

Figure 10.2 Hibern


nate Architectture

A deetailed view of the Hiberrnate Applicaation Architeecture with some of the ccore
classses is shown in Figure 10.33

Figure10.3 Hibernate
H Dettailed Architecctural View

Hibeernate uses Java APIs like Java Transaction


T API (JTA), Java Databbase
Connnectivity (JD
DBC) and JavaJ Namingg and Direcctory Interfacce (JNDI). The
know ments helps yoou to understand the inteernal
wledge of Hibbernate archiitecture elem
workking of Hibernnate.

Con
nfiguration
An innstance of Coonfiguration allows
a the appplication to sppecify propertties and mappping
docuuments to be used
u when creeating a SessiionFactory. The
T Configuraation object iss the
first object whichh is being created in the Hibernate
H appllication. The Configuratioon is
3
Configuration of only an initialization-time object. Usually, a Hibernate application creates a single
Hibernate (ORM) Configuration, builds a single immutable SessionFactory and then instantiate Sessions
in threads servicing client requests. Configuration represents an entire set of mappings
of an application's Java types to an SQL database. The Configuration can be
configured either programmatically or using configuration file. The configuration file
can be either an XML file such as hibernate.cfg.xml or a properties file such as
hibernate.properties.
Xml based hibernate configuration for Mysql database is shown below-
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.0.dtd">

<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>

Properties file base hibernate configuration for Mysql database is shown below-

hibernate.dialect= org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class= com.mysql.jdbc.Driver
hibernate.connection.url= jdbc:mysql://localhost:3306/test
hibernate.connection.username= root
hibernate.connection.password=root
hibernate.show_sql=true
hibernate.hbm2ddl=update

SessionFactory
4
Spring Boot and Hibernate
The Hibernate creates an immutable SessionFactory object using the Configuration (ORM)
object. SessionFactory is used to instantiate the session object in a thread to service
client requests. SessionFactory object is thread safe and used by all the threads of an
application.
SessionFactory object is per database using a separate configuration file. Thus, for
multiple databases, we will require to create multiple SessionFactory objects. The
SessionFactory is a heavyweight object, and it is created at the time of application
startup.

Session
The session object provides an interface to interact with the database from an
application. It is lightweight, which instantiates each time an interaction is required
with the database. Session objects are used to retrieve and save persistent objects. It is
a short-lived object which wraps the JDBC connection. It also provides a first-level
cache of data.

Transaction
A Transaction represents a unit of work with the database, and most of the RDBMS
supports transaction functionality. Transaction object provides a method for
transaction management. It enables data consistency and rollback in case something
wrong.

Query
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data
from the database and create objects. A Query instance is used to bind query
parameters, limit the number of results returned by the query, and finally to execute
the query.

Persistent Objects
These are plain old java objects (POJOs), which get persisted into the database by
hibernate. Persistent objects can be configured in configurations files
(hibernate.cfg.xml or hibernate.properties) or annotated with @Entity annotation.

First-level Cache
Cache is a mechanism that improves the performance of any application. Hibernate
provides a caching facility also. First-level cache is enabled by default, and it can’t be
disabled. Hibernate ORM reduces the number of queries made to a database in a
single transaction using First-level cache. First-level cache is associated with Session
object and it is available till the session object is alive. First-level cache associated
with session objects is not accessible to any other session object in other parts of the
application. Important facts about First-level cache is as followings-
• First-level cache scope is session. Once the session object is closed, the first-
level cache is also destroyed.
• First-level cache can’t be disabled.
• First time query for an entity into a session is retrieved from the database and
stored in the First-level cache associated with the Hibernate session.
• Query for an object again with the same session object will be loaded from
the cache.
• Session evict() method is used to remove the loaded entity from Session.
• Session clear() method is used to remove all the entities stored in the cache.

Second-level Cache

5
Configuration of Second-level cache is used globally in Session Factory scope. Once the session
Hibernate (ORM) factory is closed, all cache associated with it dies, and the cache manager is also
closed down. Working of Second-level cache is as followings-
• At first, the hibernate session tries to load an entity, then First-level cache is
looked up for cached copy of entity.
• If an entity is available in First-level cache, it is returned as a result of the load
method.
• If an entity is not available in First-level cache, Second-level cache is looked
up for cached copy of the entity.
• If an entity is available into Second-level cache, it is returned as a result of the
load method. But before returning the result, the First-level cache is being
updated so that the next invocation for the same entity can be returned from
the First-level cache itself.
• If an entity is not found in any of cache, the database query is executed, and
both the cache is being updated.
• Second level cache validates itself for modified entities, if the modification
has been done through hibernate session APIs.

Check Your Progress 1

1) What is Hibernate Framework? List down its advantages.


…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
2) Explain some important interfaces of Hibernate framework.
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
3) What is Hibernate caching? Explain Hibernate first level cache.
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
4) Explain the working of second level cache.
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………

10.3 HIBERNATE CONFIGURATION WITH

6
Spring Boot and Hibernate
ANNOTATION (ORM)

This section explains various annotations available in Hibernate. Later a “Hello


World” hibernate example will be created using explained annotation.

@Entity
In JPA, POJOs are entities that represent the data that can be persisted into a database.
An entity represents the table in a database. Every instance of an entity represents a
row in the table. Let’s say there is a POJO named Student, which represents the data
of Student. In order to store the student records into a database, Student POJO must
be defined as an entity so that JPA is aware of it. This can be done by annotating
POJO class with @Entity annotation. The annotation must be defined at class level.
The Entity must have no-arg constructor and a primary key. The entity name defaults
to the name of the class. Its name can be changed using the name element into
@Entity.
@Entity(name = “student”)

public class Student

Entity classes must not be declared final since JPA implementations try to subclass the
entity in order to provide their functionality.
@Id
The primary key uniquely identifies the instances of the entity. The primary key is a
must for each JPA entity. The @Id annotation is used to define the primary key in a
JPA entity. Identifiers are generated using @GeneratedValue annotation. There are
four strategies to generate id. The strategy element in @GeneratedValue can have
value from any of AUTO, TABLE, SEQUENCE, or IDENTITY.

@Entity
public class Student

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
privateintid;

@Table
Bydefault, the name of the table in the database will be the same as the entity name.
@Table annotation is used to define the name of the table in the database.

@Entity

7
Configuration of @Table(name="STUDENT")
Hibernate (ORM)
publicclass Student

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

privateintid;

@Column
Similar to @Table annotation, @Column annotation is used to provide the details of
columns into the database. Check the other elements defined into @Column, such as
length, nullable, unique.

@Entity

@Table(name="STUDENT")

publicclass Student

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

privateintid;

@Column(name = "firstname", length=50, nullable=false, unique=false)

private String firstName;

@Transient
@Transient annotation is used to make a field into an entity as non-persistent. For
example, the age of a student can be calculated from the date of birth. Thus, age field
can be made as non-persistent into Student class as shown below-

@Entity

@Table(name=”STUDENT”)

publicclass Student

8
@Id Spring Boot and Hibernate
(ORM)
@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = “id”)

privateintid;

@Column(name = “firstname”, length=50, nullable=false, unique=false)

private String firstName;

@Column(name = “lastname”, length=50, nullable=true, unique=false)

private String lastName;

@Transient

privateintage;
}

@Temporal
The types in the java.sql package such as java.sql.Date, java.sql.Time,
java.sql.Timestamp are in line with SQL data types. Thus, its mapping is
straightforward, and either the @basic or @column annotation can be used. The type
java.util.Date contains both date and time information. This is not directly related to
any SQL data type. For this reason, another annotation is required to specify the
desired SQL type. @Temporal annotation is used to specify the desired SQL data
type. It has a single element TemporalType. TemporalType can be DATE, TIME or
TIMESTAMP. The type of java.util.Calendar also requires @Temporal annotation
to map with the corresponding SQL data type.
@Entity
@Table(name="STUDENT")
publicclass Student
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
privateintid;
@Column(name = "firstname", length=50, nullable=false, unique=false)
private String firstName;
@Column(name = "lastname", length=50, nullable=true, unique=false)
private String lastName;
@Transient
privateintage;
@Temporal(TemporalType.DATE)
@Column(name = "dateofbirth", nullable = false)
private Date dob;
}

The types from the java.time package in Java 8is directly mapped to corresponding
SQL types. So there's no need to explicitly specify @Temporal annotation:
• LocalDate is mapped to DATE

9
Configuration of
• Instant, LocalDateTime, OffsetDateTime and ZonedDateTime are mapped
Hibernate (ORM) to TIMESTAMP
• LocalTime and OffsetTime are mapped to TIME

10.3.1 A Complete Hibernate Example

This section explains all steps required to create Hibernate Application with Mysql
using Java configuration without using hibernate.cfg.xml. In the application, the Data
Access Object (DAO) layer persists the Student entity and retrieves the persisted
entity from the database. Required tools and technologies are as follows:
• IDE – Eclipse
• Hibernate 5.3.7.Final
• Maven
• MySQL 8
• JavaSE 1.8
Perform the following steps to create and run the Hibernate Application.

Step 1: Maven project is created into Eclipse IDE. The directory structure of the
project with various layers is shown below-

Step 2: Create a maven project with the following dependencies in pom.xml

<dependencies>
<!‐‐ https://mvnrepository.com/artifact/mysql/mysql‐connector‐java ‐‐>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql‐connector‐java</artifactId>
<version>8.0.13</version>
</dependency>
<!‐‐ https://mvnrepository.com/artifact/org.hibernate/hibernate‐core ‐
‐>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate‐core</artifactId>
<version>5.3.7.Final</version>

10
</dependency> Spring Boot and Hibernate
<dependency> (ORM)
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind‐api</artifactId>
<version>2.3.2</version>
</dependency>
</dependencies>

Step 3: Create Hibernate configuration file named as HibernateUtil with Java


configuration. This contains the information about the database and JPA entity
mapping.

publicclassHibernateUtil
{
privatestaticSessionFactorysessionFactory;
publicstaticSessionFactorygetSessionFactory()
{
if (sessionFactory == null)
{
try
{
Configuration configuration = newConfiguration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = newProperties();
settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
settings.put(Environment.URL,
"jdbc:mysql://localhost:3306/test?useSSL=false");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "root");
settings.put(Environment.DIALECT,
"org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "create‐drop");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Student.class);
ServiceRegistryserviceRegistry = newStandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch (Exception e)
{
e.printStackTrace();
}
}
returnsessionFactory;
}
}

In above configuration, list of possible options for Environment.HBM2DDL_AUTO


are as followings-

• validate: validate the schema, makes no changes to the database.


• update: update the schema.
11
Configuration of • create: creates the schema, destroying previous data.
Hibernate (ORM) • create-drop: drop the schema when the SessionFactory is closed explicitly,
typically when the application is stopped.
• none: does nothing with the schema, makes no changes to the database

Step 4: Create a JPA Entity/Persistent class. This example creates the Student
persistent class, which is mapped to a student database table. A Persistent class should
follow some rules:
• Prefer non-final class: Hibernate uses proxies to apply some performance
optimization. JPA entity or Hibernate Persistent class as final limits the ability
of hibernate to use proxies. Without proxies, the application loses lazy loading
which will cost performance.
• A no-arg constructor: Hibernate creates an instance of a persistent class
using newInstance() method. Thus, a persistent class should have a default
constructor at least package visibility.
• Identifier Property: Each JPA entity should have a Primary Key. Thus an
attribute should be annotated with @Id annotation.
• Getter and Setter methods: Hibernate recognizes the method by getter and
setter method names by default.

/**
* @authorRahulSingh
*/
@Entity
@Table(name="student")
publicclass Student
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
privateintid;
@Column(name = "firstname", length=50, nullable=false, unique=false)
private String firstName;
@Column(name = "lastname", length=50, nullable=true, unique=false)
private String lastName;

@Transient
privateintage;
@Temporal(TemporalType.DATE)
@Column(name = "dateofbirth", nullable = false)
private Date dob;
private String email;
publicStudent()
{
}
publicStudent(String firstName, String lastName, String email, Date dob)
{
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.dob = dob;
}
publicintgetId()
{
returnid;
}
publicvoidsetId(intid)
{
this.id = id;
}
public String getFirstName()
{
returnfirstName;
}
publicvoidsetFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
returnlastName;

12
} Spring Boot and Hibernate
publicvoidsetLastName(String lastName) (ORM)
{
this.lastName = lastName;
}
public String getEmail()
{
returnemail;
}
publicvoidsetEmail(String email)
{
this.email = email;
}
publicintgetAge()
{
returnage;
}
publicvoidsetAge(intage)
{
this.age = age;
}
public Date getDob()
{
return dob;
}
publicvoidsetDob(Date dob)
{
this.dob = dob;
}
@Override
public String toString()
{
return"Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", dob="
+ dob + ", email=" + email + "]";
}
}

Step 5: Create a DAO layer that performs the operations to the database. StudentDao
code is given below, which performs two operations.
• save(Student student) – saves a given Student into the database.
• getStudentList() – retrieves all students from the database.

publicclassStudentDao

publicvoidsave(Student student)

Transaction txn = null;

try (Session sess = HibernateUtil.getSessionFactory().openSession())

txn = sess.beginTransaction(); // start a transaction

sess.save(student); // save the student object

txn.commit(); // commit transaction

catch (Exception e)

13
Configuration of
Hibernate (ORM) if (txn != null)

txn.rollback();

e.printStackTrace();

public List<Student>getStudentList()
{
try (Session sess = HibernateUtil.getSessionFactory().openSession())
{
returnsess.createQuery("from Student", Student.class).list();
}
}

Step 6: Create the main class named as HibernateApp


publicclassHibernateApp
{
publicstaticvoidmain(String[] args) throws Exception
{
StudentDaostudentDao = newStudentDao();
SimpleDateFormatdateFormat = newSimpleDateFormat("dd-MM-yyyy");
Date dob = dateFormat.parse("10-08-1986");
Student student = newStudent("Rahul", "Singh", "[email protected]", dob);
studentDao.save(student);
List < Student >students = studentDao.getStudentList();
students.forEach(s ->System.out.println(s));
}
}

Step 7: Run the application from eclipse IDE or command line. Check the logs in the
console and record into the database. The application is executed with eclipse IDE. It
saves student records into a database. Console log with insert and select query
generated by Hibernate as shown below:

14
Spring Boot and Hibernate
Output (ORM)

10.4 HIBERNATE CRUD (CREATE, READ,


UPDATE AND DELETE) FEATURES

This section describes the persistence context. It also explains how hibernate uses the
concept of persistence context to solve the problem of managing the entities at
runtime.

The persistence context sits between the application and database store. Persistence
context keeps monitoring the managed entity and marks the entity as dirty if some
modification has been done during a transaction. Persistence context can be
considered as a staging area or first-level cache where all the loaded and saved objects
to the database reside during a session.

The instance of org.hibernate.Sessionrepresents the persistence context in Hibernate.


Similarly, the instance of javax.persistence.EntityManagerrepresents the persistence
context in JPA. When Hibernate is used as a JPA provider, EntityManager interface is
used to perform database related operations. In this case, basically
java.persistence.EntityManager wraps the session object. Hibernate Session has more
capability than JPA EntityManager. Thus, sometimes it is useful to work directly with
Session.

Hibernate Entity Lifecycle States


Hibernate works with POJO. Without any Hibernate specific annotation and mapping,
Hibernate does not recognize these POJO’s. Once properly annotated with required
annotation, hibernate identifies them and keeps track of them to perform database
operations such as create, read, update and delete. These POJOs are considered as
mapped with Hibernate. An instance of a class mapped with Hibernate can be any of
the four persistence states which are known as hibernate entity lifecycle states and
depicted in Figure 10.4.

1. Transient
2. Persistent
3. Detached
4. Removed

15
Configuuration of Transient: An object off a POJO class is in a transsient state when created ussing a new
Hibernaate (ORM)

F
Figure 10.4: Hiibernate Entitty Lifecycle Sttates

operator in Java. In the ttransient statee, the object is not relatedd to any databbase table.
An object in i a transiennt state is nott managed bby session orr Entity Mannager. The
transient staate object is not
n tracked foor any modification from the t persistencce context.
Thus, any modification
m oof a transient state
s object does
d not impacct the databasse.

Persistent: When a Traansient entity is saved, it iis associated with a uniquue session
object and it
i enters into a Persistent state.
s A Persiistent state enntity is a repreesentation
of a row intto a databasee, although thhe row might not exist in the database yet; upon
flushing thee session, thee entity is gu
uaranteed to have
h a corresponding row w into the
database. Session
S manaages the Perssistent state objects and keeps track of every
modificationn done. Sesssion propaggates all the modificatioons into the database
automatically. The Hibbernate sessio on’s followinng methods make an enntity into
Persistent sttate.
• sesssion.save()
• sesssion.update()
• sesssion.saveOrU Update()
• sesssion.lock()
• sesssion.merge()

publicclassPersiistentStateExamplle
{
publicstaticvoidmain(String[] args)
{
Transactionn txn = null;
try (Sessionn sess = HibernateeUtil.getSessionFactory().openSessioon())
{
ttxn = sess.beginTrransaction(); // starrt a transaction
SSimpleDateFormaatdateFormat = new wSimpleDateForm mat("dd-MM-yyyyy");
D
Date dob = dateFoormat.parse("10-099-1995");
SStudent student = newStudent("Rahuul", "", "[email protected]", doob); // 1
ssess.saveOrUpdatee(student); // 2
LList<Student>studdents = sess.createQ Query("from Studdent", Student.classs).list();
sstudents.forEach(ss ->System.out.priintln(s)); // 3
sstudent.setLastNam me("Singh"); //4
sstudents = sess.creeateQuery("from S Student",Student.cllass).list();
sstudents.forEach(ss ->System.out.priintln(s)); //5
ttxn.commit(); // 6
}
catch (Exceeption e)

16
{ Spring Boot and Hibernate
if (txn != null) (ORM)
{
txn.rollback();
}
e.printStackTrace();
}
}
}

Output:

Check the following code into the above example code.


1. The student object created using the new operator is in a transient state.
2. session.saveOrUpdate() method makes the student object into persistent state.
Once the object is in persistent state, Session keeps track of any modification
and automatically flushes the changes into the database.
3. All the records of the student table are being rendered. Notice that at this point
lastName as empty for id 1.
4. The student’s last name is updated. The student entity is in the persistent state,
and Session keeps track of this change and updates the database
automatically. The update statement is issued and can be found in the log.
5. All the records of the student table are being rendered. Check at this point
lastNameis updated for id 1.
6. The transaction is committed, and all required changes are synced with the
database.
Detached: On call of any session method such as clear(), evict() or close() make the
persistent state objects into the detached state. Session does not keep track of any
modification to detached state objects. Detached entity has a corresponding row in the
database but changes to the entity will not be reflected in the database.
In order to persist the changes of entity, detached entities must be re-attached to the
valid Hibernate Session. The detached state entity can be re-attached to the Hibernate
Session with the call of following methods-
• session.update()
• session.merge()
• session.saveOrUpdate()

publicclassDetachedStateExample
{
publicstaticvoidmain(String[] args)
{
try
{
Session sess = HibernateUtil.getSessionFactory().openSession();
SimpleDateFormatdateFormat = newSimpleDateFormat("dd-MM-yyyy");
Date dob = dateFormat.parse("10-09-1995");
Student student = newStudent("Rahul", "", "[email protected]", dob);

17
Configuration of sess.saveOrUpdate(student); //student entity is in persistent state
Hibernate (ORM) List<Student>students = sess.createQuery("from Student",
Student.class).list();
sess.close(); // session close() makes student entity in detached state.
students.forEach(s ->System.out.println(s));
student.setLastName("Singh"); //This change is not tracked by Hibernate
session.
sess = HibernateUtil.getSessionFactory().openSession();
sess.update(student); // session update() makes the detached object into
persistent state.
students = sess.createQuery("from Student",Student.class).list();
students.forEach(s ->System.out.println(s));
sess.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Removed: Once a persistent object passes through session’s delete() method, it enters
into Removed state. When an application commits the session the entries in the
database that correspond to remove entities are deleted. At this state, java instance
exists but any change made to the instance will not be saved into the database. If the
removed entities are not referenced anywhere, then it is eligible for garbage
collection.
The following sections explain the various Hibernate operations and differences
between the same types of operations.

10.4.1 Hibernate Get Entity – get vs load


The Hibernate provides session.load() and session.get() methods to fetch the entity by
id. This section explains both the methods with examples and differences between
them.
Session load() method: There are several overloaded methods of load() into the
Hibernate Session interface. Each load() method requires the object’s primary key as
an identifier to load the object from the database. Along with the identifier, hibernate
also requires to know which class or entity name to use to find the object. Some
important overloaded methods are as follows:
• public Object load(Class<T>theClass, Serializable id) throws
HibernateException
• public Object load(String entityName, Serializable id) throws
HibernateException
• public void load(Object object, Serializable id) throws HibernateException
As we see that return type of load() method is either Object or void. Thus, we need to
typecast the returned object with a suitable type of class. There are other overloaded
methods of load(), which requires lock mode as an argument too. Hibernate picks the
correct lock mode for us. Thus, very rarely an overloaded load() method with lock
mode argument is used.

publicclassEntityLoadExample

publicstaticvoidmain(String[] args)
{
try
{
18
Session sess = HibernateUtil.getSessionFactory().openSession(); Spring Boot and Hibernate
SimpleDateFormatdateFormat = newSimpleDateFormat("dd-MM-yyyy"); (ORM)
Date dob = dateFormat.parse("10-09-1995");
Student student = newStudent("Rahul", "Singh", "[email protected]", dob);
sess.save(student); //student entity is in persistent state
sess.close();

intstudentId = student.getId(); //Id has been generated and set on call of save method.

// First Overloaded method example


Session sess1 = HibernateUtil.getSessionFactory().openSession();
Student student1 = (Student)sess1.load(Student.class, studentId);
System.out.println(student1);
sess1.close();

// Second Overloaded method example


Session sess2 = HibernateUtil.getSessionFactory().openSession();
Student student2 = (Student)sess2.load("com.org.ignou.entity.Student", studentId);
System.out.println(student2);
sess2.close();

// Third Overloaded method example


Session sess3 = HibernateUtil.getSessionFactory().openSession();
Student student3 = newStudent();
sess3.load(student3, studentId);
System.out.println(student3);
sess3.close();

}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Session get() method: Theget() method is similar to the load() method to fetch the
entity from the database. Like load() method, get() methods also take an identifier and
either an entity name of a class. Some important overloaded methods are as follows:
• public Object get(Class<T>clazz, Serializable id) throws HibernateException
• public Object get(String entityName, Serializable id) throws
HibernateException
Difference between load() and get() methods
Although load() and get() methods perform the same task, still the differences exist in
their return values in case the identifier does not exist in the database.
• The get() method returns NULL if the identifier does not exist.
• The load() method throws a runtime exception if the identifier does not exist.

10.4.2 Hibernate Insert Entity – persist, save and saveOrUpdate


The Session interface into Hibernate provides a couple of methods to transit an object
from transient state or detached state to persistent state e.g. persist(), save(), and
saveOrUpdate(). These methods are used to store an object in a database. There are
significant differences among these methods.
Session persist() method: The persist() method is used to add a record into the
database. This method adds a new entity instance to persistent context. On call of
persist() method, the transit state object moves into a persistent state object but not yet
saved to the database. The insert statement generates only upon committing the
transaction, flushing or closing the session. This method has a return type as void. The
semantics of persist() method is as follows:

19
Configuration of
• A transient state object becomes a persistent object, and the operation
Hibernate (ORM) cascades all of its relation with cascade=PERSIST or cascade=ALL. The spec
does not say that persist() method will generate the Id right away but on
commit or flush,non-null Id is guaranteed. The persist() method does not
promise the Id as non-null just after calling this method. Thus one should not
rely upon it.
• The persist() method has no impact on persistent objects, but the operation
still cascaded all of its relation with cascade=PERSIST or cascade=ALL.
• The persist() method on detached objects throws an exception, either upon
calling this method or upon committing or flushing the session.
A sample example explains the above points with output. For better understanding,
have hands-on with the following code.

publicclassEntityPersistExample
{
publicstaticvoidmain(String[] args)
{
try
{
Session sess = HibernateUtil.getSessionFactory().openSession();
Transaction txn = sess.beginTransaction();
SimpleDateFormatdateFormat = newSimpleDateFormat("dd-MM-yyyy");
Date dob = dateFormat.parse("10-09-1995");
Student student = newStudent("Abhishek", "Singh", "[email protected]", dob);
sess.persist(student); //student entity is transitioned from transit -> persistent
sess.persist(student); // No impact
sess.evict(student); // student entity is transitioned from persistent -> detached

sess.persist(student); // Exception. Since persistent state object is being persisted.


txn.commit();
sess.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Output:

Session save() method: The save() method is similar to the persist() method which
stores the record into the database. This is the original Hibernate Session method
which does not conform to JPA specification. The save() method differs from the
persist() method in terms of its implementation. The documentation of this method
states that at first, it assigns the generated id to the identifier and then persists the
entity. The save() method returns the Serializable value of this identifier. The
semantics of save() method is as follows:
20
● A transient state object becomes a persistent object and the operation cascades Spring Boot and Hibernate
all of its relation with cascade=PERSIST or cascade=ALL. At first it assigns (ORM)
the generated id to the identifier and then persists the entity.
● The save() method has no impact on persistent objects, but the operation still
cascaded all of its relations with cascade=PERSIST or cascade=ALL.
● The save() method on detached instances creates a new persistent instance. It
assigns the new generated Id to the identifier, which results in a duplicate
record in the database upon committing or flushing.
A sample example explains the above points with output as shown below:

publicclassEntitySaveExample

publicstaticvoidmain(String[] args)

try

Session sess = HibernateUtil.getSessionFactory().openSession();

Transaction txn = sess.beginTransaction();

SimpleDateFormatdateFormat = newSimpleDateFormat("dd-MM-yyyy");

Date dob = dateFormat.parse("10-09-1995");

Student student = newStudent("Abhishek", "Singh", "[email protected]", dob);

Integer id1 = (Integer) sess.save(student); //student entity is transitioned from transit ->
persistent

System.out.println("Id1: "+id1);

Integer id2 = (Integer) sess.save(student); // No impact

System.out.println("Id2: "+id2);

sess.evict(student); // student entity is transitioned from persistent -> detached

Integer id3 = (Integer) sess.save(student); // New Id generated and assigns it to identifier

System.out.println("Id3: "+id3);

txn.commit();

sess.close();

catch (Exception e)

e.printStackTrace();

}
}

21
Configuration of Execution Result:
Hibernate (ORM)

It can be observed in the above log that the detached instance is saved into the
database with a newly generated id and which results in a duplicate record into the
database as shown in the database screenshot.
Session saveOrUpdate() method: This method either performs save() or update() on
the basis of identifier existence. E.g. If an identifier exists for the instance, update()
method will be called otherwise save() will be performed. The saveOrUpdate()
method handles the cases where we need to save a detached instance. Unlike the
save() operation on detached instances, the saveOrUpdate() method does not result in
a duplicate record. Similar to update(), this method is used to reattach an instance to
the session. This method can be considered as a universal tool to make an object
persistent regardless of its state, whether it is transient or detached.

publicclassEntitySaveOrUpdateExample
{
publicstaticvoidmain(String[] args)
{
try
{
Session sess = HibernateUtil.getSessionFactory().openSession();
Transaction txn = sess.beginTransaction();
SimpleDateFormatdateFormat = newSimpleDateFormat("dd-MM-yyyy");
Date dob = dateFormat.parse("10-09-1995");
Student student = newStudent("Abhishek", "Singh", "[email protected]", dob);
sess.saveOrUpdate(student); //student entity is transitioned from transit -> persistent
System.out.println("Id1: "+student.getId());
sess.saveOrUpdate(student); // No impact
System.out.println("Id2: "+student.getId());

sess.evict(student); // student entity is transitioned from persistent -> detached

sess.saveOrUpdate(student); // Since Id exist, thus only update operation is performed on


detached entity
System.out.println("Id3: "+student.getId());
txn.commit();
sess.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}

22
} Spring Boot and Hibernate
(ORM)
Program Output:

As in output, you can see that saveOrUpdate() operation does not result in duplicate
records even for the detached entity . Thus, this operation can be used as a universal
tool to make an object persistent regardless of its state.

10.4.3 Hibernate Query Language (HQL)


Hibernate Query Language (HQL) is an object-oriented query language. HQL is
similar to the database SQL language. The main difference between HQL and SQL is
HQL uses class name instead of table name, and property names instead of column
name. HQL queries for Select, Update, Delete and Insert is explained below.
HQL Select query to retrieve the student data of id 1.

Query query = session.createQuery("from Student where id = :id ");


query.setParameter("id", "1");
List list = query.list();

HQL Update query to update the student’s last name as ‘Singh’ whose id 1.

Query query = session.createQuery("Update Student set lastName = :lastName where id = :id


");
query.setParameter("lastName", "Singh");
query.setParameter("id", "1");
int result = query.executeUpdate();

HQL Delete query to delete the student where id is 1.

Query query = session.createQuery("Delete Student where id = :id ");


query.setParameter("id", "1");
int result = query.executeUpdate();

HQL Insert
In HQL, only the INSERT INTO … SELECT … is supported; there is no INSERT
INTO … VALUES. HQL only support insert from another table. For example, insert
student records from another student_backup table. This is also called bulk-insert
statement.

Query query = session.createQuery("Insert into Student(firstName, lastName, emailId)"+


"Select firstName, lastName, emailed from
23
Configuration of student_backup");
Hibernate (ORM) int result = query.executeUpdate();

Check Your Progress 2


1) Describe @Temporal annotation with its usage.
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
2) List down the prescribed guidelines for a persistent class.
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
3) Explain Hibernate entity lifecycle state.
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
4) Explain HQL with examples.
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………

10.5 SPRING DATA JPA OVERVIEW

A well-structured codebase of a web project consists of various layers such as


Controller, Service and DAO (data access object) layer. Each layer has its own
responsibilities. While developing a web application, business logic should be focused
instead of technical complexity and boilerplate code. The DAO layer usually consists
of lots of boilerplate code, and that can be simplified. The simplification reduces the
number of artifacts that need to be defined and maintained. It also makes the data
access pattern and configuration consistent.

Different storage technologies require different API’s to access data, different


configurations and different methods. JPA handles the object-relational mappings and
technical complexities in JDBC based database interaction. The JPA provides
standardization across SQL data stores. The Java Persistence API (JPA) specification
and Spring Data JPA are very popular to simplify the DAO layer. Before the
explanation of Spring Data JPA, the following section explains the relationship
between Spring Data JPA, JPA and Hibernate.

Java Persistence API (JPA) is just a specification that defines APIs for object-
relational mappings and management of persistent objects. It is a set of interfaces that
can be used to implement the persistence layer. It itself doesn’t provide any
24
implementation classes. In order to use the JPA, a provider is required which Spring Boot and Hibernate
implements the specifications. Hibernate and EclipseLink are popular JPA providers. (ORM)

Spring Data JPA is one of the many sub-projects of Spring Datathat simplifies the
data access for relational data stores. Spring Data JPA is not a JPA provider; instead it
wraps the JPA provider and adds its own features like a no-code implementation of
the repository pattern. Spring Data JPA uses Hibernate as the default JPA provider.
JPA provider is configurable, and other providers can also be used with Spring Data
JPA. Spring Data JPA provides a complete abstraction over the DAO layer into the
project.

Spring Data JPA introduces the concept of JPA Repositories. JPA Repositories are a
set of Interfaces that defines query methods. It does not require writing native queries
anymore. Sometimes custom queries may be required in order to fetch the data from
the database. These queries are JPQL (Java Persistence Query Language), not native
queries. The advantages of using Spring Data JPA are as follows.

DAO Abstraction with No-Code Repositories


Spring Data JPA defines many Repository Interfaces such as CrudRepository,
PagingAndSortingRepository, JpaRepositoryhaving methods to store, retrieve, sorted
retrieval, paginated result and many more. The interfaces only define query methods
and spring provides proxy implementation at runtime. With Spring Data JPA, we
don’t have to write SQL statement, instead we just need to extend the interface
defined by Spring Data JPA for one of the entities. Based on JPA specification, the
underlying JPA implementation enables the Entity objects and their metadata
mapping. It also enables the entity manager who is responsible for persisting and
retrieving entities from the database.

Query Methods

Another robust and comfortable feature of Spring Data JPA is the Query Methods.
Based on the name of methods declared in the repository interfaces are converted to
low-level SQL queries at runtime. If the custom query isn’t complex, only a method is
required to be defined in the repository interface with a name starting with find…By.
Here is an example of a Student Repository to find a student by id and list of students
based on firstName and lastName.
public interface StudentRepository extends CrudRepository<Student, Long>
{
Optional<Student>findById(Long studentId);
List<Student>findByFirstNameAndLastName(String firstName, String lastName);
}

1. The first method corresponds to select * from student where id = ?


2. The second method corresponds to select * from student where firstName=
?andlastName = ?
Seamless Integration
Spring Data JPA seamlessly integrates JPA into the Spring stack, and its repositories
reduce the boilerplate code required to the JPA specification. Spring Data JPA also
helps your DAO layer integrating and interacting with other Spring based components
in your application, like accessing property configurations or auto-wiring the
repositories into the application service layer. It also works perfectly with Spring Boot
auto-configuration. We only need to provide the data source details and the rest of the
things like configuring and using EntityManager.

Check Your Progress 3

1) What is the difference between load() and get() method of Hibernate Session?
25
Configuration of …………………………………………………………………………
Hibernate (ORM)
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
2) What is the difference between persist() and save() method of Hibernate
Session?
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
3) Why is Hibernate Session's saveOrUpdate() method considered a universal
tool to make an object persistent?
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
4) Explain Spring Data JPA with its advantages.
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………
…………………………………………………………………………

10.6 SUMMARY

This unit has explained the concepts of ORM, Hibernate as ORM tool and Spring
Data JPA, which uses Hibernate as the default JPA provider. Below are the important
things which have been explained.

• Many different data storage technologies are available in this world, and each
one comes with its own data access API and driver.
• ORM stands for Object Relational Mapping, where a Java object is mapped to
a database table and with APIs.We need to work with objects and not with
native queries.
• The Java Persistence API (JPA) is a specification that defines how to persist
data in Java applications
• The Hibernate architecture elements includ such as SessionFactory, Session,
Query, First Level Cache and Second Level Cache. The first level cache can’t
be disabled.
• In order to use optimized performance of Hibernate, a POJO should follow
some rules such as-
o Prefer non-final class
o A no-arg constructor
o Identifier property
o Getter and Setter method
• The Hibernate entity lifecycle states as transient, persistent, detached and
removed.
26
• The Hibernate Session persist(), and the save() methods perform the same job Spring Boot and Hibernate
still; their implementation differs in terms of generated Id assignment. (ORM)
• The saveOrUpdate() method can be used as a universal tool for persisting an
entity irrespective of entity state.
• Spring Data JPA takes one step forward and enables developers to use data
access layers without any implementation.

10.7 SOLUTIONS/ANSWERS TO CHECK YOUR


PROGRESS
Check Your Progress 1

1) Hibernate is an open-source Java persistence framework created by Gavin


King in 2011. It simplifies the development of Java applications to interact
with databases. Hibernate is a lightweight, powerful, and high-performance
ORM (Object Relational Mapping) tool that simplifies data creation,
manipulation, and access.
The Java Persistence API (JPA) is a specification that defines how to
persist data in Java applications. Hibernate is a popular ORM which is a
standard implementation of the JPA specification with a few additional
features specific to Hibernate. Hibernate lies between Java Objects and
database servers to handle all persistence and retrieval of those objects using
appropriate mechanisms and patterns. There are several advantages of
Hibernate, such as:
o Open Source
o High Performance
o Light Weight
o Database independent
o Caching
o Scalability
o Lazy loading
o Hibernate Query Language (HQL)

2) Hibernate has four-layered architecture. The Hibernate includes many objects


such as persistent objects, sessionfactory, session, connection factory,
transaction factory, transaction etc. A few important interfaces have been
explained.
SessionFactory
The Hibernate creates an immutable SessionFactory object using the
Configuration object. SessionFactory is used to instantiate the session object
in thread to service client requests. SessionFactory object is thread-safe and
used by all the threads of an application.
SessionFactory object is per database using a separate configuration file.
Thus, for multiple databases, we will require to create multiple
SessionFactory objects. The SessionFactory is a heavyweight object, and it is
created at the time of application startup.
Session
The session object provides an interface to interact with the database from an
application. A Session object is lightweight, which instantiates each time an
interaction is required with the database. Session objects are used to retrieve
and save persistent objects. It is a short-lived object which wraps the JDBC
connection. It also provides a first-level cache of data.
Transaction

27
Configuration of A Transaction represents a unit of work with the database, and most of the
Hibernate (ORM) RDBMS supports transaction functionality. Transaction object provides
methods for transaction management. Transaction objects enable data
consistency, and rollback in case something goes wrong.

3) The cache is a mechanism that improves the performance of any application.


Hibernate provides a caching facility also. First-level cache is enabled by
default, and it can’t be disabled. Hibernate ORM reduces the number of
queries made to a database in a single transaction using First-level cache.
First-level cache is associated with Session object, and it is available till
session object is alive. First-level cache associated with session objects is not
accessible to any other session object in other parts of the application.
Important facts about First-level cache is as follows:
o First-level cache scope is session. Once the session object is closed,
the first-level cache is also destroyed.
o First-level cache can’t be disabled.
o First time query for an entity into a session is retrieved from the
database and stored in the First-level cache associated with the
hibernate session.
o Query for an object again with the same session object will be loaded
from cache.
o Session evict() method is used to remove the loaded entity from
Session.
Session’s clear() method is used to remove all the entities stored into cache.
4) Second-level cache is used globally in Session Factory scope. Once session
factory is closed, all cache associated with it die, and the cache manager
also closed down. Check section 9.2.1 for the working of Second-level
cache.
Check Your Progress 2

1) The types in the java.sql package such as java.sql.Date, java.sql.Time,


java.sql.Timestamp are in line with SQL data types. Thus, its mapping is
straightforward and either the @basic or @column annotation can be used.
The type java.util.Date contains both date and time information. This is not
directly related to any SQL data type. For this reason, another annotation is
required to specify the desired SQL type. @Temporal annotation is used to
specify the desired SQL data type. It has a single element TemporalType.
TemporalType can be DATE, TIME or TIMESTAMP. The type of
java.util.Calendar also requires @Temporal annotation to map with the
corresponding SQL data type.
2) A Persistent class should follow the following guidelines:
o Prefer non-final class: Hibernate uses proxies to apply some
performance optimization. JPA entity or Hibernate Persistent class as
final limits the ability of hibernate to use proxies. Without proxies,
application loses lazy loading, which will cost performance.
o A no-arg constructor: Hibernate creates an instance of a persistent
class using newInstance() method. Thus, a persistent class should
have default constructor at least package visibility.
o Identifier Property: Each JPA entity should have a primary Key.
Thus, an attribute should be annotated with @Id annotation.
o Getter and Setter methods: Hibernate recognizes the method by
getter and setter method names by default.

28
3) Hibernate works with POJO. Without any Hibernate specific annotation and Spring Boot and Hibernate
mapping, Hibernate does not recognize these POJOs. Once properly annotated (ORM)
with required annotation, hibernate identifies them and keeps track of them to
perform database operations such as create, read, update and delete. These
POJOs are considered as mapped with Hibernate. An instance of a class
mapped with Hibernate, can be any of the four persistence states which are
known as hibernate entity lifecycle states.
Same as Figure 10.5: Hibernate Entity Lifecycle States

1. Transient
2. Persistent
3. Detached
4. Removed

4) Check section 10.4.3

Check Your Progress 3

1) Difference between load() and get() methods


Although load() and get() methods perform the same task, still the differences
exist in their return values in case the identifier does not exist in the database.

• The get() method returns NULL if the identifier does not exist.
• The load() method throws a runtime exception if the identifier does
not exist.
2) Differences between save() and persist() methods are listedin the below table.

S.NO Key Save() Persist()

1 Basic It stores object in database It also stores object in database

2 Transaction It can save object within boundaries It can only save object within
Boundaries and outside boundaries the transaction boundaries

3 Return It returns generated id and return It does not return anything. Its
Type type is serializable return type is void.

29
Configuration of
Hibernate (ORM) 4 Detached It will create a new row in the table It will throw persistence
Object for detached object exception for detached object

5 Supported It is only supported by Hibernate It is also supported by JPA


by

3) This saveOrUpdate() method either performssave() or update() based on


identifier existence. E.g. If an identifierexists for the instance, update()
method will be called, otherwise save() will be performed. The
saveOrUpdate() method handles the cases where we need to save a detached
instance. Unlike the save() operation on detached instances, the
saveOrUpdate() method does not result in a duplicate record. Similar to
update(), this method is used to reattach an instance to the session. This
method can be considered as a universal tool to make an object persistent
regardless of its state,whether it is transient or detached.

4) Spring Data JPA is one of the many sub-projects of Spring Data which
simplifies the data access for relational data stores. Spring Data JPA is not a
JPA provider; instead it wraps the JPA provider and adds its own features like
a no-code implementation of the repository pattern. Spring Data JPA uses
Hibernate as the default JPA provider. JPA provider is configurable, and other
providers can also be used with Spring Data JPA. Spring Data JPA provides
complete abstraction over the DAO layer into the project. The advantages of
using Spring Data JPA are as follows:

DAO Abstraction with No-Code Repositories

Spring Data JPA defines many Repository Interfaces such as CrudRepository,


PagingAndSortingRepository, JpaRepository having methods to store,
retrieve, sorted retrieval, paginated result and many more.With Spring Data
JPA, we don’t have to write SQL statements; instead, we just need to extend
the interface defined by Spring Data JPA for one of the entities.
Query Methods
Another robust and comfortable feature of Spring Data JPA is the Query
Methods. Based on the name of methods declared in the repository interfaces
are converted to low level SQL queries at runtime.
Seamless Integration
Spring Data JPA seamlessly integrates JPA into the Spring stack, and its
repositories reduce the boilerplate code required to the JPA specification.
Spring Data JPA also helps the DAO layer integration and interaction with
other Spring based components in your application, like accessing property
configurations or auto-wiring the repositories into the application service
layer. It also works perfectly with Spring Boot auto-configuration.

10.8 REFERENCES/FURTHER READING

● Craig Walls, “Spring Boot in action” Manning Publications, 2016.


(https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)

30
● Christian Bauer, Gavin King, and Gary Gregory, “Java Persistence with Spring Boot and Hibernate
(ORM)
Hibernate”,Manning Publications, 2015.
● Ethan Marcotte, “Responsive Web Design”, Jeffrey Zeldman Publication,
2011(http://nadin.miem.edu.ru/images_2015/responsive-web-design-2nd-
edition.pdf)
● Tomcy John, “Hands-On Spring Security 5 for Reactive Applications”,Packt
Publishing,2018
● https://docs.jboss.org/hibernate/orm/3.5/reference/en/html/tutorial.html
● https://www.w3spoint.com/get-vs-load-hibernate
● https://www.baeldung.com/learn-jpa-hibernate
● https://www.javatpoint.com/hibernate-with-annotation
● https://www.tutorialspoint.com/jpa/index.htm
● https://howtodoinjava.com/hibernate/hibernate-jpa-2-persistence-annotations-
tutorial/
● https://docs.jboss.org/hibernate/orm/3.6/quickstart/en-US/html/hibernate-gsg-
tutorial-jpa.html
● https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate
● https://www.journaldev.com/3472/hibernate-session-get-vs-load-difference-
with-examples
● https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa
● https://dzone.com/articles/spring-data-jpa

31
UNIT 11 CRUD APPLICATION USING
SPRING BOOT AND HIBERNATE

Structure Page No.


11.0 Introduction
11.1 Objectives
11.2 Spring Data Repository
11.2.1 CrudRepository
11.2.2 PagingAndSortingRepository
11.2.3 JpaRepository
11.3 Hibernate Association Mappings
11.3.1 One-to-Many / Many-to-One
11.3.1.1 Owning Side and Bi-directionality
11.3.1.2 Eager vs Lazy loading
11.3.1.3 Cascading Operations
11.3.2 One-to-One
11.3.2.1 Implementation with Foreign key
11.3.2.2 Implementation with shared Primary key
11.3.3 Many-to-Many
11.4 Create records using Spring Boot and Hibernate
1.5 Read Records Using Spring Boot and Hibernate
11.6 Update records using Spring Boot and Hibernate
11.7 Delete records using Spring Boot and Hibernate
11.8 Summary
11.9 Solutions/ Answer to Check Your Progress
11.10 References/Further Reading

11.0 INTRODUCTION

Nowadays, there are varieties of data stores such as relational databases, NoSQL
databases like MongoDB, Casandraetc, Big Data solutions such as Hadoop etc.
Different storage technologies have different configurations, different methods and
different API's to fetch the data.
Spring Data simplifies and makes homogeneous data access technologies for
relational and non-relational databases, cloud-based data services and map-reduce
frameworks. Spring Data provides an abstraction that allows us to connect in the same
way to relational databases and NoSQL databases. Thus, switching can be done
effortlessly between data stores.
Spring Data JPA is one of the many sub-projects of Spring Datathat focuses on
simplification of the data access for relational data stores. It is not a JPA provider;
instead, it wraps the JPA provider and adds its own features like a no-code
implementation of the repository pattern. Hibernate is the default JPA provider into
Spring Data JPA. Spring Data JPA is very flexible, and other providers can also be
configured as JPA providers. Spring Data JPA provides a complete abstraction over
the DAO layer into the project.
The actual strength of Spring Data JPA lies in the repository abstraction. The
repository abstraction enables us to write the business logic code on a higher
abstraction level. Developers do not need to worry about DAO layer
implementations;instead they just need to learn Spring Data repository interfaces.
Crud Application Using Spring Data provides an implementation for these repository interfaces out-of-the-
Spring Boot and Hibernate box.
The Hibernate mappings are one of the key features of Hibernate. Association in
Hibernate tells the relationship between the objects of POJO classes, i.e. how the
entities are related to each other. The established relationship can be either
unidirectional or bidirectional. The supported relationships are similar to the database
relationships such as One-to-One, Many-to-Many, Many-to-One/One-to-Many.

11.1 OBJECTIVES

After going through this unit, you will be able to:


• describe Spring Data Repository such as CrudRepository,
PagingAndSortingRepository and JpaRepository,
• elaborate Hibernate association mappings,
• describe Hibernate Performance optimization via Eager and Lazy loading,
• demonstrate Hibernate Cascading and its impact,
• create records using Spring Data JPA,
• get records using Spring Data JPA,
• update record using Spring Data JPA, and
• delete record using Spring Data JPA

11.2 SPRING DATA REPOSITORY

The previous unit gave us the overview of Spring Data JPA. This section explains the
Spring Data Repository to create the persistence layer into the Spring Boot
application.
The Spring Data repository aims to reduce the boilerplate code required to implement
the DAO layer into a project for various persistence stores. Spring Data repository has
different interfaces, each having different functionality. Thefollowing interfaces in the
Spring Data repository have been explained.
• CrudRepository
• PagingAndSortingRepository
• JpaRepository
JpaRepository extends PagingAndSortingRepository interface, which extends
CrudRepository. Thus, JpaRepository contains all API of CrudRepositoty and
PagingAndSortingRepository. The persistent layer can extend any of the above
interfaces based on required APIs. The implementation of persistent layers is very
easy and is shown asan example.

@Entity
publicclass Book
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
privateintid;

private String title;


// getter setter
}
2
Following Repository provides a simple operation – find a Book based on its title. Spring Boot and Hibernate
(ORM)
@Repository
publicinterfaceBookRepositoryextendsCrudRepository<Book, Long>
{
publicBook findByTitle(String bookTitle);
}

The Spring Data Repository will auto-generate the implementation based on the
method name. Supported keywords inside method name can be found at -
https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.query-
methods.query-creation

11.2.1 CrudRepository

This interface provides all basic CRUD operation related APIs. The methods provided
in CrudRepository are shown in the code.
publicinterfaceCrudRepository<T, ID>extends Repository<T, ID>
{

<S extends T> S save(S entity);

<S extends T>Iterable<S>saveAll(Iterable<S>entities);

Optional<T>findById(ID id);

booleanexistsById(IDid);

Iterable<T>findAll();

Iterable<T>findAllById(Iterable<ID>ids);

long count();

voiddeleteById(ID id);

void delete(T entity);

voiddeleteAll(Iterable<? extends T>entities);

voiddeleteAll();
}

• save(…) - Saves a given entity.


• saveAll(…) - Saves all given entities.
• findById(…) - Retrieves an entity by its id.
• existsById(…) - Returns whether an entity with the given id exists.
• findAll(…) - Returns all instances of the type.
• findAllById(…) - Returns all instances of the type with the given IDs
• count(…) - Returns the number of entities available.
• deleteById(…) - Deletes the entity with the given id.
• delete(…) - Deletes a given entity.
• deleteAll(…) - Deletes the given entities.
• deleteAll() - Deletes all entities managed by the repository.

3
Crud Application Using 11.2.2 PagingAndSortingRepository
Spring Boot and Hibernate
PagingAndSortingRepository interface extends CrudRepository interface. It provides
the paging and sorting feature apart from CRUD feature. The methods in the interface
are shown in the code.
publicinterfacePagingAndSortingRepository<T, ID>extendsCrudRepository<T, ID>
{
Iterable<T>findAll(Sort sort);

Page<T>findAll(Pageablepageable);
}

• findAll(Sort sort) - Returns all entities sorted by the given options.


• findAll(Pageablepageable) - Returns a page of entities meeting the paging
restriction provided in the pageable object.

11.2.3 JpaRepository

JpaRepository extends PagingAndSortingRepository interface, which extends


CrudRepository. Thus, JpaRepository contains all API of CrudRepositoty and
PagingAndSortingRepository. The methods available in JpaRepository are shown in
the code.

publicinterfaceJpaRepository<T, ID>extendsPagingAndSortingRepository<T, ID>,


QueryByExampleExecutor<T>
{

@Override
List<T>findAll();

@Override
List<T>findAll(Sort sort);

@Override
List<T>findAllById(Iterable<ID>ids);

@Override
<S extends T> List<S>saveAll(Iterable<S>entities);

void flush();

<S extends T> S saveAndFlush(S entity);

voiddeleteInBatch(Iterable<T>entities);

voiddeleteAllInBatch();

T getOne(ID id);

@Override
<S extends T> List<S>findAll(Example<S>example);

@Override
<S extends T> List<S>findAll(Example<S>example, Sort sort);
}

4
Check Your Progress 1: Spring Boot and Hibernate
(ORM)
1) What is the relationship between JPA, Hibernate and Spring data JPA?

2) What is Spring Data?

3) What is the difference between CrudRepository and JpaRepository? Which


canextend and when?

11.3 HIBERNATE ASSOCIATION MAPPINGS

The previous unit has explained that hibernate can identify POJO classes as persistent
only when they are annotated with certain annotations. While making the POJO
classes as persistent entities using JPA annotations, we may face situations where two
entities can be related and must be referenced from each other, either uni-directional
or bi-directional. Association mappings are one of the key features of JPA
and Hibernate. That establishes the relationship between two database tables as
attributes in your model and allows you to easily navigate the association in your
model and JPQL or criteria queries.
When only one pair of entities contains a reference to the other, the association
is unidirectional. If the pair of entities contains a reference to each other, then it is
referred to as bi-directional. Entities can contain references to other entities, either
directly as an embedded property or field or indirectly via a collection of some sort
(arrays, sets, lists, etc.). There is no impact of unidirectional or bidirectional
association on database mapping. Foreign Key Relationships are used to represent
the associations in the underlying tables.
JPA and Hibernate have the same association as you are aware of relational databases.
The followings are the association that will be described in subsequent sections.
• one-to-many/many-to-one
• one-to-one
• many-to-many

5
Crud Application Using 11.3.1 One-to-Many / Many-to-One
Spring Boot and Hibernate
One-to-Many and Many-to-One relationships are the opposite sides of the same coin
and closely related. One-to-Many mapping is described as one row in a table and is
mapped to multiple rows in another table.
For the illustration of the One-to-Many relationship, the Teacher and their Courses
will be taken. A teacher can give multiple courses but a course which is given by only
one teacher is an example of one-to-many relationship. While another perspective,
many courses are given by a teacher, is an example of the many-to-one relationship.
Before diving into details of how to map this relationship, let’s create the entities.

@Entity
publicclass Teacher
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}

@Entity
publicclass Course
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
privateintid;
private String title;
}

Now, the Teacher class should include a list of courses, and mapping will be required
to map this relationship into the database. This will be annotated with a @OnetoMany
annotation.

@Entity
publicclass Teacher
{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToMany(cascade = CascadeType.ALL)
private List<Course>courses;
}

With the above configuration, Hibernate uses an association table to map the
relationship. With the above configuration, three tables named teacher, course and
teacher_courses will be created. But, definitely, we are not looking for such mapping.
In order to avoid the third table teacher_courses, @JoinColumn annotation is used to
specify the foreign key column.

6
@Entity Spring Boot and Hibernate
publicclass Teacher (ORM)
{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "teacher_id", referencedColumnName = "id")
private List<Course>courses;
}
The tables created into the database and save() operation on teacher object will result
in the following into the database (as shown in Figure 11.1, 11.2 and 11.3):

Figure11.1: Hibernate Created Tables

Figure11.2: Hibernate Created Records Into teacher Table

Figure11.3: Hibernate Created Records Into course Table

11.3.1.1 Owning Side and Bi-directionality

The previous example has defined the Teacher class as the owning side of the One-to-
Many relationship. This is because the Teacher class defines the join column between
the two tables. The Course is called the referencing side in the relationship.
Course class can be made as to the owning side of the relationship by mapping the
Teacher field with @ManytoOne in the course class instead.
@Entity
publicclass Teacher
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
@Entity
publicclassCourse
{
@Id
7
Crud Application Using @GeneratedValue(strategy = GenerationType.IDENTITY)
Spring Boot and Hibernate privateintid;
private String title;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "teacher_id", referencedColumnName = "id")
private Teacher teacher;
}

This time @ManytoOne annotation has been used instead of @OnetoMany


annotation. In the above example, it can be observed that the Teacher class does not
have a list of courses. Uni-directional relationship has been used here; thus, only one
of the entities has reference to another entity. @ManytoOne will result similar to
@OnetoMany.
Note: It's a good practice to put the owning side of a relationship in the class/table
where the foreign key will be held.
According to best practice, the second version of code using @ManytoOneis better.
If you look at the second version of the code, the Teacher class does not offer to
access the list of courses. This can be achieved by the bidirectional relationship.
The following section explains the bi-directional one-to-many mapping between
teacher and courses with a complete example. The Spring Hibernate project structure
is shown in Figure 11.4 and the Source Code structure follows;

Figure11.4: Spring Hibernate Project Structure

Teacher.java
packagecom.ignou.hibernate.association.learning.entity;

@Entity
publicclass Teacher
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToMany(mappedBy = "teacher", cascade= CascadeType.ALL, fetch =

8
FetchType.EAGER)
Spring Boot and Hibernate
private List<Course>courses;
(ORM)
public Teacher() {}

public Teacher(String name)


{
super();
this.name = name;
}

public Long getId()


{
returnid;
}

publicvoidsetId(Long id)
{
this.id = id;
}

public String getName()


{
returnname;
}

publicvoidsetName(String name)
{
this.name = name;
}

public List<Course>getCourses()
{
returncourses;
}

publicvoidsetCourses(List<Course>courses)
{
this.courses = courses;
}

@Override
public String toString()
{
return"Teacher [id=" + id + ", name=" + name + ", courses=" + courses + "]";
}

The Teacher class has reference courses. Teacher and Course has a relationship as
one-to-many, and thus, it is annotated with @OnetoMany. @OnetoManyannotation
has an attribute mappedBy. Without mappedBy attribute, we would not have a two-
way relationship. The mappedBy attributes indicatesthe JPA that the field is already
mapped by another entity. It's mapped by the teacher field of the Course entity. Other
attributes such as cascade and fetch will be explained in the next section.
Course.java
packagecom.ignou.hibernate.association.learning.entity;

@Entity
publicclass Course
{
9
Crud Application Using @Id
Spring Boot and Hibernate @GeneratedValue(strategy = GenerationType.IDENTITY)
privateintid;
private String title;

@ManyToOne
@JoinColumn(name = "teacher_id", referencedColumnName = "id")
private Teacher teacher;

public Course()
{

}
public Course(String title)
{
this.title = title;
}
publicintgetId()
{
returnid;
}
publicvoidsetId(intid)
{
this.id = id;
}
public String getTitle()
{
returntitle;
}
publicvoidsetTitle(String title)
{
this.title = title;
}
public Teacher getTeacher()
{
returnteacher;
}
publicvoidsetTeacher(Teacher teacher)
{
this.teacher = teacher;
}
@Override
public String toString()
{
return"Course [id=" + id + ", title=" + title + "]";
}
}

Course class is having the reference of Teacher. @ManytoOne annotation is used


since the Course and Teacher are having many to one relationship. Course class is the
owning side since @JoinColumn is defined in this class.

TeacherRepository.java

packagecom.ignou.hibernate.association.learning.repository;

publicinterfaceTeacherRepositoryextendsCrudRepository<Teacher, Long>
{
// No code repository. Spring data JPA will provide the implementation.
}

10
CourseRepository.java Spring Boot and Hibernate
(ORM)
packagecom.ignou.hibernate.association.learning.repository;

publicinterfaceCourseRepositoryextendsCrudRepository<Course, Long>
{
// No code repository. Spring data JPA will provide the implementation.
}

SpringHibernateJpaApplication.java

packagecom.ignou.hibernate.association.learning;

@SpringBootApplication
publicclassSpringHibernateJpaApplicationimplementsCommandLineRunner
{
@Autowired
privateTeacherRepositoryteacherRepo;

publicstaticvoid main(String[] args)


{
SpringApplication.run(SpringHibernateJpaApplication.class, args);
}

@Override
publicvoidrun(String... args) throws Exception
{
Teacher t1 = new Teacher("Vijay Kumar");

Course c1 = new Course("Java");


Course c2 = new Course("Spring Boot");

List<Course>courseList = newArrayList<Course>();
courseList.add(c1);
courseList.add(c2);

t1.setCourses(courseList);
c1.setTeacher(t1);
c2.setTeacher(t1);

t1 = teacherRepo.save(t1);
Teacher t = teacherRepo.findById(t1.getId()).get();
System.out.println(t);

}
}

11.3.1.2 Eager vs Lazy loading

It is worth noting that a mapped relationship should not impact the software’s memory
by putting too many unnecessary entities. For example, consider that the Course is a
heavy object, i.e. having too many attributes. For some business logic, all Teacher
objects are loaded from the database. Business logic does not need to retrieve or use
courses in it but Course objects are still being loaded alongside the Teacher objects.
Such loading will degrade the performance of applications. Technically, this can be
solved by using the Data Transfer Object Design Pattern and
retrieving Teacher information without the courses.
JPA has considered all such problems ahead and made One-to-Many relationships
load lazily by default. Lazy loading means relationships will be loaded when it is
11
Crud Application Using actually needed. The execution of @OnetoMany relationship with the default fetch
Spring Boot and Hibernate type will issue two queries. First is for the Teacher object and the second for the
Course objects when it’s needed. The log of the query issued by Hibernate is as
follows.

2021-03-06 17:52:47.095 DEBUG 8124 --- [ restartedMain] org.hibernate.SQL : select


teacher0_.id as id1_1_0_, teacher0_.name as name2_1_0_ from teacher teacher0_ where
teacher0_.id=?
2021-03-06 17:52:47.096 TRACE 8124 --- [ restartedMain] o.h.type.descriptor.sql.BasicBinder :
binding parameter [1] as [BIGINT] - [1]
2021-03-06 17:52:47.104 TRACE 8124 --- [ restartedMain] o.h.type.descriptor.sql.BasicExtractor :
extracted value ([name2_1_0_] : [VARCHAR]) - [Vijay Kumar]
2021-03-06 17:52:47.111 TRACE 8124 --- [ restartedMain] org.hibernate.type.CollectionType :
Created collection wrapper: [com.ignou.hibernate.association.learning.entity.Teacher.courses#1]
2021-03-06 17:52:47.117 DEBUG 8124 --- [ restartedMain] org.hibernate.SQL : select
courses0_.teacher_id as teacher_3_0_0_, courses0_.id as id1_0_0_, courses0_.id as id1_0_1_,
courses0_.teacher_id as teacher_3_0_1_, courses0_.title as title2_0_1_ from course courses0_ where
courses0_.teacher_id=?

While the execution of @OnetoMany relationship with fetch type as Eager will issue
only one query, Log of the query issued by Hibernate is as follows.

2021-03-06 18:28:11.107 DEBUG 15728 --- [ restartedMain] org.hibernate.SQL : select


teacher0_.id as id1_1_0_, teacher0_.name as name2_1_0_, courses1_.teacher_id as teacher_3_0_1_,
courses1_.id as id1_0_1_, courses1_.id as id1_0_2_, courses1_.teacher_id as teacher_3_0_2_,
courses1_.title as title2_0_2_ from teacher teacher0_ left outer join course courses1_ on
teacher0_.id=courses1_.teacher_id where teacher0_.id=?
2021-03-06 18:28:11.107 TRACE 15728 --- [ restartedMain] o.h.type.descriptor.sql.BasicBinder :
binding parameter [1] as [BIGINT] - [1]

Many-to-One relationships are eager by default.A eager relationship means all


related entities are loaded at the same time. The default behavior of fetch type can be
changed with fetch attribute as shown below-

@OneToMany(mappedBy = "teacher", cascade= CascadeType.ALL, fetch =


FetchType.EAGER)
private List<Course>courses;

@ManyToOne(fetch = FetchType.LAZY)
private Teacher teacher;

11.3.1.3 Cascading Operations

JPA operations affect the only entity on which it has been performed. These
operations will not affect the other entities that are related to it. For example, In case
of Person-Address relationship, the Address entity doesn’t have any meaning of its
own without a Person entity. Thus, on delete of Person entity, Address entity should
also get deleted.
Cascading is about JPA actions involving one entity propagating to other entities via
an association. JPA provides javax.persistence.CascadeType enumerated types that
define the cascade operations. These cascading operations can be defined with any
type of mapping i.e. One-to-One, One-to-Many, Many-to-One, Many-to-Many. JPA
provides the following cascade type to perform cascading operations.

12
Spring Boot and Hibernate
(ORM)
Cascade Type Description
ALL CascadeType.ALL propagates all operations including hibernate
specific from a parent to a child entity.
PERSIST CascadeType.PERSIST propagates the save() or persist() operation to
the related entities.
MERGE CascadeType.MERGE propagates only the merge() operation to the
related entities.
REFRESH CascadeType.REFRESH propagates only the refresh() operation to the
related entities.
REMOVE CascadeType.REMOVE removes all related entities association when
the owning entity is deleted.
DETACH CascadeType.DETACH detaches all related entities if owning entity is
detached.

Hibernate Cascade Type

Hibernate provides three additional Cascade Types along with provided by JPA.
Hibernate provides org.hibernate.annotations.CascadeTypeenumerated types that
define the cascade operations.

• CascadeType.REPLICATE
• CascadeType.SAVE_UPDATE
• CascadeType.Lock

Clear understanding of One-to-Many/Many-to-One association, as explained above,


will help you to understand other associations. The following section will explain the
other association as bidirectional with example.

11.3.2 One-to-One

One-to-One mapping is described as one row in a table mapped to only one row in
another table.
For the illustration of One-to-One relationship, The Student and the Address have
been taken.

11.3.2.1 Implementation with Foreign key

ER diagram of foreign key based one-to-one mapping is shown in Figure 11.5. The
address_id column in Student is the foreign key to the address.

Figure 11.5: ER Diagram For One-to-One Mapping With Foreign Key

@Entity
publicclass Student
{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
13
Crud Application Using private Long id;
Spring Boot and Hibernate
private String name;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name="address_id", referencedColumnName = "id")
private Address address;

// getter setter
}

The Student and the Address has a one-to-one relationship. Entity Student comprises
another entity Address, and it is annotated with @OnetoOne annotation. Check the
cascade attribute into the annotation. Student entity is the owner, and thus, it has
@JoinColumn annotation on Address entity. @JoinColumn is to configure the name
of the column in the Student table that maps to the primary key in the address table. If
the name attribute is not provided in @JoinColumn, Hibernate will follow some rules
to select the default name of the column.
@Entity
publicclass Address
{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
privateintid;
private String street;
private String state;
private String pincode;
private String country;
@OneToOne(mappedBy = "address")
private Student student;

// getter setter

The Address entity is having @OneToOne annotation on another entity Student with
attribute mappedBy. The mappedBy attribute is used since the Address is non-owning.
Note that on both entities @OneToOne annotations are used since its bidirectional.

11.3.2.2 Implementation with shared Primary key

In this strategy, instead of creating a new column address_id, we'll mark the
primary key column (student_id) of the address table as the foreign key to
the student table. ER diagram is shown in Figure 11.6. This strategy optimizes the
storage space.

Figure 11.6: ER Diagram For One-to-One Mapping With Shared Primary Key

14
Spring Boot and Hibernate
(ORM)
@Entity
publicclass Student
{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToOne(mappedBy = "student", cascade = CascadeType.ALL)


@PrimaryKeyJoinColumn
private Address address;

// getter setter
}

The @PrimaryKeyJoinColumnannotation indicates that the primary key of Student


entity is used as the foreign key value for the associated Address entity. The
mappedBy attribute is used here because the foreign key is now present in the address
table.
@Entity

publicclass Address

@Id

@Column(name ="student_id")

privateintid;

private String street;

private String state;

private String pincode;

private String country;

@OneToOne

@MapsId

@JoinColumn(name="student_id")

private Student student;

// getter setter

15
Crud Application Using The identifier of the Address entity is still having @Id annotation but it no longer uses
Spring Boot and Hibernate @GeneratedValue annotation. Instead it references the student_id column. The
@MapsIdindicates that the primary key values will be copied from the Student entity.

11.3.3 Many-to-Many

Many-to-Many mapping is described as many rows in a table mapped to many rows


in another table.

For the illustration of Many-to-Many relationship, Book and the Author have been
taken. A book may be written by multiple writers and a writer will write multiple
books. Thus, the Book and Author relationship is many-to-many and is shown as an
ER diagram in Figure 11.7.

Figure11.7: ER Diagram For Many-to-Many Relationship

The JPA implementation for many-to-many mapping for Book as owning side is
shown below:
@Entity
@Table(name = "books")
publicclass Book
{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

//Other fields

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "book_author" , joinColumns = @JoinColumn(name =
"book_id" ), inverseJoinColumns = @JoinColumn(name = "author_id"))
private List<Author>authors;

//getter setter

@JoinTable and @JoinColumnaren’t mandatory annotations. These are used to


customize the name of the table and column name. @ManyToManyannotation has
been used for many-to-many mapping. @JoinTableannotationhas a name attribute
which defines the name of the joining table. It also requires the foreign keys with
the @JoinColumn annotations. The joinColumn attribute will connect to the owner
side of the relationship, and the inverseJoinColumn to the other side.
@Entity
@Table(name = "authors")
publicclass Author
16
{
Spring Boot and Hibernate
@Id
(ORM)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "author_name")
@Size(max = 100)
@NotNull
private String name;

private Integer rating;

@ManyToMany(mappedBy = "authors", cascade = CascadeType.ALL)


private List<Book>books;
}

Check Your Progress 2:

1) Explain One-to-Many association in Hibernate. Write an example for uni-


directional one-to-many mapping.

2) Explain Eager and Lazy loading in Hibernate. How does it improve the
performance of hibernate applications?

3) What are the different Cascade types supported by JPA?

11.4 CREATE RECORDS USING SPRING BOOT


AND HIBERNATE

17
Crud Application Using The previous unit explained Spring Data JPA and hibernate as the default provider
Spring Boot and Hibernate for Spring Data JPA. This unit has elaborated on Spring Data Repository and
hibernate association mapping. This section provides the complete Rest Application to
create records using Spring Boot and Hibernate by using all the explained concepts.
The example considers the many-to-many relationship between Book and Author.
Many books can be written by an Author and many authors can write a book. The
same example will be considered for CRUD operation.The required tools and
software are as follows:
• Eclipse IDE
• Maven
• Spring Boot
• Hibernate
• Mysql
• Postman
Visit Spring Initializr (https://start.spring.io) in order to generate the spring project
(shown in Figure 11.8). Add the required dependencies and export the project into
eclipse as maven project. Modify the data source properties into application.properties
file and do some hands-on.

Figure11.8: SpringBoot Project Setup Using Spring Initializr

The source code structure is shown below.

18
Spring Boot and Hibernate
(ORM)

Figure 11.9: SpingBootAnd Hibernate CRUD Applicatication Folder Structure

SpringbootHibernateCrudApplication.java – This is the main class of Spring Boot


application. To create the records at the time of application start, it implements
CommandLineRunner interface and creates records using book repository.
@SpringBootApplication
@EnableJpaRepositories
publicclassSpringbootHibernateCrudApplicationimplementsCommandLineRunner
{
@Autowired
privateBookRepositorybookRepository;

publicstaticvoid main(String[] args)


{
SpringApplication.run(SpringbootHibernateCrudApplication.class, args);
}

@Override
publicvoid run(String... args) throws Exception
{
Book b1 = new Book("Java In Action", "ISBN-001");
List<Book>bookList = newArrayList<Book>();
bookList.add(b1);

Author au1 = new Author("O. P. Sharma");


Author au2 = new Author("K L Mishra");

List<Author>authorList = newArrayList<Author>();
authorList.add(au1);
authorList.add(au2);

b1.setAuthors(authorList);
au1.setBooks(bookList);
au2.setBooks(bookList);

bookRepository.save(b1);

19
Crud Application Using Book b2 = new Book("Java 8 In Action", "ISBN-002");
Spring Boot and Hibernate List<Book>bookList2 = newArrayList<Book>();
bookList2.add(b2);

Author au3 = new Author("R K Singh");


Author au4 = new Author("A K Sharma");

List<Author>authorList2 = newArrayList<Author>();
authorList2.add(au3);
authorList2.add(au4);

b2.setAuthors(authorList2);
au3.setBooks(bookList2);
au4.setBooks(bookList2);

bookRepository.save(b2);

}
}

BookController.java – The BookController is responsible to handle the request from


client for the URL pattern /books/*. The controller is having a method
createBookRecord which is annotated with @PostMapping which means it will
accept the post request for the URL pattern /books with the request body having a
valid Book entity json.

@RestController
@RequestMapping("/books")
publicclassBookController
{
@Autowired
privateBookRepositorybookRepository;
@Autowired
privateAuthorRepositoryauthorRepository;
@PostMapping
public Book createBookRecord(@Valid@RequestBody Book b)
{
returnbookRepository.save(b);
}
}

In the example, there are two entities Book and Author, having a many-to-many
relationship. Entities with bidirectional many-to-many associations are shown in the
code.
Book.java

@Entity
@Table(name = "books")
publicclass Book
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)

20
private Long id;
Spring Boot and Hibernate
(ORM)
@NotNull
@Size(max=75)
private String title;

@NotNull
@Size(max = 100)
private String isbn;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(joinColumns = @JoinColumn(name = "book_id" ), inverseJoinColumns
= @JoinColumn(name = "author_id"))
private List<Author>authors;

public Book() {}

public Book(@NotNull@Size(max = 75) String title, @NotNull@Size(max = 100)


String isbn)
{
this.title = title;
this.isbn = isbn;
}

// getter setter

@Override
public String toString()
{
return"Book [id=" + id + ", title=" + title + ", isbn=" + isbn + ", authors=" + authors
+ "]";
}
}

Author.java

@Entity
@Table(name = "authors")
publicclass Author
{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "author_name")
@Size(max = 100)
@NotNull
private String name;

private Integer rating;

@ManyToMany(mappedBy = "authors", cascade = CascadeType.ALL)


@JsonIgnore
private List<Book>books;

public Author() {}

public Author(@Size(max = 100) @NotNull String name)


{

21
Crud Application Using super();
Spring Boot and Hibernate this.name = name;
}

// getter setter

@Override
public String toString()
{
return"Author [id=" + id + ", name=" + name + ", rating=" + rating + "]";
}
}

BookRepository.java – BookRepository provides the methods to interact with


databases to perform CRUD operation. BookRepository extends CrudRepository
interface. To create the records, the default save() method of CrudRepository will be
used.

@Repository
publicinterfaceBookRepositoryextendsCrudRepository<Book, Long>
{
// No implementation is required.
}

application.properties

# DATASOURCE (DataSourceAutoConfiguration&DataSourceProperties)
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
&useLegacyDatetimeCode=false
spring.datasource.username=root
spring.datasource.password=root

# Hibernate
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernateddl auto (create, create-drop, validate, update)


spring.jpa.hibernate.ddl-auto = create

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Start the rest application by executing SpringbootHibernateCrudApplication.java.


Use the postman to send the post request for book record creation. Sample post
request with postman for book record creation is shown in Figure 11.10. Check the
response status as 200 OK and response body with generated id for new record.

22
Spring Boot and Hibernate
(ORM)

Figure 11.10: Create Record Using SpringBoot and Hibernate

11.5 READ RECORDS USING SPRING BOOT AND


HIBERNATE
This section explains how to read the records and search the records using Spring
Boot and Spring Data JPA with Hibernate. The previous section example will be used
to explain the read operation. We will just add the new feature into the existing rest
application. Add the new features into BookRepository and BookController as shown
below in order to test the read records operation.
BookRepository.java
@Repository
publicinterfaceBookRepositoryextendsCrudRepository<Book, Long>
{
public List<Book>findByTitleContaining(String pattern); // 1

public List<Book>findByTitleContaininsIgnoreCase(String pattern); //2

public List<Book>findByTitleLike(String pattern); // 3

@Query(“Select b from Book b where b.title like %:pattern%”)


public List<Book>findByTitle(String pattern); // 4
}

BookRepository extends the CrudRepository interface, which provides the methods to


read all records, specific record by id etc. Here we have added three new methods in
order to provide search features. All three methods generate the same like queries, but
there are some differences.
1. Query methods using Containing, Contains, and IsContaining generate the
like query. For example, the query method findByTitleContaining(String
pattern) generates the following sql query.

SELECT * FROM books WHERE title LIKE '%<pattern>%'

2. The findByTitleContainsIgnoreCase(String pattern) is similar to


findByTitleContaining(String pattern) but with case insensitive.

23
Crud Application Using 3. Spring Data JPA also provides a Like keyword, but it behaves differently. An
Spring Boot and Hibernate example to call the findByTitle(…) is shown inBookRepository code in the
next paragraph.
4. Sometimes we need to create queries that are too complicated for Query
Methods or would result in absurdly long method names. In those cases, we
can use the @Query annotation to query our database.
• Named Parameters (:name) – Query parameters can be passed as
named parameters into the query. Check the example in the
aboveBookRepository.
• Ordinal Parameters (?index) - JPQL also supports ordinal parameters,
whose form is ?index. An example of ordinal parameters is as
“Select b from Book b where b.title like %?1%”

24
BookController.java Spring Boot and Hibernate
(ORM)
@RestController

@RequestMapping("/books")

publicclassBookController

@Autowired

privateBookRepositorybookRepository;

@GetMapping

publicIterable<Book>getBooks()

returnbookRepository.findAll();

@GetMapping("/search-by-method-containing")

public List<Book>searchByMethod(@RequestParam(value = "q", required = true)


String pattern)

returnbookRepository.findByTitleContaining(pattern);

@GetMapping("/search-by-method-like")

public List<Book>searchByMethodLike(@RequestParam(value = "q", required =


true) String pattern)

returnbookRepository.findByTitleLike("%"+pattern+"%");

@GetMapping("/search-by-query")

public List<Book>searchByQuery(@RequestParam(value = "q", required = true)


String pattern)

returnbookRepository.findByTitle(pattern);

}
}

The BookController provides the following GET endpoints to get all books and
search the book with title keywords.

25
Crud Application Using • http://localhost:8080/books - Returns all the books with its authors.
Spring Boot and Hibernate • http://localhost:8080/search-by-method-containing?q=Java – Returns all the
books with title containing Java
• http://localhost:8080/search-by-method-like?q=Java – Returns all the books
with title containing Java.
• http://localhost:8080/search-by-query?q=Java – Returns all the books with
title containing Java

11.6 UPDATE RECORDS USING SPRING BOOT


AND HIBERNATE

To update the record/records, CrudRepository provides save(…) and saveAll(…)


methods. If the entity has an identifier, JPA will perform update operation instead of
save operation. Add the following into the BookController.java in order to provide the
update feature to the rest application.

BookController.java

@RestController
@RequestMapping("/books")
publicclassBookController
{

@Autowired
privateBookRepositorybookRepository;

@PutMapping
public Book updateBook(@Valid@RequestBody Book b)
{
returnbookRepository.save(b);
}

To test the update feature, use the postman and use the PUT method with a valid Book
record into the request body. Following request, update the authors of the given book
with id 3 (as shown in Figure 11.11).

Figure 11.11: Update Record Using SpringBoot and Hibernate

26
11.7 DELETE RECORDS USING SPRING BOOT Spring Boot and Hibernate
(ORM)
AND HIBERNATE

To delete a record or all records, CrudRepository provides deleteById(…), delete(…)


and deleteAll(…) methods. Add the following code into the BookController.java in
order to provide the delete feature into the rest application.

@RestController
@RequestMapping("/books")
publicclassBookController
{

@Autowired
privateBookRepositorybookRepository;

@DeleteMapping("/{bookId}")
@ResponseStatus(value = HttpStatus.OK)
publicvoiddeleteBook(@PathVariable(value="bookId", required=true) Long bookId)
{
bookRepository.deleteById(bookId);
}
}

BookController.java

The delete operation does not return any body response. It just returns the response
status as 200 OK on successful deletion. Use the postman to issue the DELETE
request, as shown into the screenshot (Figure 11.12). Thefollowing is the delete
request to delete the book with id as 2. The response status is 200 OK, and the
response body is empty as expected.

Figure 11.12: Delete Record Using SpringBoot and Hibernate

27
Crud Application Using
Spring Boot and Hibernate

Check Your Progress 3

1) Explain the annotation @OneToMany and its attributes :


@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="EMPLOYEE_ID")
private Set<AccountEntity> accounts;

2) How does Spring Data framework derive queries from method names?

3) Explain the following User repository definition.


@Repository
public interface UserRepository extends Repository<User, Long> {
List<User>findByEmailAddressAndLastname(String emailAddress, String
lastname);
}

4) Explain the following repository definition.


@Repository
publicinterfaceBookRepositoryextendsCrudRepository<Book, Long>
{
public List<Book>findByTitleContaining(String pattern); // 1
public List<Book>findByTitleContaininsIgnoreCase(String pattern); //2
public List<Book>findByTitleLike(String pattern); // 3
@Query(“Select b from Book b where b.title like %:pattern%”)
public List<Book>findByTitle(String pattern); // 4

28
Spring Boot and Hibernate
(ORM)

11.8 SUMMARY

This unit has explained Spring Data Repository with a complete example using other
hibernate association concepts. For better understanding, start coding by using the
examples explained in this unit. The important points are as following:
• The goal of Spring Data repository abstraction is to significantly reduce the
amount of boilerplate code required to implement data access layers for
various persistence stores.
• CrudRepository, PagingAndSortingRepository and JpaRepositoryhave been
explained with all available methods.
• Association mappings are one of the key features of JPA and Hibernate. That
establishes the relationship between two database tables as attributes in your
model and allows you to navigate the association easily in your model and
JPQL or criteria queries
• JPA has considered the related entity loading overhead problems ahead and
made One-to-Many relationships load lazily by default.
• The fetch type for Many-to-One relationship is eager by default.
• Cascading is about JPA actions involving one entity propagating to other
entities via an association. JPA provides javax.persistence.CascadeType
enumerated types that define the cascade operations. JPA provides the
cascade types as ALL, PERSIST, MERGE, REFRESH, REMOVE,
DETACH.
• Query methods using Containing, Contains, and IsContaining generate the
like query. For example, query method findByTitleContaining(String pattern)
generates the sql query as SELECT * FROM books WHERE title LIKE
'%<pattern>%'
• Query parameters as Named Parameters (:name) and Ordinal Parameters
(?index)

11.9 SOLUTIONS/ ANSWER TO CHECK YOUR


PROGRESS

Check Your Progress 1


1) Java Persistence API (JPA) is a specification that defines APIs for object-
relational mappings and management of persistent objects. JPA is a set of
interfaces that can be used to implement the persistence layer. JPA itself
doesn’t provide any implementation classes.
Hibernate is an implementation of JPA.
Spring Data JPA is one of the many sub-projects of Spring Data that focuses
on simplification of the data access for relational data stores. Spring Data JPA
is not a JPA provider; instead it wraps the JPA provider and adds its own

29
Crud Application Using features like a no-code implementation of the repository pattern. Spring Data
Spring Boot and Hibernate JPA uses Hibernate as the default JPA provider.

2) There are varieties of data stores such as relational databases, NoSQL


databases like MongoDB, Casandraetc, Big Data solutions such as Hadoop
etc. Different storage technologies have different configurations, different
methods and different API's to fetch the data.
Spring Data aims at providing a homogeneous and consistent Spring-based
programming model to fetch data along with keeping the special traits of the
underlying data stores. Spring Data provides Abstractions (interfaces) that can
be used irrespective of the underlying data source.
public interface EmployeeRepository extends
CrudRepository<Employee, Long> {}
No implementation of EmployeeRepository is required in order to perform
insert, update, delete and retrieval of EMPLOYEE entities from the database.

3) CrudRepository provides all the typical Save, Update, Delete operations for
an entity while JpaRepository extends CrudRepository as well as Repository,
QueryByExampleExecutor and PagingAndSortingRepository interfaces.
So, if only CRUD operations are required to perform, select
CRUDRepository. Else, if one or more features out of Pagination, Batch
processing and flush operations are required, choose JPARepository.
Check Your Progress 2

1) One-to-Many and Many-to-One relationships are the opposite sides of the


same coin and closely related. One-to-Many mapping is described as one row
in a table mapped to multiple rows in another table.
For the illustration of the One-to-Many relationship, the Teacher and their
Courses will be taken. A teacher can give multiple courses, but a course is
given by only one teacher is an example of one-to-many relationship. While
another perspective, many courses are given by a teacher is an example of the
many-to-one relationship.
@Entity
publicclass Teacher
{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "teacher_id", referencedColumnName = "id")
private List<Course>courses;
}

@Entity
publicclass Course
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
privateintid;
private String title;
}

30
2) The difference between lazy and eager loading is described in the table. Spring Boot and Hibernate
(ORM)
S.No Key Lazy Eager
.
1 Fetching In Lazy loading, associated In Eager loading, data
strategy data loads only when we loading happens at the time
explicitly call getter or size of their parent is fetched
method.
2 Default ManyToMany and ManyToOne and OneToOne
Strategy in OneToMany associations associations used a lazy
ORM Layers used a lazy loading loading strategy by default.
strategy by default.
3 Loading It can be enabled by using It can be enabled by using
Configuration the annotation parameter : the annotation parameter :

fetch = FetchType.LAZY fetch = FetchType.EAGER


4 Performance Initial load time much Loading too much
smaller than Eager loading unnecessary data might
impact performance

Performance improvement can be explained with an example. Consider the


teacher and course as a one-to-many relationship. The Course is a heavy
object i.e. having too many attributes. For some business logic, all Teacher
objects are loaded from the database. Business logic does not need to retrieve
or use courses in it, but Course objects are still being loaded alongside the
Teacher objects.
Such loading will degrade the performance of applications. JPA has
considered all such problems ahead and made One-to-Many relationships
load lazily by default. Lazy loading means relationships will be loaded when
it is actually needed.

3) One of the main aspects of JPA is that it helps to propagate Parent to Child
relationships. This behavior is possible through CascadeTypes. The
CascadeTypes supported by JPA are:
Cascade Description
Type
ALL CascadeType.ALL propagates all operations, including hibernate
specific from a parent to a child entity.
PERSIST CascadeType.PERSIST propagates the save() or persist() operation
to the related entities.
MERGE CascadeType.MERGE propagates only the merge() operation to the
related entities.
REFRESH CascadeType.REFRESH propagates only the refresh() operation to
the related entities.
REMOVE CascadeType.REMOVE removes all related entities associations
when the owning entity is deleted.
DETACH CascadeType.DETACH detaches all related entities if the owning
entity is detached.

31
Crud Application Using Cascading is useful only for Parent - Child associations where the parent
Spring Boot and Hibernate entity state transitions cascade to the child entity. The cascade configuration
option accepts an array of CascadeTypes. The below example shows how to
add the refresh and merge operations in the cascade operations for a One-to-
Many relationship:
@OneToMany(cascade={CascadeType.REFRESH, CascadeType.MERGE},
fetch = FetchType.LAZY)
@JoinColumn(name="EMPLOYEE_ID")
private Set<AccountEntity> accounts;

Check Your Progress 3


1) One-to-Many mapping is described as one row in a table is mapped to
multiple rows in another table and Hibernate provides annotation
@OnetoMany. The attribute “cascade=CascadeType.ALL” means that any
change that happens to Employee Entity must cascade to all associated entities
(Accounts Entity in this case) also. This means that if you save an employee
into the database, then all associated accounts will also be saved into the
database. If an Employee is deleted, then all accounts associated with that
Employee will also be deleted. However, if we want to cascade only the save
operation but not the delete operation, we need to clearly specify it using
below code.
@OneToMany(cascade=CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name="EMPLOYEE_ID")
private Set<AccountEntity> accounts;

Now only when the save() or persist() methods are called using an employee
instance, the accounts will be persisted. If any other method is called on
session, its effect will not affect/cascade to the accounts entity.
2) Spring Data framework has an in-built query builder mechanism that derives
queries based on the method name. Method names are defined as 'find...By..',
'count...By...' etc. 'By' acts as the delimiter to identify the start of the criteria.
'And' and 'Or' are used to define multiple criteria. 'OrderBy' is used to identify
the order by criteria. Few examples of query methods are as follows:
• findByFirstname(String firstName): It derives the query to get the
list based on the first name.
• findByFirstnameAndLastname(String firstName, String
lastName): It derives the query to get the list based on first name and
last name
• findByFirstnameAndLastnameOrderByFirstnameAcs(String
firstName, string last): it derives the query to get the list based on
the first name and sorted by the first name in ascending order.

3) UserRepository extends the Repository marker interface. Marker interface


does not contain any method. Thus, UserRepository provides a single API to
find the list of users based on the email address and last name. The query
method:
List<User>findByEmailAddressAndLastname(String emailAddress,
String lastname) translates into the following query:
select u from User u where u.emailAddress = ?1 and u.lastname = ?2.
4) BookRepository extends the CrudRepository interface, which provides the
methods to read all records, specific record by id etc. All methods generate
the same queries, but there are some differences.
1. Query methods using Containing generates the following sql query.
SELECT * FROM books WHERE title LIKE '%<pattern>%'
32
2. The findByTitleContainsIgnoreCase(String pattern) is similar to Spring Boot and Hibernate
findByTitleContaining(String pattern) but with case insensitive. (ORM)
3. The findByTitleLike(String pattern) generates SELECT * FROM
books WHERE title LIKE '<pattern>'. JPA Like keyword behaves
differently. It can be noticed in the generated query that it does not
include wild char %. Thus, while calling this method, argument should
have wild char included.
4. Sometimes we need to create queries that are too complicated for Query
Methods or would result in absurdly long method names. In those
cases, we can use the @Query annotation to query our database. The
method findByTitile with @Query annotation is similar to the first
method.

11.10 REFERENCES/FURTHER READING

• Craig Walls, “Spring Boot in action” Manning Publications, 2016.


(https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)
• Christian Bauer, Gavin King, and Gary Gregory, “Java Persistence with
Hibernate”,Manning Publications, 2015.
• Ethan Marcotte, “Responsive Web Design”, Jeffrey Zeldman Publication,
2011(http://nadin.miem.edu.ru/images_2015/responsive-web-design-2nd-
edition.pdf)
• Tomcy John, “Hands-On Spring Security 5 for Reactive Applications”,Packt
Publishing,2018
• https://spring.io/projects/spring-data
• https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa
• https://github.com/spring-projects/spring-data-examples
• https://dzone.com/articles/magic-of-spring-data
• https://www.journaldev.com/17034/spring-data-jpa
• https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/associations.html
• https://www.baeldung.com/spring-data-rest-relationships

33
UNIT 12 SPRING SECURITY
CONFIGURATION
Structure

12.0 Introduction
12.1 Objective
12.2 Introduction to Web Securities
12.2.1 Introduction of Java Cryptography Architecture (JCA)
12.2.2 Introduction of Java Secure Socket Extension (JSSE)
12.3 Issues and Challenges of Web Security
12.4 Spring Security Overview
12.5 Java Based Configuration
12.6 Create Spring Initializer Class
12.7 Create Controller and View
12.8 Run Application
12.9 Summary
12.10 Solutions/Answers to Check Your Progress
12.11 References/Further Reading

12.0 INTRODUCTION

In unit 9, Spring Boot Application and a simple application without any security
considerations are described. This unit will describe security features like
authentication and authorization that create a secured Java Enterprise Application. The
following sections will explain JCA and JSSE to secure our data at various levels.
This unit will also describe how spring security simplifies the security implementation
as compared to non-spring projects.

12.1 OBJECTIVE

After going through this unit, you should be able to:

• secure the data using JCA,


• establish Secure communication between client and server using JSSE,
• explain common web application security vulnerabilities,
• perform Authentication (AuthN) and Authorization (AuthZ),
• describe building blocks of Spring Security, and
• develop the secured applications using spring security.

12.2 INTRODUCTION TO WEB SECURITIES

Security is one of the topmost concern for any application. It includes many aspects
such as sensitive data safety, robust website against hacking, sql injection, csrf etc. A
different set of tools are used for various aspects of application security. This section
describes how to secure sensitive information on backend applications, i.e. passwords
1
Web Security
in the database, critical records etc. With the emergence of cloud services, security has
become an indispensable requirement for sensitive information on every platform.

Encryption of data in-transit and at-rest


Data in-transit is data moving from/ through the internet or private network. Term
Data protection in transit is the protection of data while it is moving from network to
network or istransferred from a local storage device to a cloud storage device.
The term Data at-rest is data that is not moving from device to device or network to
networks such as data stored on a hard drive, laptop or archived/stored in some other
way. Data protection at rest aims to secure inactive data stored on any device or
network.
Safeguarding sensitive data both in-transit and at-rest is vital for modern enterprises
as attackers are persistently trying innovative ways to compromise systems and steal
data. Data can be exposed to many security threats, both in-transit and at-rest, which
requires safeguard against such threats. There are multiple approaches to protect data
in-transit and at-rest. Encryption plays a vital role in data protection and is a very
popular tool for securing data both in-transit and at-rest. Enterprises often encrypt
sensitive data prior to move and/or use encrypted connections such as HTTPS, SSL,
TLS, FTPS etc., to protect the data in transit. Enterprises can simply encrypt sensitive
data prior to storing them and/or choose to encrypt the storage drive itself.

12.2.1 INTRODUCTION OF JAVA CRYPTOGRAPHY


ARCHITECTURE (JCA)
Cryptography
Cryptography is the art and science of making a cryptosystem that is capable of
providing information security. Cryptography aims to provide the following:
• Secret Communication
• Authentic Information
• Store Sensitive Information
Cryptography Primitives
Cryptography primitives are simply the tools and techniques in Cryptography that can
be particularly used to provide a set of desired security services −
• Encryption
• Hash functions
• Message Authentication codes (MAC)
• Digital Signatures
Java Cryptography Architecture (JCA)
The Java Cryptography Architecture (JCA) is based on “provider” architecture. It is
a set of APIs’ to cryptography such as encryption, message digests, key generation
and management, digital signatures, certificates etc. It enables you to encrypt and
decrypt data in java, manage keys, sign and authenticate messages etc.
JCA provides some general-purpose classes and interfaces. JCA has “provider” based
architecture; thus actual functionality and implementation are provided by providers.
The encryption algorithm used for encryption and decryption in Cipher class depends
on the concrete provider used.
Core Classes and Interfaces
Following java packages has been defined into Java cryptography API.
• javax.crypto
• javax.crypto.spec
• javax.crypto.interfaces

2
Spring Security
• java.security Configuration
• java.security.cert
• java.security.spec
• java.security.interfaces
Above defines, packages contain many core classes and interfaces. Some of
thefrequently used ones are as follows:
• Provider
• Cipher
• MessageDigest
• Signature
• Mac
• KeyPairGenerator
• KeyGenerator
• KeyStore
The following sections will give you insights of some frequently used classes and its
feature.
Provider
JCA has a “provider” based architecture. Java SDK provides a default provider.
Default providers may not support the encryption algorithms you want to use. In order
to use a different provider instead of the default, Java Cryptography API provides a
method to set the desired provider. Cryptography provider can be set as below-
Security.addProvider(…)

Cipher
The Cipher (javax.crypto.Cipher) class is the core of JCA framework. This class
provides cryptographic cipher for encryption and decryption. Cipher’s getInstance
method provides cipher object for encryption and decryption. Method getInstance
expects the name of the requested transformation. A transformation can be any form
either "algorithm/mode/padding" or "algorithm".
Cipher instance can be created using getInstnace method as –

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Encryption/Decryption example using Cipher Class

package com.ignou;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
publicclassEncryptDecrypt
{
publicstaticbyte[] Encrypt(String secretKey, String plainText)
throwsGeneralSecurityException
{
byte[] keyBytes = secretKey.getBytes(Charset.forName("UTF-8"));
if (keyBytes.length != 16)
{
thrownewIllegalArgumentException("Allowed key size is 16");
}
IvParameterSpecparamSpec = newIvParameterSpec(newbyte[16]);
3
Web Security
SecretKeySpeckeySpec = newSecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);
byte[] cipherTextBytes = cipher.doFinal(plainText.getBytes(Charset.forName("UTF-8")));
returncipherTextBytes;
}
publicstaticbyte[] Decrypt(String key, byte[] cipherText) throwsGeneralSecurityException
{
byte[] keyBytes = key.getBytes(Charset.forName("UTF-8"));
if (keyBytes.length != 16)
{
thrownewIllegalArgumentException("Allowed key size is 16");
}
IvParameterSpecparamSpec = newIvParameterSpec(newbyte[16]);
SecretKeySpeckeySpec = newSecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
byte[] plainTextBytes = cipher.doFinal(cipherText);
returnplainTextBytes;
}
publicstaticvoidmain(String[] args)
{
try
{
String key = "ThisIsASecretKey";
String plainText = "Hello, Good Morning";
byte[] ciphertextbytes = Encrypt(key, plainText);
System.out.println("Cipher Text: " + Base64.getEncoder().encodeToString(ciphertextbytes));
byte[] plaintextbytes = Decrypt(key, ciphertextbytes);
String decryptedPlainText = newString(plaintextbytes, StandardCharsets.UTF_8);
System.out.println("Decrypted Plain Text: "+decryptedPlainText);
}
catch (GeneralSecurityException e)
{
e.printStackTrace();
}
}
}

Output: Program execution will provide the below output. As you can see by
encryption, you are getting encrypted text corresponding to plain text. This Cipher
text is used for confidentiality. This encrypted text has been decrypted to the plain text
using Cipher class in Decrypt mode.

Message Digest
Message digests are a secured one-way hash functions that take arbitrary-sized data
and output fixed-length hash value. A common solution to validate the encrypted data
on the way to you has not been modified is Message Digest. A message digest is a
hash value calculated from message data. Steps to send encrypted data with message
digest and validation of encrypted data is as-
• Calculate the message digest from data before encryption
• Encrypt both data and message digest and send across the wire
• Once encrypted data is received, decrypt it to get the message and message
digest

4
Spring Security
• Calculate message digest for the received message and compare it with the Configuration
received message digest
• If the comparison evaluates to true, there is a high probability (but not a 100%
guarantee) that the data was not modified.
Java provides a class, named MessageDigest which belongs to the package
java.security, to create a message digest for message data. This class supports
algorithms such as SHA-1, SHA-256, SHA-384, SHA-512, MD5 algorithms to
convert an arbitrary-length message to a fixed-length message digest. Sample code to
generate message digest for multiple blocks of data is as –
MessageDigest md = MessageDigest.getInstance("SHA-256");

byte[] msg1 = "This is msg1".getBytes("UTF-8");


md.update(msg1);
byte[] msg2 = "This is msg2".getBytes("UTF-8");
md.update(msg2);

// Call digest method to get the MD


byte[] digest = md.digest();

Mac
The term MAC stands for Message Authentication Code. The integrity of information
transmitted over an unsecured channel can be validated using MAC. A MAC is like a
Message Digest but uses an additional key to encrypt the message digest. Thus, A
MAC is a message digest encrypted with a secret key. MAC from a message can be
created using Java Mac Class. To verify the MAC of a message, it requires the key
along with original data. Hence, a MAC is a more protected way to guard a block of
data from modification than a message digest. Java code to calculate the MAC of a
message data is as –
packagecom.ignou;
importjava.util.Base64;
importjavax.crypto.Mac;
importjavax.crypto.spec.SecretKeySpec;
publicclass MAC
{
publicstaticvoidmain(String[] args) throws Exception
{
Mac mac = Mac.getInstance("HmacSHA256");
byte[] keyBytes = newbyte[]{'T','h','i','s','I','s','A','S','e' ,'c','r','e','t','K','e','y'};
String algo = "RawBytes";
SecretKeySpec key = newSecretKeySpec(keyBytes,algo);
mac.init(key); // MAC instance initialized with key

byte[] msg1 = "This is msg1".getBytes("UTF-8");


mac.update(msg1); // Update that data for which mac should be calculated
byte[] msg2 = "This is msg2".getBytes("UTF-8");
mac.update(msg2); // Update that data for which mac should be calculated
byte[] macBytes = mac.doFinal(); // Calculate MAC for given blocks of data
System.out.println("Message Authentication Code(MAC): " +
Base64.getEncoder().encodeToString(macBytes));
}
}
Execution of the above program will give the MAC. MAC helps to validate the integrity of the
received msg. The person who receives and knows the key, he/she can validate the integrity of
msg.
Output:

5
Web Security
Signature
A digital signature is a mathematical technique used to validate the authenticity and
integrity of a message or digital document. Digital signatures provide the added
assurances of evidence of origin, identity and status of an electronic document or
message. It also ensures the non-repudiation, i.e. the author of the message can't later
deny that they were the source. Digital Signatures are based on public-key
cryptography. The signer uses his private key to create the signature and signature can
be authenticated only by the signer public key.
The Signature (java.security.Signature) class is used to create Signature instance in
java. A digital signature is an encrypted message digest with the private key of the
signing authority. The signing authority may be the device, person or organization that
is to sign the data.
To create a Signature instance, you call the Signature.getInstance(...) method.
Signature instance creation is shown below:

Signature signature = Signature.getInstance("SHA256WithDSA");

Signature creation and verification example

package com.ignou;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
public class CreateAndVerifySignature
{
public static void main(String[] args) throws Exception
{
KeyPairGeneratorkeyPairGen = KeyPairGenerator.getInstance("DSA");
// Initializing the key pair generator
keyPairGen.initialize(2048);
// Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();
// Get the private key from the key pair
PrivateKeyprivateKey = pair.getPrivate();
// Get the public key from the key pair
PublicKeypublicKey = pair.getPublic();
// Create signature instance
Signature sign = Signature.getInstance("SHA256withDSA");
// Initialize with private key
sign.initSign(privateKey);
// Data that needs to be signed
byte[] bytes = "This is my digital signed data".getBytes();
// Update signature instance with data to be signed
sign.update(bytes);
// Create the signature
byte[] signature = sign.sign();
// Initiate the signature with public key to verify signature
sign.initVerify(pair.getPublic());
// Update signature instance with data for which signature needs to verify
sign.update(bytes);
// Verify the signature
booleanisValidSignature = sign.verify(signature);

if (isValidSignature)
{
System.out.println("Signature verified");
}
else
{
6
Spring Security
System.out.println("Signature Failed");
Configuration
}
}
}

☞Check Your Progress 1


1) Write about JCA with some of the core classes and interface with example

2) Write the characteristics of Message Digest (MD) and Message


Authentication Code (MAC) and compare MD and MAC.

3) Alice wants to send some confidential data securely to Bob over the network.
Alice uses digital signature to sign the data and did the following where S(m)
= digital signature of m.
• Compute S(m) using her private key
• Send m, S(m) and her public key to Bob
Bob did as below upon receiving the confidential data:
• Bob receive S(m), m and Alice's public key
• Bob verify the S(m) using m and Alice's key.
Alice used private key to digitally sign the confidential data. Yet the above
approach is attack prone. Figure out the possible attack and flaw in the above
approach.

12.2.2 INTRODUCTION OF JAVA SECURE SOCKET


EXTENSION (JSSE)
Data in-transit is vulnerable and can easily be modified or hacked by an unintended
recipient. Private or critical data that travel across the network containing information
such as password, credit card numbers etc., must be made unintelligible to
unauthorized parties. Data integrity must be ensured while data transports. Many
protocols have been designed to protect the privacy and integrity of in-transit data.
The Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols are
among them.
The Java Secure Socket Extension (JSSE) is a framework to enable secure internet
communication. This framework provides an implementation for a Java version of the
Secure Socket Layer (SSL) and Transport Layer Security (TLS) protocols. It also
7
Web Security
provides API’s for data encryption, server authentication, message integrity and
optional client Authentication.
JSSE provides API framework along with its implementation.It acts as a building
block to build secure web applications simply. It reduces the security vulnerabilities
by abstracting the complex underlying security algorithms and handshaking
mechanisms. The JSSE API boosts up the core network and cryptographic services
defined by the java.security and java.net packages with add-on security.
Supported security protocols by JSSE API are as follows:
• TLS: version 1.0, 1.1, and 1.2
• SSL: version 3.0
• DTLS: versions 1.0 and 1.2
JSSE Features and Benefits
As per the Oracle JSSE reference guide, important benefits and features of JSSE are
as follows:
• A standard component of the JDK
• Provider-based architecture makes it flexible and extensible
• Provides classes to create secure channels such as SSLSocket,
SSLServerSocket, and SSLEngine
• Initiation or verification of secure communication using cipher suite
negotiation
• Support for client and server authentication, which is part of the normal
SSL/TLS/DTLS handshaking
• Encapsulated HTTP in the SSL/TLS protocol, which allows access to web
pages using HTTPS
• Server session management APIs
• Server name indication extension to facilitate secure connections to virtual
servers.
• Provides support for Server Name Indication (SNI) Extension, which extends
the SSL/TLS/DTLS protocols to indicate what server name the client is
attempting to connect to during handshaking.
• Prevents man-in-the-middle attacks by providing support for endpoint
identification during handshaking.
The following section explains the SSL and describes how to implement SSL in Java
using JSSE (Java Secure Socket Extension) API.

JSSE provides an SSL toolkit for Java applications. In addition to the necessary
classes and interfaces, JSSE provides a handy command-line debugging switch that
you can use to watch the SSL protocol in action. A simple example with the below
code can be executed in debug mode to watch the handshaking details.

packagecom.ignou;
publicclassSecureConnection
{
publicstaticvoidmain(String[] arstring)
{
try
{
new java.net.URL("https://www.google.com").getContent();
}

catch (Exception exception)


{
exception.printStackTrace();
}
}
}

8
Spring Security
To run the above application in debug mode, we need to turn on SSL debugging. The Configuration
application connects to the secure website https://www.google.com using the SSL
protocol via HTTPS. In the command given below, the first option loads the HTTPS
protocol handler, while the second option, the debug option, causes the program to
print out its behavior.
java -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol -
Djavax.net.debug=sslcom.ignou.SecureConnection

The above SecureConnection program using the java.net.URL class demonstrates the
easiest way to add SSL to your applications. This approach is useful, but it is not
flexible enough to let you create a secure application that uses generic sockets. The
next section describes SSL and its implementation using JSSE.
In simple terms, we can understand that SSL provides a secured connection between
server and client. SSL encrypts the communication between two devices operating
over a network connection to provide a secure channel. Secure communication
between web browsers and web servers is a very common example of SSL. The
following three main information security principles is required for secured
communication over a network, and SSL fulfils these:
• Encryption: Protects the data transmissions between involved entities
• Authentication: Ensures that the server we connect to is actually the intended
server
• Data integrity: guarantee that data exchange between two entities is not
modified by the third party

JSSE API
Java Security API is based on Factory Design Pattern extensively. JSSE provides
many factory methods to instantiate. The following section will outline some
important classes in JSSE API and the use of these classes.

SSLSocketFactory

The javax.net.ssl.SSLSocketFactory is used to create SSLSocket objects. Methods in


the the javax.net.ssl.SSLSocketFactory class can be categorized into three categories.
The first category consist of a single method static getDefault(), that can retrieve the
default SSL socket factory: static SocketFactorygetDefault()
The second category consist of five methods that can be used to
create SSLSocket instances:
• Socket createSocket(String host, int port)
• Socket createSocket(InetAddress host, int port)
• Socket createSocket(String host, int port, InetAddressclientHost, int
clientPort)
• Socket createSocket(InetAddress host, int port, InetAddressclientHost, int
clientPort)
• Socket createSocket(Socket socket, String host, int port, booleanautoClose)
The third category consists of two methods which return the list of SSL cipher suites
that are enabled by default and the complete list of supported SSL cipher suites:
• String [] getDefaultCipherSuites()
• String [] getSupportedCipherSuites()

SSLSocket
9
Web Security
This javax.net.ssl.SSLSocket class extends java.net.Socket class in order to provide
secure socket. SSLSockets are normal stream sockets but with an added layer of
security over a network transport protocol, such as TCP. Since it extends
java.net.Socket class, thus it supports all the standard socket methods and adds
methods specific to secure sockets. SSLSocket instances construct an SSL connection
to a named host at a specified port. This allows binding the client side of the
connection to a given address and port. Few important methods in
javax.net.ssl.SSLSocket are listed below:

• String [] getEnabledCipherSuites()
• String [] getSupportedCipherSuites()
• void setEnabledCipherSuites(String [] suites)
• booleangetEnableSessionCreation()
• void setEnableSessionCreation(boolean flag)
• booleangetNeedClientAuth()
• void setNeedClientAuth(boolean need)
The methods below change the socket from client mode to server mode. This affects
who initiates the SSL handshake and who authenticates first:
• booleangetUseClientMode()
• void setUseClientMode(boolean mode)
Method void startHandshake() forces an SSL handshake. It's possible, but not
common, to force a new handshake operation in an existing connection.

SSLServerSocketFactory

The SSLServerSocketFactory class creates SSLServerSocket instance. It is quite


similar to SSLSocketFactory. Like createSocket method in SSLSocketFactory,
createServerSocket method is there in SSLServerSocketFactory class to get
SSLServerSocket instance.

SSLServerSocket

This class is subclass of ServerSockets and provides secure server sockets using
protocols such as the Secure Sockets Layer (SSL) or Transport Layer Security (TLS)
protocols. SSLServerSocket creates SSLSockets by accepting connections.

Example
The class SecureEchoServer uses JSSE API to create a secure server socket. It listens
on the server socket for connections from secure clients. When executing the
SecureEchoServer, you must specify the keystore to use. The keystore contains the
server's certificate.
package com.ignou;
public class SecureEchoServer
{
public static void main(String[] arstring)
{
try
{
SSLServerSocketFactorysslserversocketfactory = (SSLServerSocketFactory)
SSLServerSocketFactory.getDefault();
SSLServerSocketsslserversocket = (SSLServerSocket)
sslserversocketfactory.createServerSocket(8888);
SSLSocketsslsocket = (SSLSocket) sslserversocket.accept();
InputStreaminputstream = sslsocket.getInputStream();
InputStreamReaderinputstreamreader = new InputStreamReader(inputstream);
BufferedReaderbufferedreader = new BufferedReader(inputstreamreader);
String text = null;
10
Spring Security
while ((text = bufferedreader.readLine()) != null)
Configuration
{
System.out.println("Received From Client: "+text);
System.out.flush();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}

The SecureEchoClient code used JSSE to securely connect to the server. When
running the SecureEchoclient, you must specify the truststore to use, which contains
the list of trusted certificates.

package com.ignou;
public class SecureEchoClient
{
public static void main(String[] arstring)
{
try
{
SSLSocketFactorysslsocketfactory = (SSLSocketFactory)
SSLSocketFactory.getDefault();
SSLSocketsslsocket = (SSLSocket) sslsocketfactory.createSocket("localhost", 8888);
InputStreaminputstream = System.in;
InputStreamReaderinputstreamreader = new InputStreamReader(inputstream);
BufferedReaderbufferedreader = new BufferedReader(inputstreamreader);
OutputStreamoutputstream = sslsocket.getOutputStream();
OutputStreamWriteroutputstreamwriter = new OutputStreamWriter(outputstream);
BufferedWriterbufferedwriter = new BufferedWriter(outputstreamwriter);
String text = null;
System.out.println("Send Text to server");
while ((text = bufferedreader.readLine()) != null)
{
bufferedwriter.write(text + '\n');
bufferedwriter.flush();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}

The execution of the SecureEchoServer without keystore will give exception as


javax.net.ssl.SSLHandshakeException: no cipher suites in common while
execution of SecureEchoClient without trustStore will give exception as
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure.
Generate the self-signed SSL certificate using the Java keytool command and use the
generated certificate to execute SecureEchoServer and SecureEchoClient code.
Follow below steps to generate SSL certificate.
1. Open a command prompt or terminal
2. Run this command
keytool -genkey -keyalg RSA -alias localhost -keystore selfsigned.jks -
validity <days> -keysize 2048
Where <days> indicate the number of days for which the certificate will be
valid.
11
Web Security
3. Enter a password for the keystore. Note this password as you require this for
configuring the server
4. Enter the other required details
5. When prompted with "Enter key" password for <localhost>, press Enter to
use the same password as the keystore password
6. Run this command to verify the contents of the keystore
keytool -list -v -keystore selfsigned.jks

Put this generated selfsigned.jks file into the root directory of your source code and
execute the below command to run SecureEchoServer and SecureEchoClient.

java -Djavax.net.ssl.keyStore=selfsigned.jks -
Djavax.net.ssl.keyStorePassword=localhost com.ignou.SecureEchoServer

java -Djavax.net.ssl.trustStore=selfsigned.jks -
Djavax.net.ssl.trustStorePassword=localhost com.ignou.SecureEchoClient

Note:Use the same password you used to create a self-signed certificate in step 3 for
keyStorePassword and trustStorePassword. I used localhost as a password in self-
signed certificate generation;therefore so in the above command, I used the same.

On the client terminal, send some text to the server, and the server will echo the same
text on its terminal.

☞Check Your Progress 2

1) Explain JSSE with its features and benefit

2) List down the benefits of implementing SSL using JSSE over secure
connection established using java.net.URL

3) List down the reasons for javax.net.ssl.SSLHandshakeException during the


establishment of a secure connection

12.3 ISSUES AND CHALLENGES OF WEB SECURITY

With the advancement of the Web and other technology, the frequent usage of
networks makes web applications vulnerable to a variety of threats. Advancements in
web applications have also attracted malicious hackers and scammers, who are always
coming up with new attack vectors. Hackers and attackers can potentially take various
12
Spring Security
path through the web application to cause risks to your business. Web application Configuration
security deals specifically with the security surrounding websites, web applications
and web services such as APIs.

Common Web App Security Vulnerabilities

Web application security vulnerabilities can range from targeted database


manipulation to large-scale network disruption. Few methods of attack which
commonly exploit are:
• Cross site scripting (XSS) – Cross site scripting (XSS) is a kind of client-
side code injection attack. Attacker executes malicious script into web
browser of the victim by including malicious code into benign and trusted
websites. Attacker mostly uses the forums, message boards and web pages
that allow comments to perform XSS. The use of user’s input without
validation in the output generated by web page make the web page vulnerable
to XSS. XSS attacks are possible in VBScript, ActiveX, Flash, and even CSS.
XSS is most common in JavaScript, JavaScript has very restricted access to
user’s operation system and file system since most web browsers run
JavaScript with restrictions. Malicious JavaScript can access all the objects to
which a web page has access to. Web page access also includes user’s
cookies. Most often, session tokens are stored into cookies. Thus, if attackers
obtain a user’s session cookie, they can impersonate that user, perform actions
on behalf of the user, and gain access to the user’s sensitive data.
• Cross-site request forgery (CSRF) – Cross site request forgery, also known
as CSRF or XSRF, is a type of attack in which attackers trick a victim into
making a request that utilizes their authentication or authorization. The
victim’s level of permission decides the impact of CSRF attack. Execution of
CSRF attack consists of mainly two-part.
o Trick the victim into clicking a link or loading a web page
o Sending a crafted, legitimate-looking request from victim’s browser
to the website
Tricking the victim into clicking a link or loading a web page is done through
social engineering or using the malicious link. While sending a crafted
request, attackers send the value chosen by themselves and include the
cookies, if any, which is associated with the origin of the website. A CSRF
attack exploits the fact that the browser sends the cookies to the website
automatically with each request. CSRF attacks take place only in the case of
an authenticated user. This means that the victim must be logged in for the
attack to succeed.

• SQL injection (SQLi) – SQL Injections are among the most common threat
to data security.SQL injection, also known as SQLi, is a type of injection
attack that exploits the weakness of application security and allows attackers
to execute malicious SQL statements. Malicious SQL statements execution
enable attackers to access or delete records, change an application data-driven
behavior. Attackers can use SQL Injection vulnerabilities to bypass
application security measures. Any website or web application, which uses a
relational database such as MySQL, Oracle, SQL Server etc., can be impacted
by SQL Injection. Attackers use SQLi to gain access to unauthorized
information, modify or create new user permissions, or otherwise manipulate
or destroy sensitive data. Attackers use specially-crafted input to trick an
application into modifying the SQL queries that the application asks the
database to execute. Let us understand it by example.
Suppose that a developer has developed a web page to show the account
number and balance into account for the current user’s ID provided in a URL,
Code snippet in java might be as below:

13
Web Security
String accountBalanceQuery =
"SELECT accountNumber, balance FROM accounts WHERE account_owner_id = "
+ request.getParameter("user_id");
try
{
Statement statement = connection.createStatement();
ResultSetrs = statement.executeQuery(accountBalanceQuery);
while (rs.next())
{
page.addTableRow(rs.getInt("accountNumber"), rs.getFloat("balance"));
}
}
catch (SQLException e) { ... }

For normal operation user visit the URL as below:


https://securebanking/show_balances?user_id=1234
From the java code snippet, we can check that SQL query to find the account
balance for user 1234 will be as below:
SELECT accountNumber, balance FROM accounts WHERE
account_owner_id = 1234

The above query is a valid query, and it will return only the intended result to
show the balance for the user id 1234.
Now suppose, an attacker has identified the application security vulnerability
and change the parameter user_id as-
0 OR 1 = 1

Now the query will be as below:

SELECT accountNumber, balance FROM accounts WHERE account_owner_id = 0


OR 1=1

When the application asks this query to execute into the database, it will
return the account balance for all the accounts into the database. The attacker
now knows every user’s account numbers and balances.

• Denial-of-service (DoS) – Denial-of-service attack is a type of attack which


makes information systems, devices or other network resources non-
responding. A denial-of-service condition is accomplished by flooding the
targeted host or network with traffic until the target cannot respond or simply
crashes, preventing access for legitimate users.DoS attack exploits a
vulnerability in a program or website to force improper use of its resources or
network connections, which also leads to a denial of service. There are two
general methods of DoS attack: flooding services or crashing services. Flood
attacks occur when the system receives too much traffic for the server to
buffer, causing them to slow down and eventually stop.

• Insecure Direct Object References (IDOR) - Insecure direct object


references (IDOR) are a cybersecurity issue that occurs when a web
application exposes a reference to internal implementation. Internal
implementation objects include files, database records, directories and
database keys. For example, an IDOR vulnerability could happen if the URL
of a transaction could be changed through client-side user input to show
unauthorized data of another transaction. For example, let’s consider that the
web application displays transaction details using the following URL:
https://www.example.com/transaction?id=7777

14
Spring Security
A malicious attacker could try to substitute the id parameter value 7778 with Configuration
other similar values, for example:

https://www.example.com/transaction?id=7778

transaction Id 7778 could be a valid transaction but belonging to a different


user. The malicious attacker should not be authorized to see the transaction
for id 7778. However, if the developer made an error, the attacker would see
this transaction, and hence web app would have an insecure direct object
reference vulnerability.

12.4 SPRING SECURITY OVERVIEW

Security is a very crucial aspect for any application to avoid malfunctioning,


unauthorized access or hacking of crucial data. Spring security modules provide us
with a framework to easily develop a secure application with very few configurations.
Spring Security is a very robust and highly customizable authentication and
authorization access-control framework. Along with Authentication and Authorization
in Java applications, it also protects the application against attacks such as cross-site
request forgery, session fixation, clickjacking etc. In short, Spring Security refers to a
series of processes that intercept requests and delegate security processing to the
designated Spring Security process. Let us understand the three important concepts
before getting dive into Spring Security.

Authentication

Authentication refers to the process of confirming user’s identity whom he claims to


be. It’s about validating user’s credentials such as Email/Username/UserId and
password. The system validates whether the user is one whom he claims to be using
user’s credentials. The system authenticates the user identity through login ID and
password. Authentication using login Id and password is the usual way to
authenticate; still, there are other ways to authenticate. Various methods for
authentication are as follows:
• Login Form
• HTTP authentication
• HTTP Digest
• X.509 Certificates
• Custom Authentication Methods
Authorization
Authorization action takes place once a system has authenticated the user’s identity.
Authorization refers to the rules that determine who is allowed to do what. E.g. John
may be authorized to create and delete databases, while Bob is only authorized to
read. Authorization is a process of permitting required privileges to the user to access
a specific resource in an application such as files, location, database etc. In simple
terms, authorization evaluates a user’s ability to access the system and up to what
extent. There may be different approaches to implement authorization into an
application. Different approaches to authorization include:
• Token-based: Users are granted a cryptographically signed token that
specifies what privileges the user is granted and what resources they can
access.
• Role-Based Access Control (RBAC): Users are assigned role/roles, and
these roles specify what privileges users have. Users roles would restrict what
resources they have access to.

15
Web
b Security
• Acccess Control List (ACL): An ACL speecifies which h users have access
a to a
partticular resourrce. For instaance, if a user wants to acccess a specific file or
fold
der, their userrname or detaails should bee mentioned ini the ACL inn order to
be able
a to accesss certain data.
Various metthods for authhorization aree as follows:
• Acccess controls ffor URLs
• Secure Objects aand methods
• Acccess Control L List (ACL)

Servlet Fillters

A Servlet fiilter is an object that can intercept


i HTT
TP requests. Filter
F object iis invoked
at preprocesssing and posstprocessing of a request. Filters are mainly
m used too perform
cross-cuttingg concerns such as coonversion, loogging, com mpression, enncryption,
decryption, input validatiion, security implementatio
i on etc.

Figurre 12.1: Servleet Filters

On the left of above imaage (Figure 12.1),


1 we cann see that theere is no prepprocessing
and postproocessing of reequest, and th hus request iss directly reaaching to servvlet. If we
want to immplement thee security, beefore requestt being proccessed by thhe servlet,
DispatcherSServlet in the context of sppring, can be implemented d using filters as shown
above onthee right side off the image.
In the conteext of Spring Application, no security im mplementatio on in DispatchherServlet
and no one will
w like to im mplement secuurity in all the controllers. Ideally, authhentication
and authorizzation shouldd be done beffore a requestt hits the con ntroller. Sprinng security
uses variouss filters to impplement securrity in Springg Applicationss.
Spring 4 Security
S

The Spring Security stackk is shown inn the diagram((Figure 12.2)

16
Spring Security
Configuration

Spring Security Kerberos Spring Cloud Security

Spring Security SAML Spring Security OAuth

Spring Security
Spring Security Modules

Figure 12.2: Spring Security Stack

Spring 4 Framework has the following modules to provide Security to the Spring-
Based Applications:
• Spring Security
• Spring Security SAML
• Spring Security OAuth
• Spring Security Kerberos
• Spring Cloud Security
In Spring Framework, “Spring Security” module is the base module for the rest of the
Spring Security modules. The following sections will outline some basics of “Spring
Security” module.
Spring Security is one of the Spring Framework’s security modules. It is a Java
SE/Java EE Security Framework to provide Authentication, Authorization, SSO and
other Security features for Web Applications or Enterprise Applications.

Spring 4 Security Features

Spring Security Official website: https://projects.spring.io/spring-security/


Spring Security Documentation website: https://docs.spring.io/spring-
security/site/docs/
Spring 3.x Security Framework provides the following Features as per Spring Security
Official website:

• Authentication and Authorization.


• Supports BASIC, Digest and Form-Based Authentication.
• Supports Cross-Site Request Forgery (CSRF) Implementation.
• Supports “Remember-Me” Feature through HTTP Cookies.
• Supports SSO (Single Sign-On) Implementation.
• Supports LDAP Authentication.
• Supports OpenID Authentication.
• Supports Implementation of ACLs
• Supports “Channel Security” that means automatically switching between
HTTP and HTTPS.
• Supports I18N (Internationalization).
• Supports WS-Security using Spring Web Services.

17
Web Security
• Supports Both XML Configuration and Annotations. Very Less or minimal
XML Configuration.
Spring 4.x Security Framework supports the following new features:
• Supports WebSocket Security.
• Supports Spring Data Integration.
• CSRF Token Argument Resolver.

Spring 4 Security Levels

Spring Security supports the following two Levels of Authorization-


• Method Level Authorization
• URL Level Authorization
NOTE
Spring Security supports “Method Level Security” by using AOP (Aspect-Oriented
Programming) that means through Aspects. Spring Security supports “URL Level
Security” by using Servlet filters.

Spring 4 Security Advantages

Spring 4 Security Framework provides the following Advantages:


• Open Source Security Framework
• Comprehensive support for authentication and authorization
• Flexible, Easy to Develop and Unit Test the applications
• Protection against common tasks
• Declarative Security Programming
• Easy of Extendibility
• Ease of Maintenance
• CSRF protection
• We can develop Loosely-Coupled Applications.

☞Check Your Progress 3


1) What is Spring Security? Explain in detail with its feature and benefit.

2) What is Authentication (AuthN)? Write down various methods for AuthN.

3) Howdoes Authorization (AuthZ) make the system secured and restricted? List
down various methods.

18
Spring Security
12.5 JAVA BASED CONFIGURATION Configuration

Spring security uses Servlet Filter to implement the security in java applications. It
creates a Servlet Filter named as SpringSecurityFilterChain.
SpringSecurityFilterChain takes care of all the security concerns such as validating
submitted username and passwords, application URLs protection, redirecting to the
log in form to unauthenticated users, etc. Spring Security provides an abstract class
AbstractSecurityWebApplicationInitializer that will ensure the
springSecurityFilterChain Filter get registered for every URL in the application.
SpringSecurityFilterChain can be registered into spring application with the
initialization of AbstractSecurityWebApplicationInitializer as:
import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer


extends AbstractSecurityWebApplicationInitializer
{

With the latest Spring Security and/or Spring Boot versions, Spring Security is
configured by having a class that:
• Is annotated with @EnableWebSecurity.
• Extends WebSecurityConfigurerAdapter, which basically provides a
convenient base class for creating a WebSecurityConfigurer instance. The
implementation allows customization by overriding methods. Here’s what a
typical WebSecurityConfigurerAdapter looks like:
@Configuration
@EnableWebSecurity // (1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{ // (1)

@Override
protected void configure(HttpSecurity http) throws Exception { // (2)
http
.authorizeRequests()
.antMatchers("/home").permitAll() // (3)
.anyRequest().authenticated() // (4)
.and()
.formLogin() // (5)
.loginPage("/login") // (5)
.permitAll()
.and()
.logout() // (6)
.permitAll()
.and()
.httpBasic(); // (7)
}
}

1. A POJO class extending WebSecurityConfigurerAdapter and normal Spring


@Configuration with the @EnableWebSecurity annotation
2. Overriding of WebSecurityConfigurerAdapter’sconfigure(HttpSecurity)
method enables you to configure the FilterChain using DSL.
3. permitAll() allows all the users for the configured URI. User does not have to
be authenticated. antMatcher allows to use wildcards such as (*, \*\*, ?) in the
string. The request “/home” is allowed to all users without authentication.

19
Web Security
4. All other requests except “/home”, the user to be authenticated first, i.e. the
user needs to login.
5. As described, authentication methods in section 12.4, form login with a
custom loginPage (/login, i.e. not Spring Security’s auto-generated one) is
being used in the configuration. Login page should be accessible to anyone.
Thus “/login” URI has been permitted to all using permitAll().
6. The default spring logout feature is configured and has been permitted to all.
7. Apart from form login, the configuration is also allowing for Basic Auth, i.e.
sending in an HTTP Basic Auth Header to authenticate.
The above configuration creates SpringSecurityFilterChain which is accountable for
security concerns such as validating submitted username and passwords, application
URLs protection, redirecting to the log in form to unauthenticated users, etc. Java
Configuration do the following for our application.
• Register required authentication for every URL
• Creates a login form
• Allow a user to be authenticated using form-based authentication as well as
HTTP Basic Auth.
• Allow to logout
• Prevent from CSRF attack

Securing the URLs

The most common methods to secure the URL are as below:

• authenticated(): This protects the URL which requires user to be


authenticated. If the user is not logged in, the request will be redirected to the
login page.
• permitAll(): This is applied for the URL’s which requires no security, such as
css, javascript, login URL etc.
• hasRole(String role): This is used for authorization with respect to user’s role.
It restricts to single role. “ROLE_” will be appended into a given role. So if
role value is as ”ADMIN”, comparison will be against “ROLE_ADMIN”. An
alternative is hasAuthority(String authority)
• hasAuthority(String Authority): This is similar to hasRole(String Role). No
prefix will be appended in given authority. If authority is as “ADMIN”,
comparison will be against “ADMIN”
• hasAnyRole(String… roles): This allows multiple roles. An alternative is
hasAnyAuthority(String… authorities)

HTTP Security

To enable HTTP Security in Spring, we need to extend


the WebSecurityConfigurerAdapter. It allows to configure web-based security for
specific http requests. By default all request will be secured but it can be restricted
using requestMatcher(RequestMatcher) or other similar methods. The default
configuration in the configure(HttpSecurity http) method is as:
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic();
}

20
Spring Security
Form Login Configuration
Based on the features that are enabled in spring security, it generates a login page
automatically. It uses standard values for the URLs such as /login and /logout to
process the submitted login form and logout the user.
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/login").permitAll();
}

Authentication using Spring Security

Authentication is all about validating user credentials such as Username/User ID and


password to verify the user’s identity. We can either use in-memory-authentication or
jdbc-authentication.

In-Memory Authentication

In-Memory authentication can be configured using AuthenticationManagerBuilder as


below:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception
{
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("password")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("password")).roles("USER",
"ADMIN");
}

JDBC Authentication

To implement JDBC authentication, all you have to do is to define a data source


within the application and use it as below:
@Autowired
private DataSourcedataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception
{
auth.jdbcAuthentication().dataSource(dataSource)
.withDefaultSchema()
.withUser("user").password(passwordEncoder().encode("password")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("password")).roles("USER",
"ADMIN");
}

Aswe can see, we're using the autoconfigured DataSource.


The withDefaultSchema directive adds a database script that will populate the default
schema, allowing users and authorities to be stored. DDL statements are given for the
HSQLDB database. The default schema for users and authorities is as below:
create table users

21
Web Security
(
username varchar_ignorecase(50) not null primary key,
password varchar_ignorecase(50) not null,
enabled boolean not null
);
create table authorities
(
username varchar_ignorecase(50) not null,
authority varchar_ignorecase(50) not null,
constraint fk_authorities_users foreign key(username) references users(username)
);

Default Schema will not work for other databases except HSQLDB database. Check
the spring.io website for schema corresponding to a database. The database schema
can be checked at:
https://docs.spring.io/spring-security/site/docs/4.0.x/reference/html/appendix-
schema.html

Customizing the search Queries


If Spring application is not using default schema for security, we need to provide
custom queries to find user and authorities details as below:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception
{
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select uuid,password,enabled "
+ "from users "
+ "where uuid= ?")
.authoritiesByUsernameQuery("select uuid,authority "
+ "from authorities "
+ "where uuid= ?");
}

Customization of a search query in spring security is very easy, and two methods for
that has been provided as usersByUsernameQuery and
authoritiesByUsernameQuery.

12.6 CREATE SPRING INITIALIZER CLASS

AbstractAnnotationConfigDispatcherServletInitializer class has simplified the Spring


initialization. We don't need to manually create contexts but just set appropriate config
classes in getRootConfigClasses() and getServletConfigClasses() methods.
Let us consider that we're developing a web application, and we're going to use Spring
MVC, Spring Security and Spring Data JPA. For this simple scenario, we would have
at least three different config files. A WebConfig contains all our web-related
configurations, such as ViewResolvers, Controllers, ArgumentResolvers etc.
RepositoryConfig may define datasource, EntityManagerFactory,
PlatformTransactionManager etc.
For gluing all these together,we have two options. First, we can define a typical
hierarchical ApplicationContext, by adding RepositoryConfig and SecurityConfig in
root context and WebConfig in their child context:

22
Spring Security
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
Configuration
{
@Override
protected Class<?>[] getRootConfigClasses()
{
return new Class<?>[] { RepositoryConfig.class, SecurityConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses()
{
return new Class<?>[] { WebConfig.class };
}
@Override
protected String[] getServletMappings()
{
return new String[] { "/" };
}
}

If we have a single DispatcherServlet, we can add the WebConfig to the root context
and make the servlet context empty:
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses()
{
return new Class<?>[] { RepositoryConfig.class, SecurityConfig.class,
WebConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses()
{
return null;
}
@Override
protected String[] getServletMappings()
{
return new String[] { "/" };
}
}

12.7 CREATE CONTROLLER AND VIEW

Controllers and Mapping


Spring @Controller annotation is used to mark a class as web request handler in the
Spring MVC application. While @RestController is a convenience annotation to mark
a class as request handler for RESTful web services,@RestController is annotated
with @Controller and @ResponseBody.
A simple example of @Controller annotated Class responsible to handle a Get
Request method.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

23
Web Security
@Controller //(1)
@RequestMapping(value="/") //(2)
public class HomeController
{
@GetMapping //(3)
public ModelAndViewindex()
{
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
mv.getModel().put("message", "User, Spring Security Implemented Successfully !!");
return mv;
}
}

1. @Controller annotation is used to mark the class responsible to handle the


web request forwarded from Dispatcher Servlet.
2. @RequestMapping annotation has been used to mark at class level to make
class HomeController responsible to all web request for the URL pattern “/”
3. @GetMapping annotation has been used to mark the method index() to be
invoked for Method Get and URL pattern “/”
Views and Configuration
To render the view, ViewResolver configuration is required in Spring MVC
Application or Spring Boot Application. For JSP, ViewResolver configuration is
required in Spring MVC/Spring Boot application to resolve the location of jsp files.
There are two ways to configure view resolver as-

• Add entries as shown below in application.properties


spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
OR
• Configure InternalResourceViewResolver by extending
WebMvcConfigurerAdapter
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import
org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
@Override
public void configureViewResolvers(ViewResolverRegistry registry)
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
registry.viewResolver(resolver);
}
}

24
Spring Security
Configuration

12.8 RUN APPLICATION

This section will explain the steps required to run the Spring Boot application with
Spring Security. Tools and software required to write the code easily, manage the
spring dependencies and execute the application is as -
• Java 8 or above is required
• Maven
• Eclipse IDE
Step 1: Create a web maven project and add the required dependencies such as

spring-boot-starter-web, spring-boot-starter-security in pom.xml. Directory Structure


for Spring Project in eclipse will be as below –
Step 2: Spring Boot Application Initializer

packagecom.ignou.javabasedspringsecurity;

@SpringBootApplication
publicclassJavaBasedSpringSecurityApplicationextendsSpringBootServletInitializer
{
@Override
protectedSpringApplicationBuilder configure(SpringApplicationBuilderapplication)
{
returnapplication.sources(JavaBasedSpringSecurityApplication.class);
}
publicstaticvoid main(String[] args)
{
Figure 2: Project Folder Structure In Eclipse
SpringApplication.run(JavaBasedSpringSecurityApplication.class, args);
}
}

25
Web Security
Step 3: Spring Security Configuration
packagecom.ignou.javabasedspringsecurity.security;

@EnableWebSecurity
publicclassSecurityConfigextendsWebSecurityConfigurerAdapter
{
@Autowired
PasswordEncoderpasswordEncoder;
@Bean
publicPasswordEncoderpasswordEncoder()
{
returnnewBCryptPasswordEncoder();
}
@Override
protectedvoid configure(AuthenticationManagerBuilderauth) throws Exception
{
auth.inMemoryAuthentication().passwordEncoder(passwordEncoder).withUser("testuser")
.password(passwordEncoder.encode("user@123")).roles("USER").and().withUser("testadmin")
.password(passwordEncoder.encode("admin@123")).roles("USER", "ADMIN");
}
protectedvoid configure(HttpSecurityhttp) throws Exception
{
http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
}
}

Step 4: Initialize Spring Security


packagecom.ignou.javabasedspringsecurity.security;

publicclassSecurityInitializerextendsAbstractSecurityWebApplicationInitializer
{
// No Code Needed Here
}

Step 5: Include the spring security into App Initializer


packagecom.ignou.javabasedspringsecurity.security;
publicclassAppInitializerextendsAbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses()
{
returnnew Class[] { SecurityConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses()
{
returnnull;
}
@Override
protected String[] getServletMappings()
{
returnnew String[] { "/" };
}
}

26
Spring Security
Step 6: Controller Class and View Configuration
packagecom.ignou.javabasedspringsecurity.controller;
@Controller
@RequestMapping(value="/")
publicclassHomeController
{
@GetMapping
publicModelAndView index()
{
ModelAndViewmv = newModelAndView();
mv.setViewName("index");
mv.getModel().put("message", "User, Spring Security Implemented Successfully !!");
returnmv;
}
}

For the view we will use a simple jsp as below


<!DOCTYPEhtml>
<%@taglibprefix="spring"uri="http://www.springframework.org/tags"%>
<htmllang="en">
<body>
<div>
<div>
<h1>Spring Boot Security Example</h1>
<h2>Hello ${message}</h2>
</div>
</div>
</body>
</html>

Step 7: Spring Boot JspViewResolver configuration


Add the below properties into application.properties file

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

Step 8:Run the file created into Step 2 named


asJavaBasedSpringSecurityApplication.java to start the application. This file can be
executed using java command or from eclipse IDE itself. After successful execution
of the application, security configured application can be accessed using browser on
localhost:8080
In Step 3 we configured the spring security and defined the testuser with credentials
as user@123 and testadmin with credentials as admin@123.

Execution Output:
If user tries to access localhost:8080 and user is not logged in, spring will redirect to
user on localhost:8080/login as shown below. This login page is spring security in-
built.

27
Web
b Security

If user proviides wrong credentials,


c alert from spriing security will
w be as beloow:

After Succeessful login user will get thhe below screen:

☞Check Your
Y Proggress 4

1) What is SecurityyFilterChain inn Spring Secuurity?

2) Wriite the Sprinng Security Configuration


C n class code for below mentioned
m
criteeria-
httpp://www.securresite.com/staatic Opeen to everyonne – CSS, JavaaScript
httpp://www. secuuresite.com/lo
ogin Opeen to everyonne
httpp://www. secuuresite.com/usser/ ROL LE_USER orr ROLE_ADM MIN
httpp://www. secuuresite.com/addmin/ ROL LE_ADMIN only

28
Spring Security
Configuration

3) Consider that Spring Authentication with default schema attribute username


is not suitable for the application. Email attribute as the primary key is being
used instead of username. Write the Spring Security Configuration class code
to adapt the queries for the new schema as below:

CREATE TABLE users


(
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
enabled TINYINT NOT NULL DEFAULT 1,
PRIMARY KEY (email)
);

CREATE TABLE authorities


(
email VARCHAR(50) NOT NULL,
authority VARCHAR(50) NOT NULL,
FOREIGN KEY (email) REFERENCES users(email)
);

4) How to secure the URLs in Spring Security? Explain with available methods
to make URL secure.

12.9 SUMMARY

In this unit, many concepts related to web security have been explained. You got to
know about securing data at-rest and in-transit. In the unit JCA section described
many useful concepts such as Cipher, Message Digest, Message Authentication Code,
Signature. Using JCA API, the authenticity and integrity of the message can be
verified. Further SSL and other useful concepts to secure the data in-transit is
explained. The Spring Security provides a convenient and easy way to incorporate
security in spring applications with minimum configuration. The concept of
Authentication and Authorization has been explained to make application secure.
Various methods such as authenticate(), permitAll(), hasRole(), hasAuthority() have
been written to make URL secure in Spring Security. In-memory authentication and
JDBC authentication has been described with the custom search query to incorporate
user-defined schema for users and authorities.In the last section of this unit, you
learned code to integrate spring security into the spring boot application.
29
Web Security
12.10 SOLUTIONS/ANSWERS TO CHECK YOUR
PROGRESS

☞Check Your Progress 1


1) JCA has been described with the core classes and interface in section 12.2.1
2) Comparison of Message Digest and Message Authentication Code
Message Digest Message Authentication Code

A message digest algorithm takes a single A Message Authentication Code


input a message and produces a "message algorithm takes two inputs, a message
digest" (aka hash) and a secret key, and produces a MAC

It allows you to verify the integrity of the It allows you to verify the integrity
message and the authenticity of the message

Any change to the message will (ideally) Any change to the message or the
result in a different hash being generated. secret key will (ideally) result in a
different MAC being generated.

An attacker that can replace the message and Nobody without access to the secret
digest is fully capable of replacing the should be able to generate a MAC
message and digest with a new valid pair. calculation that verifies the integrity
and authenticity of the message

3) Man-in-the-middle attack is possible. Chuck, a man in the middle, attacks and


intercepts all the messages sent by Alice. Chuck performs below-
o Instead of forwarding message m, he forwards message n. Instead of
the signature on m with Alice's private key, he forwards a signature
on n with his private key.
o Instead of Alice's public key he sends his public key to Bob. Bob will
never see the difference as he does not know Alice’s public key
beforehand.
A flaw in the approach is that the public key should not be transferred along
with the message. Public key should be available to the person prior to
verification of the signature.

☞Check Your Progress 2


1) JSSE with the advantages has been written in section 12.2.2
2) java.net.URL class demonstrates the easiest way to add SSL to your
applications. This approach is useful, but it is not flexible enough to let you
create a secure application that uses generic sockets. Using JSSE API to
implement SSL gives us full control over the protocols that need to be
supported.
3) If javax.net.ssl.SSLHandshakeException occurs, it indicates that there is a
handshake_failure. We haven’t created or established the SSL certificate that
the client and server should be referencing. Normally a certificate is obtained
from a trusted certificate authority for a public site, but for testing and
development purposes, it’s common practice to create a self-signed certificate,
which just means you are the issuer. These are typically issued to
the localhost domain, so they’ll function locally but not be trusted elsewhere.
Refer section 12.2.2 for keytool to generate keypair and how to use this to
solve javax.net.ssl.SSLHandshakeException issue.

30
Spring Security
S
☞Check
C Yourr Progress 3 Configu
uration

1)
1 Refer secttion 12.4, Sprring Security has been expplained in detaail.
2)
2 Refer Autthentication inn Section 12.4
3)
3 Refer Autthorization in
n Section 12.44

☞Check
C Yourr Progress 4
1)
1 SecurityF
FilterChain iss a FilterChaain componeent which haas zero or more
m
Security Filters
F in an order.
o

Refer Sectiion 12.5 for moore details for SecurityFilterC


Chain.
2)
2 Hint: connfigure metho
od definition in
i Spring Seccurity Configu
uration will be
b as
-
@Overridde
protected void confiigure(HttpSeccurity http) thhrows Exceptiion
{
http
.authoorizeRequestss()
.antM
Matchers("/stattic","/registerr").permitAll(()
.antM
Matchers("/useer/**").hasAnnyRole("USER R", "ADMIN
N") // can passs
multipple roles
.antM
Matchers("/adm min/**").hasR Role("ADMIN N")
.anyRRequest().authhenticated()
.and())
.form
mLogin()
.login
nUrl("/login"))
.perm
mitAll();
}
• /staticc and /registerr is allowed too everyone soo permitAll() is used.
• /user//** must be accessible to o either “Usser” or “Adm min” roles. T Thus
hasAnnyRole("USE ER", "ADMIN N") is used.
• /admiin/** must be accessiible to the only Adm min role. T Thus
hasRo ole(“ADMIN N”) is used
• /loginn must be alloowed for all soo permitAll() is used.
3)
3 We need d to customize the searcch query. Sppring securityy can adapt the
customizee search querries very eassily. We simpply have to providep our oown

31
Web Security
SQL statements when configuring the AuthenticationManagerBuilder. Two
methods for customization has been provided as usersByUsernameQuery and
authoritiesByUsernameQuery. Refer to Section 12.5 for customizing the
search query.

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception
{
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select email,password,enabled "
+ "from users "
+ "where email = ?")
.authoritiesByUsernameQuery("select email,authority "
+ "from authorities "
+ "where email = ?");
}
4) Refer Securing the URLs in section 12.5

12.11 REFERENCES/FURTHER READING

• Craig Walls, “Spring Boot in action” Manning Publications, 2016.


(https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)
• Christian Bauer, Gavin King, and Gary Gregory, “Java Persistence with
Hibernate”,Manning Publications, 2015.
• Ethan Marcotte, “Responsive Web Design”, Jeffrey Zeldman Publication,
2011(http://nadin.miem.edu.ru/images_2015/responsive-web-design-2nd-
edition.pdf)
• Tomcy John, “Hands-On Spring Security 5 for Reactive Applications”,Packt
Publishing,2018
• https://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/Crypto
Spec.html
• https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERef
Guide.html
• https://docs.spring.io/spring-
security/site/docs/3.1.x/reference/springsecurity.html
• https://spring.io/guides/topicals/spring-security-architecture
• http://tutorials.jenkov.com/java-cryptography/index.html
• https://www.cloudflare.com/learning/security/what-is-web-application-
security/
• https://www.baeldung.com/java-ssl
• https://www.baeldung.com/java-security-overview
• https://www.baeldung.com/spring-security-login
• https://dzone.com/articles/spring-security-authentication

32
UNIT 13 CUSTOM LOGIN USING
SECURITY
Structure

13.0 Introduction
13.1 Objectives
13.2 Custom Login form creation
13.3 Spring Config for Custom Login Form
13.4 Create Request mapping and building Custom Login Form
13.5 Testing Custom Login Form
13.5.1 Integration Test in Spring Boot
13.6 Adding Logout Support
13.7 Summary
13.8 Solutions/ Answer to Check Your Progress
13.9 References/Further Reading

13.0 INTRODUCTION

Unit 12 explained how to secure the spring application using spring security. The
built-in login module of Spring Security authenticates the users and provides
accessibility to the application. Default spring security does not require to create new
jsp page for login since built-in login module already has default login page, which is
used to authenticate the user. The default login page provided by spring security is not
suitable for enterprise web application since the developer does not have control on
designing and processing behavior. This unit describes how to customize the login
page into spring security. The default login page, provided by Spring Security, has
been used in the example written in unit 12, section 12.8. In this unit, the example
executed in section 12.8 will be incorporated with a custom login page.

Testing is a very important phase of any application to ensure whether it works as per
expected functionality or not. Integration testing and unit testing play a vital role in
making the application error prone. This unit describes the annotation available in
spring boot for Integration testing. The next unit will explain about unit test
annotation available in spring boot.

Once user finishes all the activity on a web portal, he must be provided with a way to
invalidate the session using logout functionality. Spring logout feature with various
available methods has been explained in this unit.

13.1 OBJECTIVES
After going through this unit, you should be able to:

• create custom login page for spring security,


• configure the custom login page,
• execute the spring boot application with custom login page spring security,
and
• develop logout support in Spring Applications.

1
Web Security
13.2 CUSTOM LOGIN FORM CREATION
If no login form is configured into spring security, spring boot provides default login
screen for spring security. Default login screen will be used to authenticate the user,
and user will be allowed to access a resource. In an enterprise application default login
screen is not suitable since enterprise does not have full control over design,
processing URLs etc.
Customized login from creation and configuration is very easy in spring security.
Custom login form in Spring Application is nothing but a simple html or jsp, like
other web pages in java. A custom login form enables an enterprise to customize the
login form as per their choice of design. It provides the developer to have full control
over css and processing URL. A custom login form must be having below artifacts:

• Form action URL where the form is POSTed to trigger the authentication
process
• Username input field for the username
• Password input field for the password

Sample custom login page is shown below. You can put the css styling as per
application requirements. The following written custom login page will be used in the
execution of the application into example.

Form Action URL(Custom login Controller):


packagecom.ignou.javabasedspringsecurity.controller;

importorg.springframework.stereotype.Controller;

importorg.springframework.web.bind.annotation.GetMapping;

importorg.springframework.web.bind.annotation.RequestMapping;

@Controller

@RequestMapping(value="/customlogin")

publicclassLoginController

@GetMapping

public String login()

return"customlogin";

Custom Login Form with CSS:


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1; width: 50%; margin: auto;}

input[type=text], input[type=password]

2
{
Custom Login Using
width: 100%; Security
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}

button
{
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}

button:hover
{
opacity: 0.8;
}

.cancelbtn
{
width: auto;
padding: 10px 18px;
background-color: #f44336;
}

.container
{
padding: 16px;
width: 50%;
margin: auto;
}

.errormsg
{
width: 100%;
color: red;
padding: 12px 0px;
text-align: center;
}

span.psw
{
float: right;
padding-top: 16px;
}

</style>
</head>
<body>

<h2 style="text-align: center;">Spring Security Custom Login Form</h2>

<form action="/signin" method="post">


<div class="container">
<c:if test="${param.error ne null}">
<div class="errormsg"><b>Invalid
credentials</b></div>
</c:if>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>

<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>

<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>

<div class="container">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>

3
Web Seccurity </div>
</form>

</body>
</html>

The login foorm created abbove has the following rellevant artifactts:

• /siggnin – the UR
RL where thee form is PO OSTed to trig
gger the authhentication
proccess
• userrname – inputt field name for
f the usernaame
• passsword – inputt field name for
f the passwoord

Above jsp outputs


o the folllowing login
n screen (Figuure 13.1).

Figuree13.1: Custom
m Login Page iin Spring Secu
urity

13.3 SPRING
S Security
y CONFIG with Spring
S M
MVC
FOR
F CUSSTOM LOGIN
L F
FORM

Once you crreate the custtom login pag ge, you need to configure the custom login
l page
in spring security.
s Theere is a detaailed explanaation regardinng Java-baseed Spring
Security connfiguration inn section 12.5
5. Configuratiion for custom
m login pagee in spring
security is very easy. YYou just need d to set the lloginPage in FormLoginC Configurer
object provided by form mLogin(). Sam mple Spring security conffiguration witth custom
login page is shown beloow.
package com
m.ignou.javab
basedspringse
ecurity.secur
rity;
@EnableWebS
Security
public clas
ss WebSecurit
tyConfig exte
ends WebSecur
rityConfigure
erAdapter
{
d
@Autowired
PasswordEn
ncoderpasswor
rdEncoder;

@Bean
sswordEncoder
public Pas rpasswordEnco
oder()
{
return new BCryptPass
swordEncoder(
();
}

@Override
protected void configu
ure(Authentic
cationManager
rBuilder auth
h) throws Excception
{
auth.inMemoryAuthenti
ication().pas
sswordEncoder
r(passwordEnc
coder)
r("testuser")
.withUser
.password
d(passwordEnc
coder.encode(
("user@123")).roles("USER
R").and()
.withUser
r("testadmin"
").password(p
passwordEncod
der.encode("a
admin@123"))
.roles("U
USER", "ADMIN
N");
}

4
protected void configure(HttpSecurity http) throws Exception
Custom Login Using
{ Security
http.csrf().disable()
.authorizeRequests()
.antMatchers("/customlogin").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/customlogin")
.loginProcessingUrl("/signin")
.defaultSuccessUrl("/", true)
.failureUrl("/customlogin?error=true");
}
}

In the above configuration, in-memory authentication has been configured with two
users as testuser with Role USER and testadmin user with Role as USER, ADMIN
both. Thefollowing section will explain the elements used to create the form login
configuration.

authorizeRequests()
<intercept-url> element with access=”permitAll” configures the authorization
to allow all the requests on that particular path. Thus the requests for which no
authorization is required, can be achieved without disabling the spring security using
permitAll().

formLogin()
There are several methods to configure the behavior of formLogin().

• loginPage() – the custom login page


• loginProcessingUrl() – the url to submit the username and password to
• defaultSuccessUrl() – the landing page after a successful login
• failureUrl() – the landing page after an unsuccessful login

☞Check Your Progress 1

1) Why is login form customization required in an application? Explain the


customized login form configuration with sample code.

2) Define loginPage() and loginProcessingUrl() in Spring Boot Security


configuration.

13.4 CREATE REQUEST MAPPING AND


BUILDING CUSTOM LOGIN FORM
Custom login form creation has been explained in Section 13.2. A very simple custom
login from named as customlogin.jsp without any css is shown below
5
Web Security
<html>
<body>
<div>
<center>Custom Spring Login Form</center>
<form action="/signin" method="post">
<input name="username" type="text" placeholder="Enter Username" />
<input name="password" type="text" placeholder="Enter password" />
<input type="submit" />
</form>
</div>
<body>
<html>

Custom login form must be mapped with controller in order to render the page to the
user. The controller class is responsible for processing the request received from the
dispatcher servlet. Spring provides annotation like @Controller to make a POJO class
a controller in spring mvc application. @RequestMapping can be used at class level to
map the controller which will be responsible for handling the request, and at the
method level to map the method, which will be responsible for handling the requested
URL. In previous code snippet for security configuration in section 13.3,
loginPage("/customlogin") has been used. "/customlogin" should be mapped into a
controller which will be responsible to process it and to return the corresponding
view. Request mapping is shown below for "/customlogin" which return the view
name as customlogin.

Spring view resolver resolves this view name as customlogin.jsp and it renders the jsp
created into section 13.2
package com.ignou.javabasedspringsecurity.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value="/customlogin")
public class LoginController
{

@GetMapping
public String login()
{
return "customlogin";
}

In above code snippet, LoginController is mapped with the URL pattern /customlogin
and login() method is returning view name as cutomlogin. View resolver will resolve
the view and corresponding view will be rendered.

13.5 TESTING CUSTOM LOGIN FORM


This section describes the execution of spring boot application with custom login form
using spring security. Configuration code and request mapping code has been written
6
Custom Login Using
in code sample. This section also describes the annotations available in spring boot for Security
unit testing.
Directory Structure for Spring Project in eclipse will be as below (Figure 13.2) –

Figure 13.2: Project Structure In Eclipse

Spring Security Configuration for custom login form

packagecom.ignou.javabasedspringsecurity.security;

@EnableWebSecurity
publicclassSecurityConfigextendsWebSecurityConfigurerAdapter
{
@Autowired
PasswordEncoderpasswordEncoder;
@Bean
publicPasswordEncoderpasswordEncoder()
{
returnnewBCryptPasswordEncoder();
}
@Override
protectedvoidconfigure(AuthenticationManagerBuilderauth) throws Exception
{
auth.inMemoryAuthentication().passwordEncoder(passwordEncoder).withUser("testuser")
.password(passwordEncoder.encode("user@123")).roles("USER").and().withUser("testadmin")
.password(passwordEncoder.encode("admin@123")).roles("USER", "ADMIN");//(1)
}
protectedvoidconfigure(HttpSecurityhttp) throws Exception
{
http.csrf().disable()
.authorizeRequests()
.antMatchers("/customlogin*").permitAll() //(2)
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/customlogin") //(3)
.loginProcessingUrl("/signin") //(4)
.defaultSuccessUrl(“/”, true)
.failureUrl(“/customlogin?error=true”);
}
}

In above code followings have been configured.


1) In-Memory authentication is configured for users testuser and testadmin.

7
Web Security
2) /customlogin URL should be accessible to all. Thus permitAll() will allow all
request to pass.
3) formLogin().loginPage("/customlogin") configures the customlogin page.
Controller must have a mapping corresponding to Url pattern “/customlogin”
to return customlogin page.
4) Custom login form processing URL is configured by
loginProcessingUrl("/signin"). Custom login page form action must be
“/signin”

Controller Classes and View


packagecom.ignou.javabasedspringsecurity.controller;

importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value="/customlogin")
publicclassLoginController
{

@GetMapping
public String login()
{
return"customlogin";
}

packagecom.ignou.javabasedspringsecurity.controller;

importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value="/")
publicclassHomeController
{
@GetMapping
publicModelAndViewindex()
{
ModelAndViewmv = newModelAndView();
mv.setViewName("index");
mv.getModel().put("message", "User, Spring Security with custom login page
implemented Successfully !!");
returnmv;
}
}

Custom login from with CSS


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1; width: 50%; margin: auto;}

input[type=text], input[type=password]
{
width: 100%;
padding: 12px 20px;
margin: 8px 0;

8
display: inline-block;
Custom Login Using
border: 1px solid #ccc; Security
box-sizing: border-box;
}

button
{
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}

button:hover
{
opacity: 0.8;
}

.cancelbtn
{
width: auto;
padding: 10px 18px;
background-color: #f44336;
}

.container
{
padding: 16px;
width: 50%;
margin: auto;
}

.errormsg
{
width: 100%;
color: red;
padding: 12px 0px;
text-align: center;
}

span.psw
{
float: right;
padding-top: 16px;
}

</style>
</head>
<body>

<h2 style="text-align: center;">Spring Security Custom Login Form</h2>

<form action="/signin" method="post">


<div class="container">
<c:if test="${param.error ne null}">
<div class="errormsg"><b>Invalid
credentials</b></div>
</c:if>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>

<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>

<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>

<div class="container">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>

</body>

9
Web Seccurity </html>

Execute the application aas explained in


i Unit 12. Inn above exammple spring seecurity has
been config
gured with Usser as testuser with credenntial as user@
@123 and anoother User
as testadmin
n with credenntial as admin@
@123.

Output:
If user tries to access loccalhost:8080 and
a user is noot logged in, spring will reedirect the
user on locaalhost:8080/cuustomlogin and custom loogin page willl be rendered as shown
below in Fig gure 13.2:

Figuree 13.3: Custom


m Login Page In
I Spring Secu
urity

If user provides wrong crredentials, aleert from sprinng security wiill be as show
wn in
Figure 13.4 :

Figure 13.4: Invalid Credentialss Error Messaage

After Succeessful login usser will be reedirected to inndex.jsp and it


i will output as shown
in Figure 133.5.

10
Custom Loggin Using
Security

Figure 13.5: Success Screeen After Auth


hentication

13.5
5.1 Integrattion Test in
n Spring Boot

The following seection describbes the integrration test inn the spring boot
b applicattion.
Befoore getting diive into inteegration testinng, let us deefine how inntegration tesst is
different from uniit test.

Unit testing aims at individual modules of an


a applicationn without anyy interaction with
w
dependencies to validate
v p the expected result or not.
wheether code is working as per
gration testing
Integ g aims to vallidate the cod
de is workingg fine when different
d moddules
are combined
c as a group.

Previous sections described cuustom login form


f integratiion with sprinng security. H
Here
integgration test will
w be descrribed for con nfigured custom login fo orm with spring
securrity. Spring provides manyy annotations to perform inntegration testt.

Spriing Securityy and Mock


kMvc Set Up
p
Sprin
ng Security with
w Spring MVC M test cann be used witth the configuuration of Spring
Secu
urity FilterChaainProxy as a Filter. The foollowing set up
u performs the
t same.

@RunW
With(SpringRRunner.class)
)
@SpringBootTest
@Auto
oConfigureMoockMvc
class
sJavaBasedSppringSecurity
yApplication
nTests
{
@Autowireed
privateMoockMvcmvc;
}

@RuunWith: @RuunWith(SprinngRunner.classs) instructs JUnit to run n using Sprinng’s


testin
ng support. SppringRunner is the new naame for SpringgJUnit4ClasssRunner.

@Sp pringBootTestt: This annotaation instructts Spring Booot to use mainn class annotated
with @SpringBootApplicationn to start a Spring application conteext. Spring boot b
appliication testing
g requires notthing special to do. It’s ApplicationCoontext that neeeds
to bee available too test Spring Boot applicaation. @RunWith instructts the spring--test
moduule to create an ApplicationContext. SpringBootTe
S est loads com
mplete applicaation
and injects
i all the beans, whichh can be slow.

@Au utoConfigureM MockMvc: Spring


S providees a way to simulate
s the HTTP
H requesst in
whicch applicationn code will bee executed exxactly the sam
me way as it were
w processinng a
11
Web Security
real HTTP request but without any server start. For this simulation use, Spring’s
MockMvc and that can be configured using @AutoConfigureMockMvc.

SecurityMockMvcRequestPostProcessors

RequestPostProcessor interface is provided by Spring MVC Test. These request


processors can be used to modify the request. Spring Security has provided many
implementations of RequestPostProcessor to make testing easy and efficient.Spring
Security’s ReuestPostProcessor implementations can be used by static import of as
below:
importstaticorg.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

There are two ways to run the test cases as a specific User in Spring MVC Test.

• Running the test case as a specific user with RequestPostProcessor


• Running the test case as a specific user with Annotations
Running the test case as a user with RequestPostProcessor

The following test will run as a specific user, which need not to exist since we are
mocking the user, with the username "user", the password "password", and the role
"ROLE_USER":
@Test
publicvoidtestAlreadyLoggedInUser() throws Exception
{
mvc.perform(get("/").with(user("user"))).andExpect(authenticated().withUsername("user"))
.andExpect(authenticated().withRoles("USER"))
.andExpect(model().attribute("message",
"User, Spring Security with custom login page implemented Successfully !!"));
}

In the set up MockMvc is autoconfigured as mvc and it is being used to simulate the
HTTP request. Here RequestPostProcessoruser() has been used to modified the
get(“/”) request. User RequestPostProcessor can be customized for password and roles
as –

mvc.perform(get("/").with(user("John").password("pass@123").roles("USER","ADMIN")))

Test can be run as an anonymous user with following configuration.

mvc.perform(get("/").with(anonymous()))

Running the test case as a user with Annotation


Instead of RequestPostProcessor to create a user, annotation can be used for the same.
The following test will run as a specific user, which does not need to exist since we
are mocking the user, with the username "user", the password "password", and the
role "ROLE_USER":
@Test
@WithMockUser
publicvoidtestAlreadyLoggedInUser() throws Exception
{
mvc.perform(get("/")).andExpect(authenticated().withUsername("user"))
.andExpect(authenticated().withRoles("USER"))
.andExpect(model().attribute("message",
"User, Spring Security with custom login page implemented Successfully !!"));
}

@WithMockUser can be customized with the following attributes:

12
Custom Login Using
• username: String Security
• authorities: String[]
• password: String
• roles: String[]

SecurityMockMvcRequestBuilders

RequestBuilder interface is provided by Spring MVC Test. These request builders can
be used to create the MockHttpServletRequest into the test. Few implementations of
RequestBuilderhas been provided by Spring Security to make testing easy and
efficient. Spring Security’s ReuestBuilder implementations can be used by static
import of as below:
importstaticorg.springframework.security.test.web.servlet.request.SecurityMockMvcRequest
Builders.*;

Form Based Authentication Testing

Form based authentication can be tested very easily in Spring Boot with the help of
SecurityMockMvcRequestBuilders. Below will submit a POST request to “/login”
with the username as “user”, the password as “password” and valid CSRF token.

mvc.perform(formLogin())

Customization of formLogin() is very easy and an example of it is given below.


@Test
publicvoidtestFormLogin() throws Exception
{
mvc.perform(formLogin("/signin").user("testadmin").password("admin@123")).andExpect(
status().isFound())
.andExpect(redirectedUrl("/")).andExpect(authenticated().withUsername("testadmin"))
.andExpect(authenticated().withRoles("ADMIN", "USER"));
}

In above configuration a POST request for “/signin” with the username as “testadmin”
and the password as “admin@123” with a valid CSRF token will be submitted.
Parameters name can be customized as follows -
mvc.perform(formLogin("/singin").user("uname","[email protected]").password("password","admin@"))

Logout Testing Using SecurityMockMvcRequestBuilders

Logout functionality can be tested very easily using


SecurityMockMvcRequestBuilders. Example for Logout test is as followings-

mvc.perform(logout())

Logout processing URL can be customized as

mvc.perfrom(logout(“/signout”))

13
Web Seccurity
Check the folder
fo src/test for unit test cases.
c All unitt test cases caan be executed by right
click on the project -> Ruun As -> Juniit Test as show wn below scrreenshot in Figgure 13.6

Figuree 13.6: UnitCaase Execution From


F Eclipse IDE

Successful execution
e of Unit
U test casee will output thhe following.. As you can sees that
all test casess are passed tthat is shown by green tickk and green prrogress bar inn the
Figure 13.7..

Figgure 13.7: Uniit Test Cases E


Execution Logg

13.6 ADDING
A G LOGOU
UT SUPP
PORT
The basic configuration
c of Spring Loogout functioonality using the logout() method
m is
simple enou
ugh:
@Configurat
tion
@EnableWebS
Security
public clas
ss SecSecurittyConfig exte
ends WebSecur
rityConfigure
erAdapter
{
@Override
protected void
v configur
re(final Http
pSecurity htt
tp) throws Ex
xception
{
tp
htt
//...
/
.logout()
//...
/
}
//...
}

The above configuratioon enables default logoutt mechanism m with processing url:
/logout, whiich used to bee /j_spring_seecurity_logouut before Spriing Security 4.
4 We can

14
Custom Login Using
customize the logout feature in spring security. Let us see the advanced customization Security
of spring logout.

logoutSuccessUrl()
On successfully logout operation, Spring Security will redirect the user to a specified
page. By default, this is the root page (“/”), but this is configurable:
//...
.logout()
.logoutSuccessUrl("/successlogout")
//...

logoutUrl()
Like other defaults in Spring Security, logout mechanism has a default processing
URL as well – /logout. To hide the information regarding which framework has been
used to secure the application, it’s better to change the default value. It can be done as
below:
// ...
.logout()
.logoutUrl("/do_logout")
// ...

invalidateHttpSession and deleteCookies


These two advanced attributes control the session invalidation as well as a list of
cookies to be deleted when the user logs out. Default value for invalidateHttpSession
is true on logout.

//...
.logout()
.logoutUrl("/do_logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
// ...

Logout feature can be tested by enabling the logout option for the user. Add the logout
option by doing the changes into index.jsp as shown below.
<!DOCTYPEhtml>
<%@taglibprefix="spring"uri="http://www.springframework.org/tags"%>
<htmllang="en">
<body>
<div>
<div>
<astyle="text‐align: left;" href="/logout">logout</a>
<h1>Spring Boot Security Example</h1>
<h2>Hello ${message}</h2>
</div>
</div>
</body>
</html>

Logout configuration into WebSecurityConfig.java is described below.

15
Web Seccurity pa
ackagecom.igno
ou.javabasedsp
pringsecurity.
.security;

EnableWebSecur
@E rity
pu
ublicclassWebS SecurityConfig
gextendsWebSec
curityConfigurrerAdapter
{
@Autowired
derpasswordEnc
PasswordEncod coder;
@Bean
rdEncoderpassw
publicPasswor wordEncoder()
{
CryptPasswordE
returnnewBC Encoder();
}
@Override
dconfigure(Aut
protectedvoid thenticationMa
anagerBuilderaauth) throws Exception
E
{
oryAuthenticat
auth.inMemo tion().passworrdEncoder(pass
swordEncoder).
.withUser("tes
stuser")
.password(p
passwordEncode
er.encode("useer@123")).role
es("USER").and
d().withUser("
"testadmin")
.password(p
passwordEncode
er.encode("admmin@123")).rol
les("USER", "A
ADMIN");
}
protectedvoid
dconfigure(Htt
tpSecurityhttpp) throws Exce
eption
{
http.csrf()
).disable()
.authorizeR
Requests()
.antMatcher
rs("/customlog
gin*").permitAAll()
.anyRequest
t().authentica
ated()
.and()
.formLogin()
loginPage("/cu
.l ustomlogin")
.l
loginProcessin ngUrl("/signin
n")
.d
defaultSuccess sUrl("/", true
e)
.f
failureUrl("/c customlogin?er
rror=true")
.and()
.
.l
logout();
}
}

Execute thee application and after succcessful loginn you will loogout option as shown
below in Fig
gure 13.8:

Figurre 13.8: Successs Screen with


h Logout Feature

After clickiing logout linnk, user will be logged oout and redireected to loginn page as
shown in Figure 13.9

16
Custom Loggin Using
Security

Figure 13.9: Success Screeen with Logoout Feature

☞Check Yourr Progress 2

1)
1 Explain th
he usage of @SpringBootT
@ Test.

2)
2 Write the unit test case to execute it as a user w with RequestPPostProcessorr for
the URL pattern "/" which
w returns model
m a "message" and
attribuute with key as
value as "Hello
" World!!"

3)
3 Write thee unit test casse to execute it as a user with
w Annotattion for the U URL
pattern "/" which returrns model attrribute with kkey as "messaage" and valuue as
"Hello World!!"
W

4)
4 Write Unnit test case to test the custom logiin form havving "/signin"" as
loginProccessingUrl and
d "/" as defauultSuccessUrl.

17
Web Security
13.7 SUMMARY

Default Spring Security login form is not suitable for enterprises application since
developers do not have full control over css and form design. Spring Security provides
a way to configure custom login form in Spring Application. This unit has explained
the configuration of custom login form with an example and its execution.

Unit test plays a vital role to ensure the correctness of code, and it identifies every
defect that may arise before code is integrated with other modules. Many Spring Boot
annotations available for Integration testing, such as @SpringBootTest,
@AutoConfigureMockMvc, @WithMockUser has been explained.

Logout feature is an important feature from security perspective. At the end of this
unit, Spring provided logout support has been explained with configurable properties.

13.8 SOLUTIONS/ANSWERS TO CHECK YOUR


PROGRESS

☞Check Your Progress 1


1) By default, spring boot provides default login screen for spring security. In
enterprise application using default login screen, enterprise may not have full
control over design, processing URLs etc. Custom login form in Spring
Application is nothing but a simple html or jsp, like others web pages in java.
Sample custom login form is shown below-

<html>
<body>
<div>
<center>Custom Spring Login Form</center>
<form action="/signin" method="post">
<input name="username" type="text" placeholder="Enter Username" />
<input name="password" type="text" placeholder="Enter password" />
<input type="submit" />
</form>
</div>
<body>
<html>

Configuration for custom login page in spring security is very easy. We just
need to set the loginPage in FormLoginConfigurer object provided by
formLogin(). Sample Spring security configuration with custom login page is
shown below.

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
PasswordEncoderpasswordEncoder;
@Bean
18
Custom Login Using
public PasswordEncoderpasswordEncoder()
Security
{
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication().passwordEncoder(passwordEncoder).withUser("testuser")
.password(passwordEncoder.encode("user@123")).roles("USER").and().withUser("testadmin")
.password(passwordEncoder.encode("admin@123")).roles("USER", "ADMIN");
}
protected void configure(HttpSecurity http) throws Exception
{
http.csrf().disable()
.authorizeRequests()
.antMatchers("/customlogin").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/customlogin")
.loginProcessingUrl("/signin")
.defaultSuccessUrl("/", true)
.failureUrl("/customlogin?error=true");
}
}

2) loginPage("/dologin") instructs Spring Security to perform following-


• Whenever authentication is required, its being redirected to /dologin
• Login page is being rendered when /dologin is requested
• It will redired to /dologin?error(if default configuration is used for error)
in the case of authentication failure.
• On successful logout, it will redirect to /dologin?logout (In the case fo
default configuration used)
loginProcessingUrl(/signin) instruct the Spring Security to validate the
submitted credentials sent for /signinUrl. By default it redirects the user back
to the page from where user came. Request will neither be passed to Spring
MVC nor controller.

☞Check Your Progress 2


1) Spring-Boot provides @SpringBootTest annotation. This annotation provided
spring boot feature in the test module and works by creating the
ApplicationContext used in tests through SpringApplication. It starts the
embedded server, creates a web environment and enables @Test methods to
do integration testing.
By default, no server is started by @SpringBootTest. It provides several
options to add webEnvironment regarding how test cases should be executed.
• MOCK(Default): Loads a web ApplicationContext and provides a
mock web environment
• RANDOM_PORT: Loads a WebServerApplicationContext and
provides a real web environment. The embedded server is started and
listen to on a random port. This is the one that should be used for the
integration test
• DEFINED_PORT: Loads a WebServerApplicationContext and
provides a real web environment.
• NONE: Loads an ApplicationContext by using SpringApplication but
does not provide any web environment

19
Web Security
2) RequestPostProcessor interface is provided by Spring MVC Test. These
request processors can be used to modify the request. Many implementations
of RequestPostProcessorhas been provided by Spring Security to make testing
easy and efficient. Spring Security’s ReuestPostProcessor implementations
can be used by static import of as below:

Importstatic
org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPost
Processors.*;

Sample code to execute a unit test case with RequestPostProcessor is as


followings-
@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
classJavaBasedSpringSecurityApplicationTests
{
@Autowired
privateMockMvcmvc;
@Test
publicvoidtestAlreayLoggedInUserWithPostProcessor() throws Exception
{
mvc.perform(get("/").with(user("user"))).andExpect(authenticated().withUse
rname("user"))
.andExpect(authenticated().withRoles("USER"))
.andExpect(model().attribute("message","Hello World!!"));
}
}

3) Sample code with Annotation is as below:

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
classJavaBasedSpringSecurityApplicationTests
{
@Autowired
privateMockMvcmvc;
@Test
@WithMockUser()
publicvoidtestAlreadyLoggedInUserWithAnnotation() throws Exception
{
mvc.perform(get("/").andExpect(authenticated().withUsername("user"))
.andExpect(authenticated().withRoles("USER"))
.andExpect(model().attribute("message","Hello World!!"));
}
}

4) Sample code with Annotation is as below:


@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
classJavaBasedSpringSecurityApplicationTests
{
@Autowired
privateMockMvcmvc;
@Test
publicvoidtestFormLogin() throws Exception
{
mvc.perform(formLogin("/signin").user("testadmin").password("admin@123"))
.andExpect(status().isFound())
.andExpect(redirectedUrl("/")).andExpect(authenticated().withUsername("testadmin"))
.andExpect(authenticated().withRoles("ADMIN", "USER"));
}
}

20
Custom Login Using
Security
13.9 REFERENCES/FURTHER READING
• Craig Walls, “Spring Boot in action” Manning Publications, 2016.
(https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)
• Christian Bauer, Gavin King, and Gary Gregory, “Java Persistence with
Hibernate”,Manning Publications, 2015.
• Ethan Marcotte, “Responsive Web Design”, Jeffrey Zeldman Publication,
2011(http://nadin.miem.edu.ru/images_2015/responsive-web-design-2nd-
edition.pdf)
• Tomcy John, “Hands-On Spring Security 5 for Reactive Applications”,Packt
Publishing,2018
• https://docs.spring.io/spring-
security/site/docs/4.2.19.RELEASE/guides/html5/form-javaconfig.html
• https://www.baeldung.com/spring-security-login
• https://www.baeldung.com/spring-boot-testing
• https://docs.spring.io/spring-
framework/docs/current/reference/html/testing.html

21
UNIT 14 ROLE BASED LOGIN

Structure

14.0 Introduction
14.1 Objectives
14.2 Display User Id and Roles – Overview
14.2.1 User Details in a Controller
14.2.2 Spring view layer security and User Details using JSP Taglibs
14.3 Roles based Login Example
14.4 Restrict Access based on Roles
14.5 Testing the Application
14.5.1 Unit Tests in Spring Boot
14.5.1.1 Data Layer or Repository Layer testing with @DataJpaTest
14.5.1.2 Service Layer and Controller layer testing with @MockBean
14.6 Cross Site Request Forgery (CSRF)
14.7 Summary
14.8 Solutions/ Answer to Check Your Progress
14.9 References/Further Reading

14.0 INTRODUCTION
Role-Based access control (RBAC) allows us to define the accessibility based on
user’s roles and permissions. The roles in RBAC refer to the levels of access that user
has to the resource. Roles and permissions are used to make a resource secured from
unauthorized access. RBAC allows to define what end-users can perform at both
broad and granular levels. While using RBAC, resource access of the users is
analyzed, and users are grouped into roles based on common responsibilities and
needs. Each user into the system is assigned with one or more roles and one or more
permissions to each role. For an example, an admin can have permission to create a
new post and edit the already created post while an editor may have permission to edit
the post which already exists.

This Unit explains how to restrict resource access based on roles using the Spring
security. Most of the applications display the logged in user details. This unit
describes the various approaches to get logged in user details in controllers. It also
describes how to retrieve security related information at view layer in jsp.

The previous unit explained how to write integration test cases using annotations
provided by Spring. Good unit test cases make the codebase auto deployable and
production ready since codebase can be validated with the help of unit test cases. This
unit describes the unit test cases with available annotations in Spring.

Cross site request forgery, also known as CSRF or XSRF, is a type of attack in which
attackers trick a victim to make a request that utilizes their authentication or
authorization. The victim’s level of permission decides the impact of CSRF attack. In
the end of this Unit, Cross Site Request Forgery (CSRF) has been explained with an
example and the solution to avoid CSRF attack.

1
Web Security
14.1 OBJECTIVES

After going through this unit, you should be able to:


• explain Spring Security core component,
• describe logged in user detail in controllers,
• use Spring Security Expressions,
• describe and use Authentication and Authorization information at view layer,
• apply Role-Based Access Control and restrict the access based on roles, and
• describe Cross Site Request Forgery (CSRF).

14.2 DISPLAY USER ID AND ROLES –


OVERVIEW

Various core classes and interface available in spring security to get security context
are outlined. Spring Security core components are -
• SecurityContextHolder: A Class which provide access to SecurityContext
• SecurityContext: An Interface having Authentication and defining the
minimum-security information associated with request
• Authentication: Represents the Principal in Spring security-specific way.
The Spring Security Principal can only be retrieved as an Object from
Authentication and needs to be cast to the correct UserDetails instance as –

UserDetailsuserDetails = (UserDetails)
authentication.getPrincipal();
System.out.println("User has authorities: "+
userDetails.getAuthorities());

• GrantedAuthority: Having the application wide permissions granted to a


principal
• UserDetails:UserDetailshasthe required information to build an
Authentication object from application’s DAOs or other sources of security
data.
The following sections explain how to retrieve user details in Spring Security. There
are various ways to access logged-in user information in the Spring. Few ways are
described below.
14.2.1 User Details in a Controller
In a @Controller annotated bean, principal can be defined as a method argument, and
the Spring framework will resolve it correctly.

@Controller
public class UserSecurityController
{

@RequestMapping(value = "/username", method = RequestMethod.GET)


@ResponseBody
public String loggedInUserName(Principal principal)
{
return principal.getName();
}
}

2
Role Based Login
Instead of Principal, Authentication can be used. Authentication allows us to get the
granted authorities using getAuthorities() method while Spring Security principal can
only be retrieved as an Object and needs to be cast to the correct UserDetails instance.
Sample code is as following-

@Controller
public class UserSecurityController
{
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String loggeInUserName(Authentication authentication)
{
return authentication.getName();
}
}

User Details can be retrieved from HTTP request as -


@Controller
public class UserSecurityController
{

@RequestMapping(value = "/username", method = RequestMethod.GET)


@ResponseBody
public String loggeInUserName(HttpServletRequest request)
{
Principal principal = request.getUserPrincipal();
return principal.getName();
}
}

User Details can be retrieved in a Bean as –


Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();

14.2.2 Spring view layer security and User Details using JspTaglibs
Spring Security provides its own taglib for basic security support, such as retrieving
security information and applying security constraints at view layer jsp. To use spring
security features in jsp, you need to add the following tag library declaration into jsp-

<%@ tagliburi="http://www.springframework.org/security/tags" prefix="security"


%>

The tags provided by spring security to access security information and to secure the
view layer of the application are as below:
• Authorize Tag
• Authentication Tag
• Accesscontrollist Tag
• Csrfinput Tag
• CsrfMetaTags Tag

Authorize Tag: This tag supports to secure information based on user’s role or
permission to access a URL. Authorize tag support two types of attributes.
• access
• url

In an application, view layer might need to display certain information based on user’s
role or based on authentication state. An example for the same is shown below.
<security:authorize access="!isAuthenticated()">
Login
</security:authorize>
<security:authorize access="isAuthenticated()">

3
Web Security Logout
</security:authorize>

Further, we can also display certain information based on user role as-

<security:authorize access="hasRole('ADMIN')">
Delete Users
</security:authorize>

Value for access can be any of Spring Security Expression as below-


• hasAnyRole('ADMIN','USER') returns true if the current user has any of the
listed roles
• isAnonymous() returns true if the current principal is an anonymous user
• isRememberMe() returns true if the current principal is a remember-me user
• isFullyAuthenticated() returns true if the user is authenticated and is neither
anonymous nor a remember-me user

Using url attribute in authorize tag, at view layer we can check weather user is
authorized to send request to certain URL:
<security:authorizeurl="/inventoryManagement">
<a href="/inventoryManagement">Manage Inventory</a>
</security:authorize>

Authentication Tag: This tag is not used to implement security but it allows access
to the current Authentication object stored in the security context. It renders a property
of the object directly in the JSP. If the principal property of the Authentication is an
instance of Spring Security’s UserDetails object, then username and roles can be
accessed as –

• <security:authentication property=”principal.username” />


• <security:authentication property=”principal.authorities” />

Accesscontrollist Tag: This tag is used with Spring Security’s ACL module. It
checks list of required permissions for the specified domains. It executes only if
current user has all the permissions.

Csrfinput Tag: For this tag to work, csrf protection should be enabled in spring
application. If csrf is enabled, spring security inserts a csrf hidden form input inside
<form:form> tag. But in case if we want to use html <form></form>, we need to put
csrfinput tag inside <form> to create CSRF token as below –
<form method=”post” action=”/some/action”>
<security:csrfInput />
Name:<input type=”text” name=”username” />

</form>

CsrfMetaTags Tag: If we want to access CSRF token in javascript, we have to


insert token as a meta tag. For this tag to work, csrf protection should be enabled in
Spring Application.
<html>
<head>
<title>JavaScript with CSRF Protection</title>
<security:csrfMetaTags />
<script type=”text/javascript” language=”javascript”>
var csrfParameter =
$(“meta[name=’_csrf_parameter’]”).attr(“content”);
var csrfHeader = $(“meta[name=’_csrf_header’]”).attr(“content”);
var csrfToken = $(“meta[name=’_csrf’]”).attr(“content”);
</script>
</head>
<body>

4
Role Based Login
</body>
</html>

☞Check Your Progress 1


1) What are Authorities in Authentication object?
…………………………………………………………………………………
…………………………………………………………………………………
………………………………………............…………………………………
…………………………………………………………………………………
2) Write the code to get logged in user’s username from HttpServletRequest in a
controller.
…………………………………………………………………………………
…………………………………………………………………………………
………………………………………............…………………………………
…………………………………………………………………………………

3) Explain with an example to display username and roles on jsp.


…………………………………………………………………………………
…………………………………………………………………………………
………………………………………............…………………………………
…………………………………………………………………………………

14.3 ROLES BASED LOGIN EXAMPLE

This section describes role-based login using Spring Security. Role based login means
redirecting users to different URLs upon successful login according to the assigned
role to the logged-in user. The following section explains an example with three types
of users as Admin, Editor and normal User. Once user successfully logged into the
system, based on role user will be redirected to its own url as –

• Admin will be redirected to /admin


• Editor will be redirected to /editor
• User will be redirected to /home
In previous spring security configurations, the success URL on successful
authentication was configured using defaultSuccessUrl(Sring s). With the use of
Spring defaultSuccessUrl(“/homePage”), every user will be redirected to homepage
url irrespective of role. To have more control over the authentication success
mechanism, Spring Security provides a component that has the direct responsibility
of deciding what to do after a successful authentication – the
AuthenticationSuccessHandler.
AuthenticationSuccessHandleris an Interface and Spring provides
SimpleUrlAuthenticationSuccessHandler, which implement this interface. For role
based login, you need to configure
successHandler(AuthenticationSuccessHandlersuccessHandler) instead of
defaultSuccessUrl(Sring s). For custom success handler, you have two approaches.

1. Implement AuthenticationSuccessHandler interface to provide custom


success handler.
5
Web Security
2. ExtendSimpleUrlAuthenticationSuccessHandler class and override the
handle() method to provide the logic.
The below code sample is for custom success handler using approach 2.
publicclassCustomSuccessHandlerextendsSimpleUrlAuthenticationSuccessHandler
{
privateRedirectStrategyredirectStrategy = newDefaultRedirectStrategy();

@Override
protectedvoidhandle(HttpServletRequestrequest, HttpServletResponseresponse,
Authentication authentication)throwsIOException
{
String targetUrl = determineTargetUrl(authentication);

if (response.isCommitted())
{
System.out.println("Can't redirect");
return;
}

redirectStrategy.sendRedirect(request, response, targetUrl);


}

/*
* This method extracts the roles of currently logged‐in user and returns
* appropriate URL according to his/her role.
*/
protected String determineTargetUrl(Authentication authentication)
{
String url = "";
Map<String, String>roleTargetUrlMap = new HashMap<>();
roleTargetUrlMap.put("ROLE_USER", "/home");
roleTargetUrlMap.put("ROLE_ADMIN", "/admin");
roleTargetUrlMap.put("ROLE_Editor", "/editor");

Collection<? extendsGrantedAuthority>authorities =
authentication.getAuthorities();
List<String>roles = newArrayList<String>();
for (GrantedAuthoritya :authorities)
{
roles.add(a.getAuthority());
}

if (isAdmin(roles))
{
url = "/admin";
}
elseif (isEditor(roles))
{
url = "/editor";
}
elseif (isUser(roles))
{
url = "/home";
}
else
{
url = "/accessDenied";
}

returnurl;
}

privatebooleanisUser(List<String>roles)
{
if (roles.contains("ROLE_USER"))
{
returntrue;
}
returnfalse;
}

privatebooleanisAdmin(List<String>roles)
{
if (roles.contains("ROLE_ADMIN"))

6
Role Based Login
{
returntrue;
}
returnfalse;
}

privatebooleanisEditor(List<String>roles)
{
if (roles.contains("ROLE_EDITOR"))
{
returntrue;
}
returnfalse;
}

publicvoidsetRedirectStrategy(RedirectStrategyredirectStrategy)
{
this.redirectStrategy = redirectStrategy;
}

protectedRedirectStrategygetRedirectStrategy()
{
returnredirectStrategy;
}

Above class overrides the handle method and redirects the user based on his role as
follows –

• Admin will be redirected to /admin


• Editor will be redirected to /editor
• User will be redirected to /home

Spring Security Configuration for role-based login using successHandler is shown


below.
@Override
protected void configure(final HttpSecurity http) throws Exception
{
http
.authorizeRequests()
// endpoints
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.successHandler(customSuccessHandler())
// other configuration
}

14.4 RESTRICT ACCESS BASED ON ROLES

Role-based access control (RBAC) is a mechanism that restricts system access. RBAC
accomplishes this by assigning one or more "roles" to each user and giving each role
different permissions. To protect sensitive data, mostly large-scale organizations use
role-based access control to provide their employees with varying levels of access
based on their roles and responsibilities.

The previous unit explained to secure the application using authentication and URL
level security along with restrictions based on roles. The following sections explain to
secure the application at service layer. Method-level security is used to restrict access
based on Role. The last of this section explains to add security at view layer i.e.jsp.

Spring allows us to implement the security at the method level. Security applied at the
method level restricts the unauthorized user to access the resource mapped by the
method. How to enable method level security and restrict the method accessed based
on role is explained below.
7
Web Security
@EnableGlobalMethodSecurity
To Enable the method level security in spring we need to enable global method
security as below:
@Configuration
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class MethodSecurityConfig
extends GlobalMethodSecurityConfiguration
{
}

• The prePostEnabled property enables Spring Security pre/post annotations


• The securedEnabled property determines if the @Secured annotation should
be enabled
• The jsr250Enabled property allows us to use the @RoleAllowed annotation
@Secured

@Secured annotation is used to implement method level security based on Role. This
annotation accepts list of allowed roles to be permitted. Hence, a user can access a
method if he/she has been assigned at least one role into the list.
@Secured("ROLE_USER")
public String getUsername()
{
SecurityContextsecurityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}

User who is having role as ROLE_USER can execute the above method.
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public booleanisValidUsername(String username)
{
return userRoleRepository.isValidUsername(username);
}

A user having Either "ROLE_USER" OR "ROLE_ADMIN" can invoke above


method.

@RolesAllowed Annotation
The @RolesAllowed annotation is the JSR-250’s equivalent annotation of the
@Secured annotation. Basically, we can use the @RolesAllowed annotation in a
similar way as @Secured.
@RolesAllowed("ROLE_USER")
public String getUsername()
{
//...
}

@RolesAllowed({ "ROLE_USER", "ROLE_ADMIN" })


public booleanisValidUsername(String username)
{
//...
}

@PreAuthorize and @PostAuthorize Annotations

8
Role Based Login
Both @PreAuthorize and @PostAuthorize annotations provide expression-based
access control. The @PreAuthorize annotation checks the given expression before
entering into the method, whereas, the @PostAuthorize annotation verifies it after the
execution of the method and could alter the result.

@PreAuthorize("hasRole('ROLE_VIEWER')")
public String getUsername()
{
//...
}
@PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
public booleanisValidUsername(String username)
{
//...
}
@PreAuthorize("#username == authentication.principal.username")
public String getMyRoles(String username)
{
//...
}

getMyRoles() method can be invoked by a user only if the value of the


argument username is the same as current principal's username

@PostAuthorize annotation is similar to @PreAuthorize so it can be replaced with


@PostAuthorize.

Restriction at view layer


Access restriction based on role at view layer using spring security authorize tag is
already explained. For details check the Section 14.2. Example is as follows-
<security:authorize access="!isAuthenticated()">
Login
</security:authorize>
<security:authorize access="isAuthenticated()">
Logout
</security:authorize>

Further we can also display certain information based on user role as-
<security:authorize access="hasRole('ADMIN')">
Delete Users
</security:authorize>

☞Check Your Progress 2

1) Describe role-based login. Write the sample code to configure the role-based
login.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………
2) What is Role Based Access Control (RBAC)? Write the sample configuration
code to restrict the URL access based on role.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
9
Web Security
…………………………………………………………………………………
………………………………
3) Explain @Secured and @RolesAllowed. What is the difference between
them?
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………
4) Which are all spring security annotations allowed to use SpEL?
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………
5) What's the difference between @Secured and @PreAuthorize in spring
security?
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………

6) Explain spring security tag which restricts the access based on roles in jsp.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………

14.5 TESTING THE APPLICATION


This section writes a complete example with three types of users as Admin, Editor and
User. UserType, Role and functionality has been defined in the table as follows:

User Type Role Functionality Landing Page


Admin ROLE_ADMIN, Admin can create or /admin
ROLE_EDITOR edit a post/messages.
Editor ROLE_EDITOR Editor can only edit the /editor
post/messages.
User ROLE_USER User can only view the /home
post/messages.

In units 12 and 13, In-Memory authentication has been configured. Here JDBC
authentication with mysql database has been explained. Tools and software required
10
Role Based Login
to write the code easily, manage the spring dependencies and execute the application
is as -
• Java 8 or above is required
• Maven
• Eclipse IDE
• Mysql
• Hibernate
• JPA

Directory Structure for Spring Project in eclipse is shown below. A few of the code is
shown in Figure 14.1.

Figure 14.1: Project Folder Structure In Eclipse IDE

Spring Security Configuration classes in config packages –


customSuccessHandler is already explained above for role-based login.

packagecom.ignou.javabasedspringsecurity.config;

@Component
publicclassCustomSuccessHandlerextendsSimpleUrlAuthenticationSuccessHandler
{
privateRedirectStrategyredirectStrategy = newDefaultRedirectStrategy();

@Override
protectedvoidhandle(HttpServletRequestrequest, HttpServletResponseresponse,
Authentication authentication)throwsIOException
{
String targetUrl = determineTargetUrl(authentication);

if (response.isCommitted())
{
System.out.println("Can't redirect");
return;
}

11
Web Security
redirectStrategy.sendRedirect(request, response, targetUrl);
}

/*
* This method extracts the roles of currently logged‐in user and returns
* appropriate URL according to his/her role.
*/
protected String determineTargetUrl(Authentication authentication)
{
String url = "";
Map<String, String>roleTargetUrlMap = new HashMap<>();
roleTargetUrlMap.put("ROLE_USER", "/home");
roleTargetUrlMap.put("ROLE_ADMIN", "/admin");
roleTargetUrlMap.put("ROLE_Editor", "/editor");

Collection<? extendsGrantedAuthority>authorities =
authentication.getAuthorities();

List<String>roles = newArrayList<String>();

for (GrantedAuthoritya :authorities)


{
roles.add(a.getAuthority());
}

if (isAdmin(roles))
{
url = "/admin";
}
elseif (isEditor(roles))
{
url = "/editor";
}
elseif (isUser(roles))
{
url = "/home";
}
else
{
url = "/accessDenied";
}

returnurl;
}

privatebooleanisUser(List<String>roles)
{
if (roles.contains("ROLE_USER"))
{
returntrue;
}
returnfalse;
}

privatebooleanisAdmin(List<String>roles)
{
if (roles.contains("ROLE_ADMIN"))
{
returntrue;
}
returnfalse;
}

privatebooleanisEditor(List<String>roles)
{
if (roles.contains("ROLE_EDITOR"))
{
returntrue;
}
returnfalse;
}

publicvoidsetRedirectStrategy(RedirectStrategyredirectStrategy)
{
this.redirectStrategy = redirectStrategy;
}

12
Role Based Login
protectedRedirectStrategygetRedirectStrategy()
{
returnredirectStrategy;
}

SecurityConfig.java
Complete Security configuration with successHandler(customSuccessHandler) is as
below-
packagecom.ignou.javabasedspringsecurity.config;

@EnableWebSecurity
publicclassSecurityConfigextendsWebSecurityConfigurerAdapter
{

@Autowired
privateUserDetailsServicecustomUserService;

@Autowired
privateCustomSuccessHandlercustomSuccessHandler;

@Autowired
PasswordEncoderpasswordEncoder;

@Bean
publicPasswordEncoderpasswordEncoder()
{
returnnewBCryptPasswordEncoder();
}

@Override
protectedvoidconfigure(AuthenticationManagerBuilderauth) throws Exception
{
auth
.userDetailsService(customUserService)
.passwordEncoder(passwordEncoder);
}

protectedvoidconfigure(HttpSecurityhttp) throws Exception


{

http.csrf().disable()
.authorizeRequests()
.antMatchers("/customlogin*").permitAll()
.antMatchers("/","/home").hasRole("USER")
.antMatchers("/editor/**").hasRole("EDITOR")
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/edit/**").hasAnyRole("ADMIN","EDITOR")
.antMatchers("/create/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/customlogin")
.loginProcessingUrl("/signin")
.successHandler(customSuccessHandler)
.failureUrl("/customlogin?error=true")
.and()
.logout()
.and().exceptionHandling().accessDeniedPage("/accessdenied");;
}

Controller package Classes


LoginController.java
packagecom.ignou.javabasedspringsecurity.controller;

@Controller
@RequestMapping(value="/customlogin")

13
Web Security publicclassLoginController
{

@GetMapping
public String login()
{
return"customlogin";
}

HomeController.java
packagecom.ignou.javabasedspringsecurity.controller;

@Controller
publicclassHomeController
{

privatestatic Map<Long, String>msgs = new HashMap<>();


privatestaticlongmsgCount = 0;

static
{
msgs.put(new Long(1), "Java Cryptography Architecture (JCA)");
msgs.put(new Long(2), "Java Secure Socket Extension (JSSE)");
msgCount = 2;
}

@RequestMapping(value="/home", method=RequestMethod.GET)
public String user(Model model)
{
model.addAttribute("msgs", msgs);
return"user";
}

@RequestMapping(value="/editor", method=RequestMethod.GET)
public String editor()
{
return"editor";
}

@RequestMapping(value="/admin", method=RequestMethod.GET)
public String admin()
{

return"admin";
}

@RequestMapping(value="/edit", method=RequestMethod.GET)
public String edit(Model model)
{
model.addAttribute("msgs", msgs);
return"edit";
}

@RequestMapping(value="/edit", method=RequestMethod.POST)
public String editPost(@ModelAttributeMsgPostmsgPost, Model model)
{
longmsgId = msgPost.getId();
if (msgs.get(msgId) != null)
{
msgs.put(msgPost.getId(), msgPost.getContent());
}
model.addAttribute("msgs",msgs);
return"edit";
}

@RequestMapping(value="/create", method=RequestMethod.POST)
publicStringcreatePost(@ModelAttributeMsgPostmsgPost, Model model)
{
msgCount += 1;
msgs.put(msgCount, msgPost.getContent());
model.addAttribute("msgs",msgs);
return "edit";
}

14
Role Based Login
}

Service package classes


UserService.java

packagecom.ignou.javabasedspringsecurity.service;

@Service
@Transactional
publicclassUserServiceimplementsUserDetailsService
{

@Autowired
privateUserRepositoryuserRepository;

@Override
publicUserDetailsloadUserByUsername(String email)
throwsUsernameNotFoundException
{

User user = userRepository.findByEmail(email).orElseThrow(()‐


>newUsernameNotFoundException(email + "not found"));
returnneworg.springframework.security.core.userdetails.User(user.getEmail(),
user.getPassword(),getAuthorities(user));
}

privatestatic Collection<? extendsGrantedAuthority>getAuthorities(User user)


{
String[] userRoles = user.getRoles().stream().map((role) ‐>
role.getName()).toArray(String[]::new);
Stream.of(userRoles).forEach(System.out::print);
Collection<GrantedAuthority>authorities =
AuthorityUtils.createAuthorityList(userRoles);
returnauthorities;
}

Jsp in WEB-INF/views
Note: customlogin.jsp has been used same as explained in Unit 13.
admin.jsp

<%@tagliburi="http://www.springframework.org/security/tags"prefix="security"%>
<%@pagelanguage="java"contentType="text/html; charset=ISO‐8859‐1"pageEncoding="ISO‐
8859‐1"%>

<html>
<head>
<metahttp‐equiv="Content‐Type"content="text/html; charset=ISO‐8859‐1">
<title>Admin page</title>
</head>
<body>
Dear <strong><security:authenticationproperty="principal.username"/></strong>,
Welcome to Admin Page.
<p>You are having roles as
<strong><security:authenticationproperty="principal.authorities"/></strong>
<p><ahref="/edit">Edit</a>
<p><ahref="/logout">Logout</a>
</body>
</html>

editor.jsp
<%@tagliburi="http://www.springframework.org/security/tags"prefix="security"%>
<%@pagelanguage="java"contentType="text/html; charset=ISO‐8859‐1"pageEncoding="ISO‐
8859‐1"%>

<html>
<head>
<metahttp‐equiv="Content‐Type"content="text/html; charset=ISO‐8859‐1">
<title>Editor page</title>
</head>

15
Web Security <body>
Dear <strong><security:authenticationproperty="principal.username"/></strong>,
Welcome to Editor Page.
<p>You are having roles as
<strong><security:authenticationproperty="principal.authorities"/></strong>
<p><ahref="/edit">Edit</a>
<p><ahref="/logout">Logout</a>
</body>
</html>

user.jsp
<%@tagliburi="http://www.springframework.org/security/tags"
prefix="security"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<%@pagelanguage="java"contentType="text/html; charset=ISO‐8859‐1"
pageEncoding="ISO‐8859‐1"%>

<html>
<head>
<metahttp‐equiv="Content‐Type"content="text/html; charset=ISO‐8859‐1">
<title>Welcome page</title>
<style>
table.border,th.border,td.border
{
margin‐left: auto;
margin‐right: auto;
border: 1px solid black;
}
</style>
</head>
<body>
Dear
<strong><security:authenticationproperty="principal.username"/></strong>,
Welcome to Home Page.
<p>
You are having roles as <strong><security:authentication
property="principal.authorities"/></strong>
<tableclass="border">
<tr>
<thclass="border">Msg Id</th>
<thclass="border">Message</th>
</tr>
<c:forEachitems="${msgs}"var="msg">
<tr>
<tdclass="border">${msg.key}</td>
<tdclass="border">${msg.value}</td>
</tr>
</c:forEach>
</table>
<p>
<ahref="/logout">Logout</a>
</body>
</html>

Execute the project either from eclipse or command line. After successful execution of
the application, security configured application can be accessed using browser on
localhost:8080
The following users are configured for the testing of role-based login example.

• Admin – UserName: [email protected]: admin


• Editor – UserName: [email protected]: editor
• User – UserName: [email protected]: user
Execution Result

If a user tries to access localhost:8080 and the user is not logged in, spring will
redirect to the user on localhost:8080/customlogin as shown in Figure 14.2.

16
Role Based
d Login

Figure 14.22: Spring Secu


urity Custom L
Login Page

min Login (Shown in Figure 14.3.


Adm

Figuree14.3: Admin User Home Screen

On click
c on Edit button
b admin will see the below
b screen (Figure 14.4)). Admin has
only permission too create new messages as explained
e thee feature of eaach user in thee
nning of this section.
begin

Figure14.4: Edit
E and Creatte Screen For Admin User

17
7
Web Security
S
When Editoor logs in, youu will get the below
b screenn (Figure 14.5).

Figgure 14.5: Ediitor Role Userr Home Screen


n

On click on n Edit buttonn, editor can only edit thee already exissting messages. Check
edit.jsp file in which <security:authoorize access="hasRole('A ADMIN')">seecurity tag
has been useed to allow onnly Admin usser to create nnew messagess (Figure 14.66).

Figu
ure14.6: Edit Screen
S from E
Editor Role Usser

When a userr logs in, he/sshe will get thhe below screen(Figure 14.7) as you cann see that
normal userr does not havve any option to edit the message.

F
Figure14.7: General
G User H
Home Screen

14.5.1 Un
nit Tests in Spring Boot
Production-ready code shhould have well-written
w U test casess as well as Inntegration
Unit
Test. Good unit test casees should hav ve code coverrage of 80% or more. Wriiting good
unit test casses is an art, aand sometimees it’s difficuult to write goood code coverage unit
test cases. Spring
S providees an efficiennt way to writee Unit Test caases as well Inntegration
Test cases. In
I Unit 13, vaarious annotattions have beeen described for Integratioon Testing
18
Role Based Login
with examples. @SpringBootTest is used for integration testing, and it is useful when
we need to bootstrap the entire container. This section will describe the best practices
to write unit test cases as well as available annotations will be described.

@SpringBootTest

@SpringBootTest

class StudentEnrollmentUseCaseTest

@Autowired

private EnrollmentServiceenrollmentService;

@Test

void studentEnrollemnt()

Student student = new Student("Jack", "[email protected]");

Student enrolledStudent = enrollmentService.enroll(student);

assertThat(enrolledStudent.getEnrollmentNo()).isNotNull();

A good test case takes only few milliseconds, but the above code might take 3-4
seconds. The above test case execution takes only a few milliseconds, and the rest of
the 4 seconds is being taken by @SpringBootTest to set up the complete Spring Boot
Application Context. In the above test case complete Spring Boot Application Context
has been set up to autowire the EnrollmentService instance into the test case. Unit test
cases set up time can be reduced a lot with the use of Mock instances and appropriate
annotation instead of @SpringBootTest.
A well-structured web application consists of multiple layer such as Controllers,
Services and Repository. Controllers are responsible to handle the client request
forwarded by dispatcherServlet. The controller uses Service classes for business logic
and Service classes uses Repository classes to interact with databases. Each layer can
be tested independently with Unit test cases. The following section will describe the
important annotations available in Spring to write the good unit test with a few
milliseconds of execution time.

14.5.1.1 Data Layer or Repository Layer testing with


@DataJpaTest
An entity class named as Student which is having properties as id and name
@Entity
@Table(name = "student")
public class Student
{
19
Web Security @Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Size(min = 3, max = 20)


private String name;

// constructors, getters and setters


}

StudentRepository with Spring Data Jpa


@Repository
public interface StudentRepository extends JpaRepository<Student, Long>
{

public Student findById(Long id);


public List<Student>findByName(String name);
}

Persistence layer unit test cases code set up shown below


@DataJpaTest
public class UserRepositoryTest

@Autowired
private TestEntityManagerentityManager;

@Autowired
private UserRepositoryuserRepository;
// test cases
}

@DataJpaTest focuses only on JPA components needed for testing the persistence
layer. Instead of initializing the complete Spring Boot Application Context, as in the
case of @SpringBootTest, initializes only the required configuration relevant to JPA
tests. Thus, Unit test case set-up time is very less. @DataJpaTest does the following
configurations.\

• setting Hibernate, Spring Data, and the DataSource


• configuring H2, an in-memory database
• turning on SQL logging
• performing an @EntityScan

A complete example of persistence layer unit test case using @DataJpaTest

@DataJpaTest
publicclassUserRepositoryTest
{

@Autowired
privateTestEntityManagerentityManager;

@Autowired
privateUserRepositoryuserRepository;

@BeforeEach
privatevoidsetUp()
{
User user = newUser();
user.setEmail("[email protected]");
user.setName("Admin");
user.setPassword("admin@123");
entityManager.persist(user);
entityManager.flush();
}
20
Role Based Login
@Test
publicvoidfindByEmailTest()
{

String email = "[email protected]";

// Call userRepository to get user record


Optional<User>found = userRepository.findByEmail(email);
String getUserEmail = found.get().getEmail();

assertThat(getUserEmail).isEqualTo(email);
}

14.5.1.2 Service Layer and Controller layer testing with@MockBean


In MVC project, Controllers are dependent on Services, and Services are dependent
on Repositories. However, Controllers and Services should be testable without
knowing the complete implementation of dependencies.
@MockBean can be used to mock the required dependency. Spring boot @MockBean
annotation used to add mocks to a Spring ApplicationContext.

A complete example of Service layer unit test case with @MockBean


@ExtendWith(SpringExtension.class)
publicclassUserServiceTest
{
@TestConfiguration
staticclassUserServiceTestConfiguration
{

@Bean
publicUserServiceuserService()
{
returnnewUserService();
}
}
@MockBean
privateUserRepositoryuserRepository;
@Autowired
privateUserServiceuserService;
@BeforeEach
publicvoidsetUp()
{
User user = newUser();
List<Role>roleList = newArrayList<>();

Role adminRole = newRole();


adminRole.setName("Admin");
Role editorRole = newRole();
editorRole.setName("Editor");
roleList.add(adminRole);
roleList.add(editorRole);

user.setEmail("[email protected]");
user.setName("Admin");
user.setPassword("admin@123");
user.setRoles(roleList);

Mockito.when(userRepository.findByEmail(user.getEmail())).thenReturn(Optional.of(u
ser));
}

@Test
publicvoidwhenValidName_thenUserShouldBeFoundTest()
{
String email = "[email protected]";
UserDetailsfound = userService.loadUserByUsername(email);
assertThat(found.getUsername()).isEqualTo(email);
}
}

21
Web Security

All unit test cases can be executed by right click on the project -> Run As -> Junit
Test as shown below screenshot (Figure 14.8).

Figure 14.8: Unit Test Case Execution From Eclipse IDE

Successful execution of Unit Test case will output the following (Figure 14.9). As you
can see all test cases are passed,which is shown by the green tick and green progress
bar.

Figure14.9: Unit Test Cases Execution Status

22
Role Based Login

14.6 CROSS SITE REQUEST FORGERY (CSRF)


In Unit 12, section 12.3 CSRF concept and ways of its execution have been
described.CSRF is a type of attack in which attackers trick a victim into making a
request that utilizes their authentication or authorization. The victim’s level of
permission decides the impact of CSRF attack. Execution of CSRF attack consists of
mainly two-part.
• Trick the victim into clicking a link or loading a web page
• Sending a crafted, legitimate-looking request from victim’s browser to
website
For a better understanding of CSRF, let us have a look at a concrete example of bank
money transfer.
Suppose that bank’s website provides a form to transfer money from the currently
logged in user to another bank account.
For example, the HTTP request might look like:

POST /transfer HTTP/1.1


Host: bank.example.com
Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly
Content-Type: application/x-www-form-urlencoded

amount=100.00&account=1234

Now consider that user authenticate to bank’s website and then, without logging out,
visit an evil website. The evil website contains an HTML page with the following
form:
<form action="https://bank.example.com/transfer" method="post">
<input type="hidden"
name="amount"
value="100.00"/>
<input type="hidden"
name="account"
value="evilsAccountNumber"/>
<input type="submit"
value="Win Money!"/>
</form>

User like to win money, and he clicks on the Win Money! Button. As user clicks on
button, unintentionally he transferred $100 to a malicious user. While evil website can
not see your cookies, but the browser sent the cookie associated with bank along with
the request.
The whole process can be automated using JavaScript, and onPage load script can be
executed to perform CSRF. The most popular method to prevent Cross-site Request
Forgery is to use a randomly generated token that is associated with a particular user
and that is sent as a hidden value in every state-changing form in the web app. This
token, called an anti-CSRF token (often abbreviated as CSRF token) or a synchronizer
token. When a request is submitted, the server must look up the expected value for the
parameter and compare it against the actual value in the request. If the values do not
match, the request should fail.
Spring Security CSRF Protection

Necessary steps to use Spring Security’s CSRF protection are as follows-


• Use proper HTTP verb
• Configure CSRF protection
23
Web Security
• Include the CSRF token

Use Proper HTTP Verb

The use of proper HTTP verb plays a vital role to protect a website against CSRF
attack. We need to be assured that the application is using PATCH, POST, PUT,
and/or DELETE for anything that modifies state. This is not a limitation of Spring
Security’s support, but instead a general requirement for proper CSRF prevention.

Configure CSRF protection

By default, CSRF protection is enabled in Spring java configuration. It can be


disabled as below:

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable();
}
}

Include the CSRF Token

The last step is to include the CSRF token all PATCH, POST, PUT, and DELETE
methods. Csrfinput Tag is described into section 14.2 and used it in edit.jsp in Section
14.5. In edit.jsp we used two approach to include csrf token as follows-
• <input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
• <security:csrfInput/>

Following example will give you experimental and real feel of CSRF attack in the
application executed in Section 14.5. Steps to perform CSRF attack simulation are as
below-
Step 1: To simulate the evil website create a html file with below content. You can
give it any name. Let us assume that filename is as evil.html and save this file to any
location.

<html>
<body>
<form action="http://localhost:8080/edit" method="POST" id="attack">
<input type="hidden" name="id" value="2">
<input type="hidden" name="content" value="Hackers Msg">
<input type="button"
onclick="document.getElementById('attack').submit()" value="Click me to Won
Prize"></input>
</form>
</body>
</html>

Step 2: Start the application tested into Section 14.5 and login as Admin or Editor
user. Here consideration is that Admin user do login into the system (Figure 14.10).
24
Role Based
d Login

Figure 144.10: Admin Role


R User Hom
me Screen

Step 3: For CSR RF attack to place


p User must
m be loggeed in to the sy
ystem. In steep 2,
Admmin has logged in. Now op pen evil.htmll in the same browser in which
w admin has
loggeed and clickk on the buttton. Once yoou click the button, the following
f scrreen
(Figu
ure 14.11) willl appear with
h Hacker msgg.

F
Figure 14.11: CSRF Attack
k

As you
y can see in i above screeen that maliicious user hhas edited thee msg. Close the
evil.h
html. From admin
a y will find the
login, click on eddit link, and there also you
modiified msg by malicious
m useer.
Noww we will makke the requireed changes too protect the website
w again
nst CSRF attaacks.
We have
h configurred security inn Security.javva file. You ccan check thaat csrf is disabbled
theree. You can ju ust remove csrf.disable()
c and automattically csrf prrotection will be
enabled. We havee already inclluded token in i jsp so no nneed to makee any changees in
jsp. Perform
P all th
he steps againn, and this tim
me in step 3 yyou will get the below scrreen
(Figuure 14.12) .

F
Figure 14.12: Website
W Proteected Against CSRF Attack
k

25
5
Web Security
As you can see now,the edit is being denied since we have enabled CSRF protection
and the malicious user is unable to edit or create the msg.

You can try to create a new message as a malicious user by disabling csrf protection.
Make the changes in evil.html.

☞Check Your Progress 3

1) Explain @SpringBootTest. Why is it not suitable for unit test cases?


…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………

2) Describe @MockBean with an example.


…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………
3) What is Cross Site Request Forgery (CSRF)? What is the necessary condition
for CSRF to take place?
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………
4) How do you make the Spring Application secured against CSRF attack?
Discuss the necessary steps along with sample code to enable CSRF in
Spring.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………

14.7 SUMMARY
In the Unit, you learnt various core components of Spring Security such as
SecurityContextHolder, SecurityContext, Authentication, Principal etc. Next you
26
Role Based Login
learnt how to get logged in user details in controllers using Authentication and
Principal and many more.
Gradually you learnt various Spring Security tags such as authorize, authentication,
csrfInput etc. to secure the view layer jsp and display the user details on jsp using
these tags.
Next you learnt about role-based login. In role-based login you learnt to redirect users
on different URL based on assigned role of the User. You learnt about
AuthenticationSuccessHandler and configuration using successHandler().
This Unit has described how to secure the service layer methods using various
annotations such as @Secured, @RoleAllowed, @PreAuthorize, @PostAuthorize etc.
You executed a complete application in which you learnt how to implement the above
concept programmatically. In the lastof the unit, you learnt how to enable CSRF
protection in Spring application. You got the real feel of CSRF attack with executed
example, and this will enable you to understand CSRF attack easily.

14.8 SOLUTIONS/ ANSWER TO CHECK YOUR


PROGRESS

☞Check Your Progress 1


1) All Authentication implementations in Spring is having a list of
GrantedAuthority objects. These represent the authorities that have been
granted to the principal. AuthenticationManager inserts all the
GrantedAuthority objects into the Authentication Object. Hierarichal
Structure is as below (Figure 14.13).

Figure 14.13: Authorities in Authentication object

2) UserName using HttpServletRequest can be accessed as follows-


@Controller
public class UserSecurityController
{

@RequestMapping(value = "/username", method = RequestMethod.GET)


@ResponseBody
public String loggeInUserName(HttpServletRequest request)
{
Principal principal = request.getUserPrincipal();
return principal.getName();
}
}

3) Authentication tag can be used get logged in user details and authorities on jsp
as below-
27
Web Security
• <security:authentication property="principal.username" />
• <security:authentication property="principal.authorities" />
For details refer authentication tag in the Section 14.2
☞Check Your Progress 2

1) AuthenticationSuccessHandleris an Interface, and Spring provides


SimpleUrlAuthenticationSuccessHandler, which implement this interface. To
create the custom success handler we can extend the
SimpleUrlAuthenticationSuccessHandler class and can override the handle()
method to provide the required logic to for redirect URL. For role based login,
you need to configure
successHandler(AuthenticationSuccessHandlersuccessHandler) instead of
defaultSuccessUrl(Sring s). Configuration for custom success handler is as
below:

@Override
protected void configure(final HttpSecurity http) throws Exception
{
http
.authorizeRequests()
// endpoints
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.successHandler(customSuccessHandler())
// other configuration
}

2) For RBAC refer section 14.4. Configuration to restrict the URL access based
on role is as below-

protectedvoidconfigure(HttpSecurityhttp) throws Exception


{

http.csrf().disable()
.authorizeRequests()
.antMatchers("/customlogin*").permitAll()
.antMatchers("/","/home").hasRole("USER")
.antMatchers("/editor/**").hasRole("EDITOR")
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/edit/**").hasAnyRole("ADMIN","EDITOR")
.antMatchers("/create/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/customlogin")
.loginProcessingUrl("/signin")
.successHandler(customSuccessHandler)
.failureUrl("/customlogin?error=true")
.and()
.logout()
.and().exceptionHandling().accessDeniedPage("/accessdenied");;
}

In above configuration
URL pattern “/” and “/home” is accessible only to user which is having role
as ROLE_USER.
URL pattern “/editor/**” is accessible only to user having role as
ROLE_EDITOR
URL pattern “/admin/**” is accessible only to user having role as
ROLE_ADMIN

28
Role Based Login
URL pattern “/edit/**” is accessible to user having role as ROLE_ADMIN or
ROLE_EDITOR
URL pattern “/create/**” is permissible only to user having role as
ROLE_ADMIN

3) @Secured and @RolesAllowed both annotations provide method-level


security into Spring Beans. @Secured is Spring Security annotation from
version 2.0 onwards Spring Security. But @RolesAllowed is JSR 250
annotation. Spring Security provides the support for JSR 250 annotation as
well for method level security. @RolesAllowed provides role-based security
only.

4) @PreAuthorize and @PostAuthorize allow to use SpEL. These annotations


support expression attributes to allow pre and post-invocation authorization
checks.

5) If you wanted to do something like access the method only if the user has
Role1 and Role2 the you would have to use @PreAuthorize
@PreAuthorize("hasRole('ROLE_role1') and hasRole('ROLE_role2')") Using
@Secured({"role1", "role2"}) is treated as an OR

6) For details check the Section 14.2. Example is as follows-


<security:authorize access="!isAuthenticated()">
Login
</security:authorize>
<security:authorize access="isAuthenticated()">
Logout
</security:authorize>

Further we can also display certain information based on user role as-

<security:authorize access="hasRole('ADMIN')">
Delete Users
</security:authorize>

☞Check Your Progress 3


1) @SpringBootTest is used for integration testing and it is useful when we need
to bootstrap the entire container. The @SpringBootTest annotation tells
Spring Boot to look for a main configuration class (one with
@SpringBootApplication, for instance) and use that to start a Spring
application context. @SpringBootTest by default starts searching, a class
annotated with @SpringBootConfiguration, in the current package of the test
class and then searches upwards through the package structure. It reads the
configuration from @SpringBootConfiguration to create an application
context. This class is usually our main application class since the
@SpringBootApplication annotation includes the @SpringBootConfiguration
annotation. It then creates an application context very similar to the one that
would be started in a production environment.

2) In the MVC project, Controllers are dependent on Services, and Services are
dependent on Repositories. However, Controllers and Services should be
testable without knowing the complete implementation of dependencies.
@MockBean can be used to mock the required dependency. Spring boot
@MockBean annotation used to add mocks to a Spring ApplicationContext.
• @MockBean allows to mock a class or an interface.

29
Web Security
• @MockBean can be used on fields in either @Configuration classes
or test classes that are @RunWith the SpringRunner as well as a class
level annotation.
@MockBean at field level

@RunWith(SpringRunner.class)
public class LoginControllerTest
{

@MockBean
private LoginServiceloginService;

@MockBean at class level

@RunWith(SpringRunner.class)
@MockBean(LoginService.class)
public class LoginControllerTest
{

@Autowired
private LoginServiceloginservice;

• Mocks can be registered by type or by bean name.


• Any existing single bean of the same type defined in the context will
be replaced by the mock. If no existing bean is defined a new one will
be added.

3) For CSRF details, refer Unit 12 section 12.3 and Unit 14 section 14.6.
Necessary condition for CSRF attack to succeed is that that the victim must be
logged in and attacker is able to trick the victim into clicking a link or loading
a web page is done through social engineering or using a malicious link.

4) CSRF is a type of attack in which attackers trick a victim into making a


request that utilizes their authentication or authorization. The victim’s level of
permission decides the impact of CSRF attack. Execution of CSRF attack
consists of mainly two-part.
o Trick the victim into clicking a link or loading a web page
o Sending a crafted, legitimate-looking request from victim’s
browser to the website
Necessary steps to use Spring Security’s CSRF protection are as follows-
• Use proper HTTP verb
• Configure CSRF protection
• Include the CSRF token

14.9 REFERENCES/FURTHER READING

• Craig Walls, “Spring Boot in action” Manning Publications, 2016.


(https://doc.lagout.org/programmation/Spring%20Boot%20in%20Action.pdf)

30
Role Based Login
• Christian Bauer, Gavin King, and Gary Gregory, “Java Persistence with
Hibernate”,Manning Publications, 2015.
• Ethan Marcotte, “Responsive Web Design”, Jeffrey Zeldman Publication,
2011(http://nadin.miem.edu.ru/images_2015/responsive-web-design-2nd-
edition.pdf)
• Tomcy John, “Hands-On Spring Security 5 for Reactive Applications”,Packt
Publishing,2018
• https://www.baeldung.com/spring_redirect_after_login
• https://digitalguardian.com/blog/what-role-based-access-control-rbac-
examples-benefits-and-more
• https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html
• https://docs.spring.io/spring-
framework/docs/current/reference/html/testing.html
• https://www.baeldung.com/spring-security-csrf
• https://www.baeldung.com/java-spring-mockito-mock-mockbean

31

You might also like