Advance java Programming (AJP)
GTU # 3160707
Unit-7
Java Web
Frameworks
Spring MVC
Looping
Outline
Overview of MVC
Advantage of MVC Framework
Overview of Spring
Spring Architecture
Advantage of Spring MVC Framework
XML Configuration on Spring
Steps to run simple Spring application program
Bean life cycle
Aspect – oriented Spring
Managing Database
Managing Transaction
MVC – An overview
MVC stands for Model View and Controller.
It is a design pattern that separates the business logic, presentation logic
and data.
Controller acts as an interface between View and Model. Controller
intercepts all the incoming requests.
Model represents the state of the application i.e. data. It can also have
business logic.
View represents the presentation i.e. UI(User Interface).
In JavaEE application,
Servlet as a controller
JSP as a view component
Java Bean class as a model
MVC – An overview
Contai
ner
Controller
(Filter/Servlet)
Database
Client
View Model
(JSP) (Java Bean)
Advantage of MVC Framework
Faster Development Process
MVC supports rapid and parallel development.
If an MVC model is used to develop any particular web application then it
is possible that one programmer can work on the view
While the other can work on the controller to create the business logic of
the web application.
Ability To Provide Multiple Views
In the MVC Model, you can create multiple views for a model.
Today, there is an increasing demand for new ways to access your
application and for that MVC development is certainly a great solution.
Moreover, in this method, Code duplication is very limited because it
separates data and business logic from the display.
Advantage of MVC Framework
Support For Asynchronous Technique
The MVC architecture can also integrate with the JavaScript Framework.
This means that MVC applications can be made to work even with PDF
files, site-specific browsers, and also with desktop widgets.
MVC also supports an asynchronous technique, which helps developers to
develop an application that loads very fast.
The Modification Does Not Affect The Entire Model
the user interface tends to change more frequently than even the
business rules of the .net development company.
It is obvious that you make frequent changes in your web application like
changing colors, fonts, screen layouts, and adding new device support for
mobile phones or tablets.
Moreover, Adding a new type of view are very easy in the MVC pattern
because the Model part does not depend on the views part.
Therefore, any changes in the Model will not affect the entire architecture.
Advantage of MVC Framework
MVC Model Returns The Data Without Formatting
MVC pattern returns data without applying any formatting.
Hence, the same components can be used and called for use with any
interface.
For example, any kind of data can be formatted with HTML, but it could
also be formatted with Macromedia Flash or Dream viewer.
SEO Friendly Development Platform
MVC platform supports the development of SEO friendly web pages or web
applications.
Using this platform, it is very easy to develop SEO-friendly URLs to
generate more visits from a specific application.
This development architecture is commonly used in Test-Driven
Development applications.
Moreover, Scripting languages like JavaScript and jQuery can be
integrated with MVC to develop feature-rich web applications.
Overview of Spring
What is Spring?
Spring is a dependency injection framework to make java application
loosely coupled.
Spring framework makes the easy development of JavaEE application.
Dependency Injection
Dependency Injection (DI) is a design pattern used to implement IoC.
It allows the creation of dependent objects outside of a class and provides
those objects to a class through different ways.
Using DI, we move the creation and binding of the dependent objects
outside of the class that depends on them.
Overview of Spring
The Dependency Injection pattern involves 3 types of classes.
1)Client Class: The client class (dependent class) is a class which depends
on the service class
2)Service Class: The service class (dependency) is a class that provides
service to the client class.
3)Injector Class: The injector class injects the service class object into the
client class.
Uses
Client Service
Inj
ec
ts
Injector
Overview of Spring
public class ClientA { public class ServiceB {
ServiceB service;
public String getInfo() {
public void doSomething() { return “ServiceB’s Info”;
String info = service.getInfo(); }
} }
}
This process is called Inversion of Control (IOC).
As the name suggests, it is used to invert different kinds of controls in
object-oriented design to achieve loose coupling.
Using metadata we can implement Inversion of Control.
Use annotation or XML for Metadata.
Spring Architecture
There are around 20 modules in Spring Architecture
These modules are grouped into
Core Container
Data Access-Integration
Aspect Oriented Programming(AOP)
Instrumentation
Test
Spring Architecture/Framework/Modules
Access/integration
JDBC ORM Web Servlet
Web
Data
OXM JMS Portlet WebSocket
Transactio
n Struts
Instrumentat
AOP Aspect Messaging
ion
Container
Expression
Core
Core Beans Context
Language
Test
Spring Architecture
Core Container
Core Module
This is fundamental part of spring framework.
This module consists of IoC and Dependency Injection features.
Bean Module
This module provides BeanFactory class.
Which is a sophisticated implementation of the factory pattern.
Context Module
This module is based on Core and Bean modules.
it is a medium to access any objects defined and configured.
The ApplicationContext interface is an important point in this module.
Expression Language Module
The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.
Spring Architecture
Data Access/integration
JDBC
When we use core JDBC programming then we have to write lot of code.
The JDBC module of Spring framework removes this complexity by providing JDBC
abstraction layer.
ORM
This module provides integration layers for popular object-relational mapping APIs,
including JPA, JDO, Hibernate, and iBatis.
It provides code without worrying about catching exceptions specific to each
persistence technology.
OXM
It is used to converts object into XML format and vice versa.
Provide uniform API to access any of the OXM frameworks such as Castor, XMLBeans,
etc.
Spring Architecture
Data Access/integration
JMS
The Java Messaging Service JMS module contains features for producing and
consuming messages.
Transaction
This module supports programmatic and declarative transaction management for
classes that implement special interfaces and for all your POJOs.
Spring Architecture
Web
Web
This module provides basic web-oriented integration features such as multipart file-
upload functionality.
Also provide initialization of the IoC container using servlet listeners and a web-
oriented application context.
Web-Servlet
This module contains the model view container based implementation for web
application.
Web-Struts
This module provides the support for the integration of classic struts web tire within
the spring application.
Web-Portlet
The Web-Portlet module provides the MVC implementation to be used in a portlet
environment and mirrors the functionality of Web-Servlet module.
Spring Architecture
AOP
This module provides an aspect-oriented programming implementation.
It’s allowing you to define method-interceptors and pointcuts to cleanly
decouple code that implements functionality that should be separated.
So you can introduce new functionalities into existing code without
modifying it.
Aspects
This module provides integration with AspectJ.
Which is again a powerful and mature AOP framework.
Instrumentation
This module provides class instrumentation support and class loader
implementations to be used in certain application servers.
Spring Architecture
Messaging
This module provides support for STOMP(Simple\Streaming Text Oriented
Message Protocol) as the WebSocket sub-protocol to use in applications.
It also supports an annotation programming model for routing and
processing STOMP messages from WebSocket clients.
Test
The Test module supports the testing of Spring components with JUnit or
TestNG frameworks.
Advantage of Spring MVC Framework
Predefined Templates
Loose Coupling
Easy to test
Lightweight
Fast Development
Declarative Support
Hibernate and JDBC Support
MVC Architecture and JavaBean Support
IoC Containers
The IoC(Inversion of Control) container is at the core of the Spring
Framework.
The task of IoC container is to manage the java objects from instantiation
to destruction.
These object are basically called as Spring Beans.
The container gets its instructions about which are those objects to
instantiate, configure and assemble by reading configuration metadata
provided.
The configuration metadata can be represented either by XML, Java
annotation, or java code.
TheJava POJO
application POJO classes and configuration metadata are combined to
Spring and executable
have a fully configured Ready to use of application ready for
system
Container application
work
Metadata
Type of IoC Containers
BeanFactory Container
This is the simplest container providing the basic support for DI and is
defined by the org.springframework.beans.factory.BeanFactory interface.
For using the BeanFactory we need to get the instance of XMLBeanFactory.
Resource rec=new ClassPathResource(“Beans.xml”)
XmlBeanFactory factory = new XmlBeanFactory (rec);
Type of IoC Containers
ApplicationContext Container
The org.springframework.context.ApplicationContext interface acts as the
IoC container.
This container adds more enterprise-specific functionality such as the
ability to resolve textual messages from a properties file and the ability to
publish application events to interested event listeners.
The most commonly used ApplicationContext implementations are
FileSystemXmlApplicationContext
ClassPathXmlApplicationContext
AnnotationConfigApplicationContext
ApplicationContext context = new FileSystemXmlApplicationContext
(“C:/Users/workspace/HelloSpring/src/Beans.xml”);
XML Configuration on Spring
The configuration file is an XML file in Spring.
It binds the bean classes together.
When spring application gets loaded into memory, Framework makes use
of the XMl configuration file to create all the beans defined and assign
them unique ID as defined in <bean> tag.
You can use <property> tag to pass the value of different variables used
at the time of object creation.
XML Configuration on Spring
<?xml version=“1.0” encoding=“UTF-8”?>
<beans xmlns=“http://www.springframework.org/schema/beans”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd” >
Bean Class
Bean ID is given Name
<bean id = “studentbean” class = “springtest.StudentBean” >
<property name = “Name” value = “Raj” />
<property name = “Address” value = “Rajkot” />
</bean>
Value Assign to Bean Property
Property of Bean
</beans>
Steps to run simple Spring application program
Step 1: Create new java application
Step 2: Load Jar file of Spring in project
Step 3: Create a POJO(Plain Old Java Objects) class
Steps to run simple Spring application program
Step 4: Creating the configuration XML for ApplicationContext.
Step 5: Creating ApplicationContext class object and Initialize it using
ClassPathXmlApplicationContext
Step 6: Create associated class object
Initialize it using ApplicationContext object’s getBean() method.
Bean Lifecycle
During the Bean Lifecycle there are two important phases.
Instantiation
Destruction
Instantiation: in this phase perform some initialization to get it into a
usable state
Destruction: when the bean is no longer required and is removed from the
container, some cleanup may be required.
We declare bean using <bean> along with the init-method and destroy-
method
public classparameter in configuration file.
<bean id = “studentbean” class =
BeanProgram { “springtest.StudentBean”
init-method = “init”
public void init(){ destroy-method = “destroy” >
//do Initialize
} <property name = “Name” value = “XYZ” />
public void destroy()
{ </bean>
//do cleanup
}
Aspect Oriented Programming
One of the key components of Spring is the AOP framework.
Aspect-Oriented Programming (AOP) complements Object-Oriented
Programming (OOP) by providing another way of thinking about program
structure.
The key unit of modularity in OOP is the class, whereas in AOP the unit of
modularity is the aspect.
Aspects enable the modularization of concerns such as transaction
management that cut across multiple types and objects.
AOP terminology
Aspect
A module which has a set of APIs providing cross-cutting requirement.
Aspects are implement using regular classes.
Join point
A joint point is any point in your program such as method execution,
exception handling, field access etc.
Spring support only method execution join point
Pointcut
It is an expression language of AOP that matches join points.
AOP terminology
Advice
Advice represent an action taken by an aspect at a particular join point.
There are different type of advices.
Before advice: Advice that executes before a join point.
After returning advice: Advice to be executed after a join point completes
normally.
After throwing advice: Advice to be executed if a method exits by
throwing an exception.
After (finally) advice: Advice to be executed regardless of the means by
which a join point exits (normal or exceptional return).
Around advice: It executes before and after a join points.
Managing Database
Spring JdbcTemplate is a powerful mechanism to connect to the database
and execute SQL queries.
It internally uses JDBC api, but eliminates a lot of problems of JDBC API.
Problems of JDBC API
We need to write a lot of code before and after executing the query, such
as creating connection, statement, closing resultset, connection etc.
We need to perform exception handling code on the database logic.
We need to handle transaction.
Repetition of all these codes from one to another database logic is a time
consuming task.
JdbcTemplate class
JdbcTemplate class is the central class in the Spring JDBC support classes.
It takes care of creation and release of resources such as creating and
closing of connection object etc.
So it will not lead to any problem if you forget to close the connection.
It handles the exception and provides the informative exception messages
by the help of exception classes defined in the org.springframework.dao
package.
We can perform all the database operations by the help of JdbcTemplate
class such as insertion, updation, deletion and retrieval of the data from
the database.
Methods of Spring JdbcTemplate class.
Method Description
public int update(String It is used to insert, update and delete records.
query)
public int update(String It is used to insert, update and delete records
query,Object... args) using PreparedStatement using given
arguments.
public void is used to execute DDL query.
execute(String query)
Managing Transaction
The transaction are set of action that are treated as a single unit of work.
Transaction management is an important activity in handling databases in
order to maintain integrity and consistency.
Spring framework provides a consistent abstraction for transaction
management.
A simple transaction is usually issued to the database system
Begin the transaction
Execute several queries
Commit the transaction
Spring support both programmatic and declarative transaction
management.
Programmatic transaction management means manage the transaction
with the help of programs.
Declarative transaction management means the XML based or annotation
based configuration are used to manage the transactions.
Managing Transaction
Local Transactions Global Transactions
Local transactions are specific to a global transactions can span multiple
single transactional resource like a transactional resources like
JDBC connection transaction in a distributed system.
Local transaction management can Global transaction management is
be useful in a centralized required in a distributed computing
computing environment. environment
Application components and All the resources are distributed
resources are located at a single across multiple systems.
site
Transaction management only Transaction management needs to
involves a local data manager be done both at local and global
running on a single machine. levels.
GTU Questions
Sr No Question
1 Explain MVC Architecture.
What are the differences between Java Bean and basic java class? Explain Java
2
Bean Architecture.
Differentiate : Java Bean and basic java class and Explain Java Bean Architecture
3 and Show the use of JSP inbuilt objects: request and response, with their use in
application
4 What is Spring Web MVC framework? List its key features.
5 Explain MVC architecture in detail with figure.
Write a java bean named “student” having roll no and name having getter &
6 setter methods. Write a JSP page to set the roll number and name for a student
object and then print them by reading from object.
7 What is MVC architecture? Explain Spring architecture with neatsketch.
8 What is Dependency Injection?
9 Briefly explain spring bean life cycle.