MCS 220
MCS 220
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
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.
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.
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:
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.
3. Define the term module in J2EE. What are the four specific modules used in
J2EE applications?
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.
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;
// UnivController.java
public class UnivController
{
private UniversityModel model;
private univView view;
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();
5. Now, compile
c all thhe files using javac commaand and run MVCExample
M e file with
java as shown in figgure-3:
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:
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;
}
}
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
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
Fig
gure 5: UML diagram for Factory
F Design
n Pattern
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.
• 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");
}
}
// 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
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?
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.
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
Figure 12: S
Screen showin
ng extraction process
p of WA
AR file
18
Web Application
☞ Check Your Progress 3 Development using J2EE
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.
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:
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.
• 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
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.
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.
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();
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"
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
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
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.
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
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:
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:
10
to read data from the client. The HttpServletRequest interface extends the Basics of Servlet
ServletRequest interface.
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.
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.
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.
5. getMethod
It returns the name of the HTTP method used to make the request. Typical return
values are ‘GET’, ‘POST’, or ‘PUT’
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
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.
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.
4. getOutputStream() Method
It obtains a byte-based output stream that enables binary data to be sent to the
client.
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.
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.
6. invalidate() Method
This method is used to destroy the session.
public void invalidate()
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.
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.
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.
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
Step 5 - Creeate directoryy “ex” under thhe ‘webapps’’ folder as perr the followinng figure 7:
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.
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:
18
Basics off Servlet
Figuree 8: Command
d Prompt for S
Step 8
<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:
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
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.
Now a wind dow appears with Server settings, youu can select Finish
F buttonn from the
button Paneel.
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.
In the next window you can change servlet name and patterns and finaly click on
finish button.
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.
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.
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.
22
---------------------------------------------------------------------------------------------- Basics of Servlet
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
--------------------------------------------------------------
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
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.
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.
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>");
}
}
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
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.
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
When you will click on ‘Session Servlet Program’ link, then servlet will run and give
output as Figure-3:
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
CreateCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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).
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)
After fetching the parameter value, the FetchURLServlet program will display output
You can get this hidden field in Java Servlet using the getParameter() method of
HttpServletRequest interface.
String param1 = request.getParameter("userid");
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------
--------------------------------------------------------------------------------------
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.
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.
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)
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();
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.
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.
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.
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.
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.
Login.html
<fieldset>
<legend>Student Details</legend>
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.
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)
17
Web Application
Development using J2EE
When the condition is false, you will get the following to re-enter data:
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.
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.
StudentForm.html
<html>
<body>
<form action="../servlet/DataStoreServlet" method="post">
<h3>Indira Gandhi Open University </h3>
<fieldset>
<legend><b>Student Details </b></legend>
</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.
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.
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.
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.
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/");
}
}
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
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>
</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.
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:
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.
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.
4
Java Server Pages
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:
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.
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
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:
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.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.
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:
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>
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:
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.
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.
Step-2: Create a TLD file named taglib.tld as shown in following source program and
save it in WEB-INF directory.
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>
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.
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.
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.
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:
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:
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>©2020 SOCIS, IGNOU</footer>
</body></html>
3. Write a JSP program using Scriptlets that add numbers from 1 to 10 and prints
this result.
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_____________________________________________
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:
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:
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;
}
You can access the properties of the Java Bean from the following JSP file named as
universitydetails.jsp.
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.
The following output screen is as follows for the University details program:
<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 :
In the above syntax, name attribute defines the name of parameter being referenced
and value attribute represents the value of named parameter.
<jsp:include>
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.
<% 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.
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.
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 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" %>
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:
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.
This tag is used for executing the SQL query written into its body or through the sql
attribute. For example:
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.
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
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:
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
%>
</body></html>
23
Web Application
Development using J2EE Source code for error.jsp.
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.
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.
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>
Figure 20: Output Screen for Exception handling through try and catch clause
<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.
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.
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.
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):
In the above screen, when you will enter values then the following screen (figure-22)
will show you a message for data storage
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
con = DriverManager.getConnection(url);
if (con != null)
{
stmt = con.createStatement();
//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
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.
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>
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.
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.
• 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.
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.
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.
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-
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.
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.
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
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
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.
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).
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.
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:
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.
• 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.
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
Spring MV
VC Configu
uration
• 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.
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.
5. Spring Boot CLI: It allows us to write Groovy Spring Boot application with
concise code without requiring traditional project build.
12
Frameworks for J2EE
☞ Check Your Progress 2:
1. What is Dependency Injection?
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.
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.
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();
}
}
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");
}
We observe that method has been declared deprecated from the example, and the
compiler generates a warning message.
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 ();
}
}
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.
• @Target annotation tag defines the valid Java constructs among the
methods, class, fields etc. An annotation may associate with one or more
targets.
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
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:
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().
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.
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.
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
{
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;
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:
24
Frameworks for J2EE
5.6 SUMMARY
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 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.
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.
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.
27
Introduction to J2EE
Frameworks 5.8 REFERENCES/FURTHER READING
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.
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
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.
● Model 1 Architecture
● Model 2 (MVC) Architecture
2
Frameeworks for J2E
EE
6.2.11.1 Model 1 Architecture
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
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
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
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.
4
Frameworks for J2EE
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.
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.
<!‐‐ 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>
<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...
}
<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" />
</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!!
<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>
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">    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.
Validation has been implemented for both the fields. Hence, if any field validation
fails, the user will be notified with error messages.
11
Frameworks Available For
J2ee Development –Struts,
Success response after valid form submission is as follows.
Spring Boot and Hibernate
12
Frameworks for J2EE
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.
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.
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.
Struts Spring
It also provides integration with ORM and It provides an easy integration with ORM and
JDBC but manual coding is required. JDBC technologies.
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 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 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.
16
Frameworks for J2EE
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.
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.
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>
<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>
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.
validate Verifies the correctness of the project and make sure that all required
dependencies are downloaded.
Test Executes the unit test cases using a suitable unit testing framework
without packaging the binary artifacts
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>
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
The command mvn exec:java will execute the jar file. The output for the command
execution is shown below:
24
Frameworks for J2EE
3) Explain the different build life cycles available in the Maven tool.
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.
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
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
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
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
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.
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
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
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
Once IDE setup is done then download the latest version of Spring framework
binaries from https://repo.spring.io/release/org/springframework/spring.
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:
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
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.
Implement DIP by
Creating abstraction
Step3
Implement DI
Step4
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.
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
10
Frameworks for J2EE
Q2: Is Spring Framework open source?
• 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
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.
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";
}
}
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.
13
Spring MVC Concepts
Second step is to create spring bean configuration file as ignou-serv-servlet.xml.
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;
}
}
Ignou.jsp
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.
16
Frameworks for J2EE
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
@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";
}
}
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/*”)
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).
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:
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:
<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>
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;
}
}
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" ;
}
}
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/view/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
StudentDetailForm.jsp
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>
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
@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.")
23
Spring MVC Concepts
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.
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:
24
Frameworks for J2EE
There are two types of IoC containers. They are:
BeanFactory
ApplicationContext
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.
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:
• 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.
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
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>
● 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
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>
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" />
…………………………………………………………………………………
……………………………………………............................…………………
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………............................…………………
…………………………………………………………………………………
3) What are the obvious reasons to use Bootstrap CDN to configure it with
Spring?
…………………………………………………………………………………
…………………………………………………………………………………
……………………………………………............................…………………
…………………………………………………………………………………
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.
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.
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.2: CRUD Application Page Using Bootstrap And Custom CSS
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>
@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;
}
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
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.
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;
In REST context, CRUD corresponds to Rest web service POST, GET, PUT and
DELETE respectively. The following table maps CRUD to REST with example.
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.
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
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[] { "/" };
}
}
@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";
}
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())));
}
packagecom.ignou.mvcapp.model;
@Entity
@Table(name = "students")
publicclass Student
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
privateLongid;
publicvoidsetId(Long id)
{
this.id = id;
}
publicvoidsetFirstName(String firstName)
{
this.firstName = firstName;
}
publicvoidsetLastName(String lastName)
{
this.lastName = lastName;
}
publicvoidsetGrade(Integer grade)
{
this.grade = grade;
}
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
{
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);
}
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update
<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>
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>
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} ${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>
.btn{font‐size:10px }
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.
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.
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.
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.
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.
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.
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;
}
25
Spring MVC with @Bean
Bootstrap CSS publicPlatformTransactionManagergetTransactionManager()
{
HibernateTransactionManagerhtm =
newHibernateTransactionManager();
htm.setSessionFactory(sessionFactory().getObject());
return htm;
}
}
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
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
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.
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.
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.
9.1 OBJECTIVES
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:
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
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.
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.
@ConditionalOnProperty
The annotation is used to conditionally create a Spring bean depending on the
configuration of a property.
@Bean
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();
}
}
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-jdbc It is used for JDBC with the Tomcat JDBC connection pool.
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
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.
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.
package com.ignou.springboot.learning;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages= {"com.ignou.springboot"})
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"})
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.
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.
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.
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)
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"/>
</head>
<body>
</body>
</html>
greeting.html
<!DOCTYPEHTML>
<htmlxmlns:th="http://www.thymeleaf.org">
<head>
<metahttp‐equiv="Content‐Type"content="text/html; charset=UTF‐8"/>
</head>
<body>
</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)
13
Introduction To Spring
Boot
14
Check Your Progress 1 Spring Boot and Hibernate
(ORM)
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.
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>
• 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.
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
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.
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.
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>
19
Introduction To Spring
Boot
management.endpoints.web.exposure.include= *
21
Introduction To Spring …………………………………………………………………………………
Boot
……………………………….
3) Write a simple "Hello World" Spring Boot rest application.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
……………………………….
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
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
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}”)
@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}”)
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)
25
Introduction To Spring Active profile can be checked in the log while starting the application.
Boot
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 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.
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.
The execution of the above command packages the application and produces the jar
file into the target folder. The generated jar file can be executed using the following
command.
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.
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>
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.
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:
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>
Spring Boot provides a vast number of features and benefits. A few of them
are as follows:
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.
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>
3) To create a simple Hello World rest application using Spring Boot, we need to
perform the below steps:
33
Introduction To Spring @RestController
Boot
publicclassHomeController {
@GetMapping(value="/")
return"Hello World!!";
-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.
34
Spring Boot and Hibernate
9.8 REFERENCES/FURTHER READING (ORM)
35
UNIT 10 CONFIGURATION OF
HIBERNATE(ORM)
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
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
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
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.
6
Spring Boot and Hibernate
ANNOTATION (ORM)
@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”)
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;
@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;
@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
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-
<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>
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;
}
}
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)
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 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)
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.
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:
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.
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.
}
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.
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
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
SimpleDateFormatdateFormat = newSimpleDateFormat("dd-MM-yyyy");
Integer id1 = (Integer) sess.save(student); //student entity is transitioned from transit ->
persistent
System.out.println("Id1: "+id1);
System.out.println("Id2: "+id2);
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());
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.
HQL Update query to update the student’s last name as ‘Singh’ whose id 1.
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.
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.
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) 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.
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.
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
• 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.
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
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:
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
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
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;
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>
{
Optional<T>findById(ID id);
booleanexistsById(IDid);
Iterable<T>findAll();
Iterable<T>findAllById(Iterable<ID>ids);
long count();
voiddeleteById(ID id);
voiddeleteAll();
}
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);
}
11.2.3 JpaRepository
@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();
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?
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;
@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;
@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):
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;
}
Teacher.java
packagecom.ignou.hibernate.association.learning.entity;
@Entity
publicclass Teacher
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
8
FetchType.EAGER)
Spring Boot and Hibernate
private List<Course>courses;
(ORM)
public Teacher() {}
publicvoidsetId(Long id)
{
this.id = id;
}
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 + "]";
}
}
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;
@Override
publicvoidrun(String... args) throws Exception
{
Teacher t1 = new Teacher("Vijay Kumar");
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);
}
}
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.
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.
@ManyToOne(fetch = FetchType.LAZY)
private Teacher teacher;
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 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
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.
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.
@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.
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;
// getter setter
}
publicclass Address
@Id
@Column(name ="student_id")
privateintid;
@OneToOne
@MapsId
@JoinColumn(name="student_id")
// 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
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.
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
@Column(name = "author_name")
@Size(max = 100)
@NotNull
private String name;
2) Explain Eager and Lazy loading in Hibernate. How does it improve the
performance of hibernate applications?
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.
18
Spring Boot and Hibernate
(ORM)
@Override
publicvoid run(String... args) throws Exception
{
Book b1 = new Book("Java In Action", "ISBN-001");
List<Book>bookList = newArrayList<Book>();
bookList.add(b1);
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);
List<Author>authorList2 = newArrayList<Author>();
authorList2.add(au3);
authorList2.add(au4);
b2.setAuthors(authorList2);
au3.setBooks(bookList2);
au4.setBooks(bookList2);
bookRepository.save(b2);
}
}
@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() {}
// 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;
public Author() {}
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 + "]";
}
}
@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
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
22
Spring Boot and Hibernate
(ORM)
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")
returnbookRepository.findByTitleContaining(pattern);
@GetMapping("/search-by-method-like")
returnbookRepository.findByTitleLike("%"+pattern+"%");
@GetMapping("/search-by-query")
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
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).
26
11.7 DELETE RECORDS USING SPRING BOOT Spring Boot and Hibernate
(ORM)
AND HIBERNATE
@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.
27
Crud Application Using
Spring Boot and Hibernate
2) How does Spring Data framework derive queries from method names?
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)
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.
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
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@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 :
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;
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.
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
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.
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 –
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");
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
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:
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
}
}
}
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.
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();
}
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
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
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();
}
}
}
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.
2) List down the benefits of implementing SSL using JSSE over secure
connection established using java.net.URL
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.
• 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) { ... }
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
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.
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
Authentication
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
16
Spring Security
Configuration
Spring Security
Spring Security Modules
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.
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.
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.*;
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)
}
}
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
HTTP Security
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();
}
In-Memory Authentication
JDBC Authentication
@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");
}
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
@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.
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[] { "/" };
}
}
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;
}
}
@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
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
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();
}
}
publicclassSecurityInitializerextendsAbstractSecurityWebApplicationInitializer
{
// No Code Needed Here
}
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;
}
}
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
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
☞Check Your
Y Proggress 4
28
Spring Security
Configuration
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
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
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
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
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:
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.
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value="/customlogin")
publicclassLoginController
@GetMapping
return"customlogin";
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>
<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
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().
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.
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”);
}
}
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”
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;
}
}
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>
<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>
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:
If user provides wrong crredentials, aleert from sprinng security wiill be as show
wn in
Figure 13.4 :
10
Custom Loggin Using
Security
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.
@RunW
With(SpringRRunner.class)
)
@SpringBootTest
@Auto
oConfigureMoockMvc
class
sJavaBasedSppringSecurity
yApplication
nTests
{
@Autowireed
privateMoockMvcmvc;
}
@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.
SecurityMockMvcRequestPostProcessors
There are two ways to run the test cases as a specific User in Spring MVC Test.
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")))
mvc.perform(get("/").with(anonymous()))
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 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())
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@"))
mvc.perform(logout())
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
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..
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")
// ...
//...
.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>
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:
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
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.
<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");
}
}
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.*;
@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!!"));
}
}
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
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());
@Controller
public class UserSecurityController
{
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();
}
}
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-
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>
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 –
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>
4
Role Based Login
</body>
</html>
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 –
@Override
protectedvoidhandle(HttpServletRequestrequest, HttpServletResponseresponse,
Authentication authentication)throwsIOException
{
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted())
{
System.out.println("Can't redirect");
return;
}
/*
* 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 –
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
{
}
@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);
}
@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()
{
//...
}
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)
{
//...
}
Further we can also display certain information based on user role as-
<security:authorize access="hasRole('ADMIN')">
Delete Users
</security:authorize>
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.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………....................................………
…………………………………………………………………………………
………………………………
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.
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>();
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);
}
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
@RequestMapping(value="/customlogin")
13
Web Security publicclassLoginController
{
@GetMapping
public String login()
{
return"customlogin";
}
HomeController.java
packagecom.ignou.javabasedspringsecurity.controller;
@Controller
publicclassHomeController
{
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
}
packagecom.ignou.javabasedspringsecurity.service;
@Service
@Transactional
publicclassUserServiceimplementsUserDetailsService
{
@Autowired
privateUserRepositoryuserRepository;
@Override
publicUserDetailsloadUserByUsername(String email)
throwsUsernameNotFoundException
{
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.
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
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).
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()
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.
@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.\
@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()
{
assertThat(getUserEmail).isEqualTo(email);
}
@Bean
publicUserServiceuserService()
{
returnnewUserService();
}
}
@MockBean
privateUserRepositoryuserRepository;
@Autowired
privateUserServiceuserService;
@BeforeEach
publicvoidsetUp()
{
User user = newUser();
List<Role>roleList = newArrayList<>();
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).
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.
22
Role Based Login
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
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.
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable();
}
}
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
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.
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.
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
@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-
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
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
Further we can also display certain information based on user role as-
<security:authorize access="hasRole('ADMIN')">
Delete Users
</security:authorize>
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;
@RunWith(SpringRunner.class)
@MockBean(LoginService.class)
public class LoginControllerTest
{
@Autowired
private LoginServiceloginservice;
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.
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