Block 02
Block 02
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>
</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>
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!!
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
Figure 6.8: Execution Result 3
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.
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>
8
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); Introduction to J2EE
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
Frameworks
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
returndataSource;
}
private Properties hibernateProperties()
{
Properties properties = newProperties();
properties.put("hibernate.dialect", environment.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getProperty("hibernate.hbm2ddl.auto"));
returnproperties;
}
@Bean
publicPlatformTransactionManagergetTransactionManager()
{
HibernateTransactionManagerhtm = newHibernateTransactionManager();
htm.setSessionFactory(sessionFactory().getObject());
return htm;
}
}
Property file inside src/main/resources. File name can be any with extension as
properties.
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/schoolDB
jdbc.username = root
jdbc.password = root
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update
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[] { "/" };
}
}
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;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "grade", nullable = false)
private Integer grade;
public Long getId()
{
returnid;
}
publicvoidsetId(Long id)
{
this.id = id;
}
public String getFirstName()
{
returnfirstName;
}
publicvoidsetFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
returnlastName;
}
publicvoidsetLastName(String lastName)
{
this.lastName = lastName;
}
public Integer getGrade()
{
returngrade;
}
publicvoidsetGrade(Integer grade)
{
this.grade = grade;
}
public String getName()
{
returnthis.firstName + " " + this.lastName;
}
}
17
Spring MVC with
Bootstrap CSS
Step 6: Create the DAO layer into the package com.ignou.mvcapp.dao. DAO layer is
responsible for interacting with the database.
StudentDao.java
packagecom.ignou.mvcapp.model;
publicinterfaceStudentDao
{
Student getStudent(Long id);
Long saveStudent(Student st);
List<Student>listAllStudents();
voidupdateStudent(Student st);
voiddeleteStudent(Student st);
}
StudentDaoImpl.java
packagecom.ignou.mvcapp.model;
@Repository("studentDao")
@Transactional
publicclassStudentDaoImplimplementsStudentDao
{
@Autowired
privateSessionFactorysessionFactory;
@Override
public Student getStudent(Long id)
{
Session session = sessionFactory.getCurrentSession();
Student s =session.get(Student.class, id);
returns;
}
@Override
public Long saveStudent(Student st)
{
Session session = sessionFactory.getCurrentSession();
session.save(st);
returnst.getId();
}
@Override
public List<Student>listAllStudents()
{
Session session = sessionFactory.getCurrentSession();
CriteriaBuildercb = session.getCriteriaBuilder();
CriteriaQuery<Student>cq = cb.createQuery(Student.class);
Root<Student>root = cq.from(Student.class);
cq.select(root);
Query query = session.createQuery(cq);
@SuppressWarnings("unchecked")
List<Student>students = query.getResultList();
returnstudents;
}
@Override
publicvoidupdateStudent(Student st)
{
Session session = sessionFactory.getCurrentSession();
session.update(st);
}
@Override
publicvoiddeleteStudent(Student st)
18
{ Introduction to J2EE
Session session = sessionFactory.getCurrentSession();
Frameworks
session.delete(st);
}
hibernate.hbm2ddl.auto = update
19
Spring MVC with cssClass="form‐horizontal">
Bootstrap CSS <form:inputtype="hidden"path="id"id="id"/>
<divclass="form‐group">
<labelfor="firstName">First Name</label>
<form:inputpath="firstName"id="firstName"cssClass="form‐control"/>
</div>
<divclass="form‐group">
<labelfor="lastName">Last Name</label>
<form:inputpath="lastName"id="lastName"cssClass="form‐control"/>
</div>
<divclass="form‐group">
<labelfor="grade">Grade</label>
<form:inputpath="grade"id="grade"cssClass="form‐control"/>
</div>
<hr/>
<c:choose>
<c:whentest="${edit}">
<buttontype="submit"class="btnbtn‐
primary">Update</button>
</c:when>
<c:otherwise>
<buttontype="submit"class="btnbtn‐
primary">Save</button>
</c:otherwise>
</c:choose>
<aclass="btnbtn‐secondary"href="<c:urlvalue='/list'/>">List
of All Students</a>
</form:form>
</div>
</body>
</html>
allStudents.jsp
<%@taglibprefix="form"uri="http://www.springframework.org/tags/form"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metahttp‐equiv="Content‐Type"content="text/html; charset=ISO‐8859‐1">
<title>All Students</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<scriptsrc="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></
script>
<linkhref="<c:urlvalue="/css/custom.css"/>"rel="stylesheet">
</head>
<body>
<navclass="navbar navbar‐light bg‐light">
<divclass="container">
<divclass="navbar‐brand mx‐auto text‐success"href="#">
<h1>Student Management System (SMS)</h1>
</div>
</div>
</nav>
<divclass="container">
<divclass="text‐secondary text‐center">
<h2>Registered Students</h2>
</div>
<c:iftest="${not empty success}">
<divclass="alert alert‐success alert‐dismissible fade show"
role="alert">${success}
<buttontype="button"class="btn‐close"data‐bs‐
dismiss="alert"
aria‐label="Close"></button>
20
</div> Introduction to J2EE
</c:if>
Frameworks
<hr/>
<tableclass="table">
<theadclass="thead‐dark">
<tr>
<td>Student ID</td>
<td>Student Name</td>
<td>Grade</td>
<td>Modify</td>
<td>Delete</td>
</tr>
<c:forEachitems="${allstudents}"var="student">
<tr>
<td>${student.id}</td><td>${student.firstName} ${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 }
tr:first‐child{font‐size:20px; color:maroon; font‐weight:bold;}
Step 10: Build the project using maven with goal clean install and then deploy the
generated war file inside the target directory to the external tomcat. You can directly
execute the project into the eclipse by using the Run on Server option. Once the
application is up and running, access the URL http://localhost:8080/spring-mvc-crud-
app/ and perform the CRUD operation provided by the application.
Output:
Home screen renders all existing students by executing read operation into the
database.
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;
}
private Properties hibernateProperties()
{
Properties properties = newProperties();
//set Hibernate properties
returnproperties;
}
25
Spring MVC with @Bean
Bootstrap CSS publicPlatformTransactionManagergetTransactionManager()
{
HibernateTransactionManagerhtm =
newHibernateTransactionManager();
htm.setSessionFactory(sessionFactory().getObject());
return htm;
}
}
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