Spring 2.0
Spring 2.0
Core Container
❖ The Core Container consists of the Core, Beans, Context, and
Expression Language modules.
❖ The Core and Beans modules provide the fundamental parts of the
framework, including the IoC and Dependency Injection features.
The BeanFactory is a sophisticated implementation of the factory
❖ It removes the need for programmatic singletons and allows you to
decouple the configuration and specification of dependencies from
your actual program logic.
❖ The Context module builds on the solid base provided by the Core
and Beans modules: it is a means to access objects in a
framework-style manner that is similar to a JNDI registry.
❖ The Context module inherits its features from the Beans module and
adds support for internationalization (using, for example,resource
bundles), event-propagation, resource-loading, and the transparent
creation of contexts.
❖ for example, a servlet container. The Context module also supports
Java EE features such as EJB, JMX ,and basic remoting. The
ApplicationContext interface is the focal point of the Context
module.
❖ The Expression Language module provides a powerful expression
language for querying and manipulating an object graph at runtime.
It is an extension of the unified expression language (unified EL) as
specified in the JSP 2.1 specification. The language supports setting
and getting property values.
❖ property assignment, method invocation, accessing the context of
arrays, collections and indexers.
❖ logical and arithmetic operators, named variables, and retrieval of
objects by name from Spring’s IoC container. It also supports list
projection and selection as well as common list aggregations.
Data Access/Integration
Web
(e.g. spring-core, spring-webmvc, spring-jms, etc.). The actual jar file name
that you use is normally the module name concatenated with the version
number (e.g. spring-core-5.0.9.RELEASE.jar).
Link :
https://repo.spring.io/release/org/springframework/spring/5.2.0.RELEASE/
Each release of the Spring Framework will publish artifacts to the following
places:
• Maven Central, which is the default repository that Maven queries, and
does not require any special configuration to use. Many of the common
libraries that Spring depends on also are available from Maven Central and
a large section of the Spring community uses Maven for dependency
management, so this is convenient for them. The names of the jars here are
in the form spring-*-
So the first thing you need to decide is how to manage your dependencies:
we generally recommend the use of an automated system like Maven,
Gradle or Ivy, but you can also do it manually by downloading all the jars
❖ Inversion of Control (IoC) is a design principle (although, some
people refer to it as a pattern). As the name suggests, it is used to
invert different kinds of controls in object-oriented design to achieve
loose coupling.
@Autowired
❖ For annotation based dependency injection, @Autowired
annotation is used. The classes marked with
@Component/@Service/@Repository etc can be injected
to the property which is marked with @Autowired
@Autowired is applied to
❖ field: for the field-based dependency injection
❖ setter for the setter dependency injection. Same as
field-based dependency injection.
❖ constructor for constructor-based dependency injection.
The Spring container converts the text inside the <value/> element into a
java.util.Properties instance by using the JavaBeans PropertyEditor
mechanism. This is a nice shortcut, and is one of
a few places where the Spring team do favor the use of the nested <value/>
element over the value attribute style.
Autowiring collaborators
➔ The Spring container can autowire relationships between
collaborating beans.
➔ You can allow Spring to resolve collaborators (other beans)
automatically for your bean by inspecting the contents of the
ApplicationContext.
PropertyPlaceholderConfigurer
❖ You use the PropertyPlaceholderConfigurer to externalize property
values from a bean definition in a separate file using the standard
Java Properties format.
❖ Doing so enables the person deploying an application to customize
environment-specific properties such as database URLs and
passwords, without the complexity or risk of modifying the main
XML definition file or files for the container.
❖ Consider the following XML-based configuration metadata fragment,
where a DataSource with placeholder values is defined.
❖ The example shows properties configured from an external
Properties file. At runtime, a PropertyPlaceholderConfigurer is
applied to the metadata that will replace some properties of the
DataSource.
❖ The values to replace are specified as placeholders of the form
${property-name} which follows the Ant / log4j / JSP EL style.
@Required
The @Required annotation applies to bean property setter methods, as in
the following example:
@Autowired
As expected, you can apply the @Autowired annotation to "traditional"
setter methods:
❖ You can also apply the annotation to methods with arbitrary names
and/or multiple arguments.
❖ You can apply @Autowired to constructors and fields.
Bean aliasing
it is sometimes desirable to give a single bean multiple names, otherwise
known as bean aliasing. The name attribute of the @Bean annotation
accepts a String array for this purpose.
AOP concepts
❖ • Aspect: a modularization of a concern that cuts across multiple
classes. Transaction management is a good example of a crosscutting
concern in enterprise Java applications.
❖ In Spring AOP, aspects are implemented using regular classes (the
schema-based approach) or regular classes annotated with the
@Aspect annotation (the @AspectJ style).
❖ Join point: a point during the execution of a program, such as the
execution of a method or the handling of an exception. In Spring
AOP, a join point always represents a method execution.
❖ Advice: action taken by an aspect at a particular join point. Different
types of advice include "around," "before" and "after" advice. (Advice
types are discussed below.)
❖ Many AOP frameworks, including Spring, model an advice as an
interceptor, maintaining a chain of interceptors around the join
point.
❖ Pointcut: a predicate that matches join points. Advice is associated
with a pointcut expression and runs at any join point matched by the
pointcut (for example, the execution of a method with a certain
name).
❖ The concept of join points as matched by pointcut expressions is
central to AOP, and Spring uses the AspectJ pointcut expression
language by default
Target object: object being advised by one or more aspects. Also
referred to as the advised object.
Since Spring AOP is implemented using runtime proxies, this object
will always be a proxied object.
Types of advice:
• Before advice: Advice that executes before a join point, but which
does not have the ability to prevent execution flow proceeding to the
join point (unless it throws an exception).
Declaring a pointcut
Combining pointcut expressions
Declaring advice
Advice is associated with a pointcut expression, and runs before,
after, or around method executions matched by the pointcut.
The pointcut expression may be either a simple reference to a named
pointcut, or a pointcut expression declared in place.
Around advice
❖ The final kind of advice is around advice. Around advice runs
"around" a matched method execution.
❖ It has the opportunity to do work both before and after the
method executes, and to determine when, how, and even if, the
method actually gets to execute at all.
Data Access
Spring Framework integrates with
❖ Transaction Management
❖ DAO support
❖ Data access with JDBC
❖ Object Relational Mapping (ORM) Data Access
❖ Marshalling XML using O/X Mappers
Transaction Management: Comprehensive transaction support is among
the most compelling reasons to use the Spring Framework. The Spring
Framework provides a consistent abstraction for transaction management
that delivers the following benefits:
❖ • Consistent programming model across different transaction APIs
such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence
API (JPA), and Java Data Objects (JDO).
❖ Support for declarative transaction management.
❖ • Simpler API for programmatic transaction management than
complex transaction APIs such as JTA.
❖ • Excellent integration with Spring’s data access abstractions.
Global transactions
Global transactions enable you to work with multiple transactional
resources, typically relational databases and message queues.
The application server manages global transactions through the
JTA, which is a cumbersome API to use (partly due to its exception model).
Local transactions
❖ Local transactions are resource-specific, such as a transaction
associated with a JDBC connection.
❖ Local transactions may be easier to use, but have significant
disadvantages:
❖ They cannot work across multiple transactional resources. For
example, code that manages transactions using a JDBC connection
cannot run within a global JTA transaction. Because the application
server is not involved in transaction management, it cannot help
ensure correctness across multiple resources. (It is worth noting
that most applications use a single transaction resource.)
❖ Another downside is that local transactions are invasive to the
programming model.
Data access with JDBC
You can choose among several approaches to form the basis for your JDBC
database access. In addition to three flavors of the JdbcTemplate, a new
SimpleJdbcInsert and SimplejdbcCall approach optimizes database
metadata, and the RDBMS Object style takes a more object-oriented
approach similar to that of JDO Query design. Once you start using one of
these approaches, you can still mix and match to include a feature from a
different approach. All approaches require a JDBC 2.0-compliant
driver, and some advanced features require a JDBC 3.0 driver.
Package hierarchy
The Spring Framework’s JDBC abstraction framework consists of four
different packages, namely core, datasource, object, and support.
Spring Jdbc
➢ JdbcTemplate is the classic Spring JDBC approach and the most
popular. This is the "lowest level" approach and all others use a
JdbcTemplate under the covers.
➢ NamedParameterJdbcTemplate wraps a JdbcTemplate to
provide named parameters instead of the traditional JDBC "?"
placeholders. This approach provides better documentation
and ease of use when you have multiple parameters for an SQL
statement.
➢ The Spring Framework’s JDBC abstraction framework consists
of four different packages, namely core, datasource, object, and
support.
➢ The org.springframework.jdbc.core package contains the
JdbcTemplate class and its various callback interfaces.
➢ The org.springframework.jdbc.datasource package contains a
utility class for easy DataSource access, and various simple
DataSource implementations that can be used for testing and
running.
➢ The org.springframework.jdbc.object package contains classes
that represent RDBMS queries, updates, and stored procedures
as thread safe, reusable objects.
➢ The org.springframework.jdbc.support package provides
SQLException translation functionality and some utility
classes.
❖ JdbcTemplate
➢ JdbcTemplate class is the central class in the JDBC core
package.
➢ It handles the creation and release of resources.(connection ,
statement ... etc).
❖ NamedParameterJdbcTemplate
❖o The NamedParameterJdbcTemplate class wraps a JdbcTemplate,
and delegates to the wrapped JdbcTemplate to do much of its work.
❖o The NamedParameterJdbcTemplate class adds support for
programming JDBC statements using named parameters, as opposed
to programming JDBC statements using only classic placeholder ( '?')
arguments.
Example :
Hibernate
ØWhat is Hibernate?
ØAdvantages of Hibernate ?
ØWhat ORM does ?
ØHow to save a Java Object with Hibernate?
Ø All the CRUD operations are handled by Hibernate.
The Web
Web MVC framework
❖ The Spring Web model-view-controller (MVC) framework is
designed around a DispatcherServlet that dispatches requests
to handlers, with configurable handler mappings, view
resolution, locale, time zone and theme resolution as well as
support for uploading files.
❖ The default handler is based on the @Controller and
@RequestMapping annotations, offering a wide range of
flexible handling methods.
❖ With the introduction of Spring 3.0, the @Controller
mechanism also allows you to create RESTful Web sites and
applications, through the @PathVariable annotation and other
features.
❖ In Spring Web MVC you can use any object as a command or
form-backing object; you do not need to implement a
framework-specific interface or base class. Spring’s data
binding is highly flexible: example, it treats type mismatches as
validation errors that can be evaluated by the application, not
as system errors. Thus you need not duplicate your business
objects' properties as simple, untyped strings
❖ In your form objects simply to handle invalid submissions, or to
convert the Strings properly. Instead, it is often preferable to
bind directly to your business objects.
❖
❖ Defining a controller with @Controller
The @Controller annotation indicates that a particular class serves the
role of a controller. Spring does not require you to extend any controller
base class or reference the Servlet API. However, you can still reference
Servlet-specific features if you need to.
The @Controller annotation acts as a stereotype for the annotated class,
indicating its role. The dispatcher scans such annotated classes for mapped
methods and detects @RequestMapping annotations.
In the Front Controller pattern, all requests will first go to the front controller
instead of the servlet. It'll make sure that the responses are ready and will
send them back to the browser. This way we have one place where we control
everything that comes from the outside world.
The front controller will identify the servlet that should handle the request
first. Then, when it gets the data back from the servlet, it'll decide which view
to render and, finally, it'll send the rendered view back as a response:
What Are Model 1 and Model 2 Architectures?
Model 1 and Model 2 represent two frequently used design models when it
comes to designing Java Web Applications.
On the other hand, it isn't convenient for large-scale web applications. The
functionalities are often duplicated in JSPs where business and presentation
logic are coupled.
The Model 2 is based on the Model View Controller design pattern and it
separates the view from the logic that manipulates the content.
● @GetMapping
● @PostMapping
● @PutMapping
● @PatchMapping
● @DeleteMapping
The @PathVariable annotation is used to extract the value of the URI template. It is passed within the
@RequestMapping("/show/{id}")
What are the ways of reading data from the form in Spring
MVC?
The following ways to read the data from the form are: -
javax.servlet.http package. Like Servlets, you can use HttpServletRequest in Spring to read the
● @RequestParam annotation - The @RequestParam annotation reads the form data and binds it
The Bean Validation API is a Java specification which is used to apply constraints on object models via
annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can
Hibernate Validator. The Hibernate Validator is a fully compliant JSR-303/309 implementation that
The @Valid annotation is used to apply validation rules on the provided object.
In Spring MVC Validation, we can validate the user's input within a number range by using the following
annotations: -
● @Min annotation - It is required to pass an integer value with @Min annotation. The user input
● @Max annotation - It is required to pass an integer value with @Max annotation. The user input
Spring Framework
❖ Spring Framework Introduction
❖ Spring Framework is a Java platform based framework , that provides
comprehensive infrastructure support for developing Java
applications.
❖ Spring handles the infrastructure so developers can focus on
application development/Business logic .
❖ The Spring Framework is divided into modules. Applications can
choose which modules they need. At the heart are the modules of the
core container, including a configuration model and a dependency
injection mechanism.
❖ Spring came into being in 2003 as a response to the complexity of
the early J2EE specifications.
❖ Beyond the Spring Framework, there are other projects, such as
Spring Boot, Spring Security, Spring Data, Spring Cloud, Spring Batch,
among others.
❖ Guiding principles of the Spring Framework
■ · Provide choice at every level
■ · Accommodate diverse perspectives
■ · Maintain strong backward compatibility
■ · Care about API design
■ · Set high standards for code quality
❖ As mentioned above Spring is a vast framework, Some important
modules given below
★· Spring Core
★· Spring AOP
★· Spring JDBC
★· Spring Transaction
★· Spring ORM
★· Spring MVC
❖ All the modules of Spring are independent of each other except
Spring Core. As Spring core is the base module, so in all modules we
have to use Spring Core.
❖ The Major features of Spring framework are
■ · Inversion Of Control
■ · Dependency Injection.
Core Container
Data Access/Integration
❖ The Data Access/Integration layer consists of the JDBC, ORM,
OXM, JMS and Transaction modules.
❖ The JDBC module provides a JDBC-abstraction layer that
removes the need to do tedious JDBC coding and parsing of
database-vendor specific error codes.
❖ The ORM module provides integration layers for popular
object-relational mapping APIs, including JPA, JDO, and
Hibernate.
❖ Using the ORM package you can use all of these O/R-mapping
frameworks in combination with all of the other features Spring
offers, such as the simple declarative transaction management
feature mentioned previously.
❖ The OXM module provides an abstraction layer that supports
Object/XML mapping implementations for JAXB, Castor,
XMLBeans, JiBX and XStream.
❖ The Java Messaging Service (JMS) module contains features for
producing and consuming messages.
❖ The Transaction module supports programmatic and
declarative transaction management for classes that implement
special interfaces and for all your POJOs (plain old Java
objects).
Web
If you are going to use Spring you need to get a copy of the jar libraries that
comprise the pieces of Spring that you need. To make this easier Spring is
packaged as a set of modules that separate the dependencies as much as
possible, so for example if you don’t want to write a web application you
(e.g. spring-core, spring-webmvc, spring-jms, etc.). The actual jar file name
that you use is normally the module name concatenated with the version
number (e.g. spring-core-4.0.9.RELEASE.jar).
Each release of the Spring Framework will publish artifacts to the following
places:
• Maven Central, which is the default repository that Maven queries, and
does not require any special configuration to use. Many of the common
libraries that Spring depends on also are available from Maven Central and
a large section of the Spring community uses Maven for dependency
management, so this is convenient for them. The names of the jars here are
in the form spring-*-
So the first thing you need to decide is how to manage your dependencies:
we generally recommend the use of an automated system like Maven,
Gradle or Ivy, but you can also do it manually by downloading all the jars
Logging
b) everyone likes to see some output from the tools they are using, and
c) Spring integrates with lots of other tools all of which have also made a
choice of logging dependency.
@Autowired
❖ For annotation based dependency injection, @Autowired
annotation is used. The classes marked with
@Component/@Service/@Repository etc can be injected
to the property which is marked with @Autowired
@Autowired is applied to
❖ field: for the field-based dependency injection
❖ setter for the setter dependency injection. Same as
field-based dependency injection.
❖ constructor for constructor-based dependency injection.
Collections
In the <list/>, <set/>, <map/>, and <props/> elements, you set the
properties and arguments of
the Java Collection types List, Set, Map, and Properties, respectively.
Lazy-initialized beans
➔ By default, ApplicationContext implementations eagerly create and
configure all singleton beans as part of the initialization process.
➔ Generally, this pre-instantiation is desirable, because errors in the
➔ configuration or surrounding environment are discovered
immediately, as opposed to hours or even days later.
➔ When this behavior is not desirable, you can prevent
pre-instantiation of a singleton bean by marking the bean definition
as lazy-initialized.
➔ A lazy-initialized bean tells the IoC container to create a
➔ bean instance when it is first requested, rather than at startup.
➔ In XML, this behavior is controlled by the lazy-init attribute on the
<bean/> element;
Autowiring collaborators
➔ The Spring container can autowire relationships between
collaborating beans.
➔ You can allow Spring to resolve collaborators (other beans)
automatically for your bean by inspecting the contents of the
ApplicationContext.
PropertyPlaceholderConfigurer
❖ You use the PropertyPlaceholderConfigurer to externalize property
values from a bean definition in a separate file using the standard
Java Properties format.
❖ Doing so enables the person deploying an application to customize
environment-specific properties such as database URLs and
passwords, without the complexity or risk of modifying the main
XML definition file or files for the container.
❖ Consider the following XML-based configuration metadata fragment,
where a DataSource with placeholder values is defined.
❖ The example shows properties configured from an external
Properties file. At runtime, a PropertyPlaceholderConfigurer is
applied to the metadata that will replace some properties of the
DataSource.
❖ The values to replace are specified as placeholders of the form
${property-name} which follows the Ant / log4j / JSP EL style.
❖ Therefore, the string ${jdbc.username} is replaced at runtime with
the values , and the same applies for other placeholder values that
match keys in the properties file.
❖ The PropertyPlaceholderConfigurer checks for placeholders in most
properties and attributes of a bean definition. Furthermore, the
placeholder prefix and suffix can be customized.
<context:property-placeholder
location="classpath:com/foo/jdbc.properties"/>
@Required
The @Required annotation applies to bean property setter methods, as in
the following example:
❖ This annotation simply indicates that the affected bean property
must be populated at configuration time, through an explicit
property value in a bean definition or through autowiring.
❖ The container throws an exception if the affected bean property has
not been populated; this allows for eager and explicit failure,
avoiding NullPointerExceptions or the like later on.
❖ It is still recommended that you put assertions into the bean class
itself, for example, into an init method. Doing so enforces those
required references and values even when you use the class outside of
a container.
@Autowired
As expected, you can apply the @Autowired annotation to "traditional"
setter methods:
❖ You can also apply the annotation to methods with arbitrary names
and/or multiple arguments.
❖ You can apply @Autowired to constructors and fields.
Bean aliasing
it is sometimes desirable to give a single bean multiple names, otherwise
known as bean aliasing. The name attribute of the @Bean annotation
accepts a String array for this purpose.
AOP concepts
❖ • Aspect: a modularization of a concern that cuts across multiple
classes. Transaction management is a good example of a crosscutting
concern in enterprise Java applications.
❖ In Spring AOP, aspects are implemented using regular classes (the
schema-based approach) or regular classes annotated with the
@Aspect annotation (the @AspectJ style).
❖ Join point: a point during the execution of a program, such as the
execution of a method or the handling of an exception. In Spring
AOP, a join point always represents a method execution.
❖ Advice: action taken by an aspect at a particular join point. Different
types of advice include "around," "before" and "after" advice. (Advice
types are discussed below.)
❖ Many AOP frameworks, including Spring, model an advice as an
interceptor, maintaining a chain of interceptors around the join
point.
❖ Pointcut: a predicate that matches join points. Advice is associated
with a pointcut expression and runs at any join point matched by the
pointcut (for example, the execution of a method with a certain
name).
❖ The concept of join points as matched by pointcut expressions is
central to AOP, and Spring uses the AspectJ pointcut expression
language by default
Target object: object being advised by one or more aspects. Also
referred to as the advised object.
Since Spring AOP is implemented using runtime proxies, this object
will always be a proxied object.
Types of advice:
• Before advice: Advice that executes before a join point, but which
does not have the ability to prevent execution flow proceeding to the
join point (unless it throws an exception).
Declaring a pointcut
Combining pointcut expressions
Declaring advice
Advice is associated with a pointcut expression, and runs before,
after, or around method executions matched by the pointcut.
The pointcut expression may be either a simple reference to a named
pointcut, or a pointcut expression declared in place.
Around advice
❖ The final kind of advice is around advice. Around advice runs
"around" a matched method execution.
❖ It has the opportunity to do work both before and after the
method executes, and to determine when, how, and even if, the
method actually gets to execute at all.
Data Access
Spring Framework integrates with
❖ Transaction Management
❖ DAO support
❖ Data access with JDBC
❖ Object Relational Mapping (ORM) Data Access
❖ Marshalling XML using O/X Mappers
Transaction Management: Comprehensive transaction support is among
the most compelling reasons to use the Spring Framework. The Spring
Framework provides a consistent abstraction for transaction management
that delivers the following benefits:
❖ • Consistent programming model across different transaction APIs
such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence
API (JPA), and Java Data Objects (JDO).
❖ Support for declarative transaction management.
❖ • Simpler API for programmatic transaction management than
complex transaction APIs such as JTA.
❖ • Excellent integration with Spring’s data access abstractions.
Global transactions
Global transactions enable you to work with multiple transactional
resources, typically relational databases and message queues.
The application server manages global transactions through the
JTA, which is a cumbersome API to use (partly due to its exception model).
Local transactions
❖ Local transactions are resource-specific, such as a transaction
associated with a JDBC connection.
❖ Local transactions may be easier to use, but have significant
disadvantages:
❖ They cannot work across multiple transactional resources. For
example, code that manages transactions using a JDBC connection
cannot run within a global JTA transaction. Because the application
server is not involved in transaction management, it cannot help
ensure correctness across multiple resources. (It is worth noting
that most applications use a single transaction resource.)
❖ Another downside is that local transactions are invasive to the
programming model.
Data access with JDBC
You can choose among several approaches to form the basis for your JDBC
database access. In addition to three flavors of the JdbcTemplate, a new
SimpleJdbcInsert and SimplejdbcCall approach optimizes database
metadata, and the RDBMS Object style takes a more object-oriented
approach similar to that of JDO Query design. Once you start using one of
these approaches, you can still mix and match to include a feature from a
different approach. All approaches require a JDBC 2.0-compliant
driver, and some advanced features require a JDBC 3.0 driver.
Package hierarchy
The Spring Framework’s JDBC abstraction framework consists of four
different packages, namely core, datasource, object, and support.
Spring Jdbc
➢ JdbcTemplate is the classic Spring JDBC approach and the most
popular. This is the "lowest level" approach and all others use a
JdbcTemplate under the covers.
➢ NamedParameterJdbcTemplate wraps a JdbcTemplate to
provide named parameters instead of the traditional JDBC "?"
placeholders. This approach provides better documentation
and ease of use when you have multiple parameters for an SQL
statement.
➢ The Spring Framework’s JDBC abstraction framework consists
of four different packages, namely core, datasource, object, and
support.
➢ The org.springframework.jdbc.core package contains the
JdbcTemplate class and its various callback interfaces.
➢ The org.springframework.jdbc.datasource package contains a
utility class for easy DataSource access, and various simple
DataSource implementations that can be used for testing and
running.
➢ The org.springframework.jdbc.object package contains classes
that represent RDBMS queries, updates, and stored procedures
as thread safe, reusable objects.
➢ The org.springframework.jdbc.support package provides
SQLException translation functionality and some utility
classes.
❖ JdbcTemplate
➢ JdbcTemplate class is the central class in the JDBC core
package.
➢ It handles the creation and release of resources.(connection ,
statement ... etc).
❖ NamedParameterJdbcTemplate
❖o The NamedParameterJdbcTemplate class wraps a JdbcTemplate,
and delegates to the wrapped JdbcTemplate to do much of its work.
❖o The NamedParameterJdbcTemplate class adds support for
programming JDBC statements using named parameters, as opposed
to programming JDBC statements using only classic placeholder ( '?')
arguments.
Example :
Hibernate
ØWhat is Hibernate?
ØAdvantages of Hibernate ?
ØWhat ORM does ?
ØHow to save a Java Object with Hibernate?
Ø All the CRUD operations are handled by Hibernate.
The Web
Web MVC framework
❖ The Spring Web model-view-controller (MVC) framework is
designed around a DispatcherServlet that dispatches requests
to handlers, with configurable handler mappings, view
resolution, locale, time zone and theme resolution as well as
support for uploading files.
❖ The default handler is based on the @Controller and
@RequestMapping annotations, offering a wide range of
flexible handling methods.
❖ With the introduction of Spring 3.0, the @Controller
mechanism also allows you to create RESTful Web sites and
applications, through the @PathVariable annotation and other
features.
❖ In Spring Web MVC you can use any object as a command or
form-backing object; you do not need to implement a
framework-specific interface or base class. Spring’s data
binding is highly flexible: example, it treats type mismatches as
validation errors that can be evaluated by the application, not
as system errors. Thus you need not duplicate your business
objects' properties as simple, untyped strings
❖ In your form objects simply to handle invalid submissions, or to
convert the Strings properly. Instead, it is often preferable to
bind directly to your business objects.
❖
❖ Defining a controller with @Controller
The @Controller annotation indicates that a particular class serves the
role of a controller. Spring does not require you to extend any controller
base class or reference the Servlet API. However, you can still reference
Servlet-specific features if you need to.
The @Controller annotation acts as a stereotype for the annotated class,
indicating its role. The dispatcher scans such annotated classes for mapped
methods and detects @RequestMapping annotations.
In the Front Controller pattern, all requests will first go to the front controller
instead of the servlet. It'll make sure that the responses are ready and will
send them back to the browser. This way we have one place where we control
everything that comes from the outside world.
The front controller will identify the servlet that should handle the request
first. Then, when it gets the data back from the servlet, it'll decide which view
to render and, finally, it'll send the rendered view back as a response:
What Are Model 1 and Model 2 Architectures?
Model 1 and Model 2 represent two frequently used design models when it
comes to designing Java Web Applications.
On the other hand, it isn't convenient for large-scale web applications. The
functionalities are often duplicated in JSPs where business and presentation
logic are coupled.
The Model 2 is based on the Model View Controller design pattern and it
separates the view from the logic that manipulates the content.
● @GetMapping
● @PostMapping
● @PutMapping
● @PatchMapping
● @DeleteMapping
The @PathVariable annotation is used to extract the value of the URI template. It is passed within the
@RequestMapping("/show/{id}")
What are the ways of reading data from the form in Spring
MVC?
The following ways to read the data from the form are: -
javax.servlet.http package. Like Servlets, you can use HttpServletRequest in Spring to read the
● @RequestParam annotation - The @RequestParam annotation reads the form data and binds it
The Bean Validation API is a Java specification which is used to apply constraints on object models via
annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can
Hibernate Validator. The Hibernate Validator is a fully compliant JSR-303/309 implementation that
The @Valid annotation is used to apply validation rules on the provided object.
In Spring MVC Validation, we can validate the user's input within a number range by using the following
annotations: -
● @Min annotation - It is required to pass an integer value with @Min annotation. The user input
● @Max annotation - It is required to pass an integer value with @Max annotation. The user input