SlideShare a Scribd company logo
SPRING MVC
HARSHIT CHOUDHARY
OUTLINE
 Introduction to MVC Design Pattern
 Configuring Spring in a Web application using Spring MVC
 DispatcherServlet front controller
 Defining Spring MVC controllers using annotations
 Spring MVC in the view layer
 Form rendering and type conversion
 Form validation using Spring and Bean validation
HARSHIT CHOUDHARY
INTRODUCTION TO SPRING MVC
HARSHIT CHOUDHARY
WHAT IS MVC?
 Clearly separates business, navigation and presentation logic.
 MVC is commonly used design pattern that can be applied to many different architectures like GUI, Web application
etc.
 MVC suggests that the application is broken up as
 Model
 Manage the data of the application
 The contract between the controller and the view
 Contains the data needed to render the view
 Populated by the controller
 View
 Renders the response to the request
 Pulls data from the model
 Defines how to present the data
 Controller
 Controllers are responsible for controlling the flow of application execution
 They control the application logic and act as the coordinator between the View and Model.
 The also perform application-wide tasks like validation, security and navigation
HARSHIT CHOUDHARY
SPRING WEB MVC
 Spring creates a lightweight container that handles incoming HTTP requests by mapping them to
Controllers, which return a Model and View that produces the HTTP response.
 It works around a single Front Controller 'DispatcherServlet' that dispatches requests to handlers,
with configurable handler mappings, view resolution, locale and theme resolution as well as
support for upload files.
 Individual Controllers can be used to handle many different URLs.
 Controllers are POJOs and are managed exactly like any other bean in the Spring
ApplicationContext.
HARSHIT CHOUDHARY
FEATURES OF SPRING WEB MVC
 Clear separation of roles - controller, validator, command object, form object, model object,
DispatcherServlet, handler mapping, view resolver, etc. Each role can be fulfilled by a specialized
object.
• Powerful and straightforward configuration of both framework and application classes as
JavaBeans
 Adaptability, non-intrusiveness, and flexibility. Define any controller method signature you need,
possibly using one of the parameter annotations such as @RequestParam, @RequestHeader,
@PathVariable, and more.
 Reusable business code - no need for duplication.
 Flexible in supporting different view types like JSP, Velocity, XML, PDF, OGNL etc
HARSHIT CHOUDHARY
FEATURES OF SPRING WEB MVC
 Customizable binding and validation.
 Customizable handler mapping and view resolution.
 Flexible model transfer. Model transfer with a name/value Map supports easy integration with any view
technology.
 Customizable locale and theme resolution, support for JSPs with or without Spring tag library, support for JSTL,
support for Velocity without the need for extra bridges, and so on.
 A simple yet powerful JSP tag library known as the Spring tag library that provides support for features such as
data binding and themes.
 A JSP form tag library, introduced in Spring 2.0, that makes writing forms in JSP pages much easier.
HARSHIT CHOUDHARY
REQUEST PROCESSING WORKFLOW IN SPRING WEB MVC
HARSHIT CHOUDHARY
DISPATCHERSERVLET CONTROLLER
 The DispatcherServlet is the Spring Front Controller
 It Initializes WebApplicationContext
 Uses /WEB-INF/[servlet-name]-servlet.xml by default
 WebApplicationContext is bound into ServletContext
 HandlerMapping - Routing of requests to handlers
 ViewResolver - Maps symbolic name to view
 LocaleResolver - Default uses HTTP accept header, cookie, or session
HARSHIT CHOUDHARY
SPECIAL BEAN TYPES IN THE WEBAPPLICATIONCONTEXT
HARSHIT CHOUDHARY
Bean Type Explanation
HandlerMapping
Maps incoming requests to handlers and a list of pre- and post-processors (handler
interceptors) based on some criteria the details of which vary by HandlerMapping
implementation
HandlerAdapter
Helps the DispatcherServlet to invoke a handler mapped to a request regardless of
the handler is actually invoked.
HandlerExceptionResolver Maps exceptions to views also allowing for more complex exception handling code.
ViewResolver Resolves logical String-based view names to actual View types.
LocaleResolver
Resolves the locale a client is using, in order to be able to offer internationalized
views
ThemeResolver
Resolves themes your web application can use, for example, to offer personalized
layouts
MultipartResolver
Parses multi-part requests for example to support processing file uploads from
HTML forms.
LIFECYCLE OF SPRING MVC APPLICATION
1. Incoming HTTP request is mapped to the Spring DispatcherServlet.
2. The locale resolver is bound to the request to enable elements to resolve the locale to use.
3. The theme resolver is bound to the request to let elements such as views determine which theme to use.
4. If the request is in multiparts and there is a multipart file resolver is specified, the request is wrapped in a
MultipartHttpServletRequest for further processing by other elements in the process.
5. An appropriate handler is searched for. If a handler is found, the execution chain associated with the handler
(preprocessors, postprocessors, and controllers) is executed in order to prepare a model or rendering.
6. If a model is returned, the view is rendered, If no model is returned, no view is rendered.
HARSHIT CHOUDHARY
CONFIGURE SPRING WEB MVC IN CASE OF XML CONFIGURATION
 Incoming HTTP request is mapped to the Spring DispatcherServlet.
 Edit web.xml as below –
HARSHIT CHOUDHARY
<web-app>
<servlet>
<servlet-name>first</servlet-name>
<servlet-lass>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
</web-app>
CONFIGURE SPRING WEB MVC
 The DispatcherServlet creates a container using the bean definitions found in the Servlet configuration
file.
 The DispatcherServlet locates the configuration file using the naming convention <servletname>-
servlet.xml.
 Create WEB-INFfirst-servlet.xml as below
HARSHIT CHOUDHARY
<mvc:annotation-driven/>
<context:component-scan base-package=“com.spring" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
CONFIGURE SPRING MVC USING JAVA-BASED CONFIGURATION
HARSHIT CHOUDHARY
<servlet>
<servlet-name>first</servlet-name>
<servlet-lass>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value> spring.config.SpringConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
ENABLING THE MVC JAVA CONFIG OR MVC NAMESPACE
 To enable MVC Java Config
 @EnableWebMVC
 Used at @Configuration class
 To achieve the same in XML
 <mvc:annotation-driven>
HARSHIT CHOUDHARY
IMPLEMENTING CONTROLLERS
 Controllers intercept user input and transform it into a model that is represented to the user by the
view.
 Since 2.5, Controllers can be implemented using Annotations.
 Two important annotations which are used are:
 @Controller
 @RequestMapping
 Controllers implemented in this style do not have to extend specific base class or implement
specific interfaces.
HARSHIT CHOUDHARY
IMPLEMENTING CONTROLLER
 @Controller annotation indicates that a
particular class serves the role of a controller
 The dispatcher scans such annotated classes
for mapped methods and detects
@RequestMapping annotation.
 The returned value need to be mapped as a
JSP page using the View Resolver
configuration.
HARSHIT CHOUDHARY
CONFIGURING VIEW RESOLVERS
HARSHIT CHOUDHARY
In JavaConfig class
In xml file
CREATE VIEW PAGE
 Create helloworld.jsp as below:
HARSHIT CHOUDHARY
MAPPING REQUEST WITH @REQUESTMAPPING
 @RequestMapping annotation can be used to map URLs onto an entire class or a particular
method.
 Class-level annotation maps a specific request path on to the controller
 Additional method-level annotations narrow down the primary mapping for a specific HTTP request
method (GET, POST etc) or an HTTP request parameter condition
HARSHIT CHOUDHARY
@Controller
@RequestMapping(“/order”)
Public class OrderController{
@RequestMapping(method=RequestMethod.GET)
Public List<Products> getProducts(){}
@RequestMapping(path=“/place”,
method=RequestMethod.POST)
public String placeOrder(){}
Request through Get method for
URL /order
Request through Post method for
URL /order/place
URI TEMPLATE PATTERNS
 URI Template is a URI-like string, containing one or more variable names. When the values are substituted for these
variables, the template becomes a URI.
 For ex,
http://www.example.com/users/{userId} – URI template containing variable userId
Providing value to the variable, it becomes a URI
http://www.example.com/users/Neelam
 To bind the value of a URI template variable, @PathVariable annotation is used on a method argument
HARSHIT CHOUDHARY
@RequestMapping(“/orders/{orderId}”)
public String getOrder(@PathVariable String orderId, Model model){
Order order = OrderService.findOrder(orderId)
model.addAttribute(“order”,order);
return displayOrder;
}
Use of PathVariable Annotation
URI TEMPLATE PATTERNS
 A method can have any number of @PathVariable annotations
 A URI template can be assembled from type and method level @RequestMapping annotations
HARSHIT CHOUDHARY
@RequestMapping(“customer/{customeId}/orders/{orderId}”)
public String getOrder(@PathVariable String customerId, @PathVariable
String orderId, Model model){
}
@Controller
@RequestMapping(“/customer/{customerId}”)
Public class CustomerController{
@RequestMapping(“/orders/{orderId}”)
public String getOrder(@PathVariable String customerId, @PathVariable
String orderId, Model model){ }
}
URI TEMPLATE PATTERNS
 @RequestMapping annotation supports the use of regular expression
HARSHIT CHOUDHARY
@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-
{version:d.d.d}{extension:.[a-z]+}" )
public String getOrder(@PathVariable String version, @PathVariable String extension){
}
REQUEST PARAMS AND HEADER VALUES
 Request Matching can also be narrowed down through request parameter conditions such as
“myParams”, “!myParams”, or “myParam=myValue”
 The first two test for request parameter presence/absence and the third for a specific
parameter value
 Example
 The same can be done to test for request header presence/absence to match based on a
specific request header value
HARSHIT CHOUDHARY
@RequestMapping(path=“/customer”, params=“myParam=myValue”)
public String getCustomer(Model model){
}
@RequestMapping(path=“/customer”, headers=“myHeader=myValue”)
public String getCustomer(Model model){
}
DEFINING @REQUESTMAPPING HANDLER METHODS
 @RequestMapping handler methods can have very flexible signatures.
 It supports a long list of method arguments and return types, Commonly used arguments and return
types are described in next slides
 Most arguments can be used in arbitrary order with the only exception being BindingResult arguments
(described later)
HARSHIT CHOUDHARY
SUPPORTED METHOD ARGUMENT TYPES
HARSHIT CHOUDHARY
Type Description
Request or Response
objects
Servlet API
Session Object An argument of this type enforces the presence of a corresponding
session
@PathVariable annotated parameters for access to URI template variables
@RequestParam annotated parameters for access to specific Servlet request
parameters
@RequestHeader annotated parameters for access to specific Servlet request HTTP
headers
@RequestBody annotated parameters for access to the HTTP request body
@RequestPart annotated parameters for access to the content of a
"multipart/form-data" request part
@SessionAttribute annotated parameters for access to existing, permanent session
attributes
SUPPORTED METHOD ARGUMENT TYPES
HARSHIT CHOUDHARY
Type Description
@RequestAttribute annotated parameters for access to request attributes.
ModelMap/Model for enriching the implicit model that is exposed to the web view.
@ModelAttribute temporarily stored in the session as part of a controller workflow
BindingResult validation results for a preceding command or form object
SUPPORTED METHOD RETURN TYPES
HARSHIT CHOUDHARY
Type Description
ModelAndView
object
ModelAndView can store the Model data and view name to be displayed
Model object Model object with view name implicitly determined
String Logical view name
Void If the method handle the response itself
View A view object
HttpHeaders To return a response with no body
DATA VALIDATION
HARSHIT CHOUDHARY
DATA VALIDATIONS
 Validation in Spring can be done in either of two ways
 Using Validator Interface provided by Spring
 Using Annotations
HARSHIT CHOUDHARY
VALIDATOR INTERFACE
 Spring features a Validator interface that you can use to validate objects.
 The Validator interface works using an Errors object so that while validating, validators can
report validation failures to the Errors object.
 Data binding is useful for allowing user input to be dynamically bound to the domain model
of an application
HARSHIT CHOUDHARY
SPRING VALIDATION API
 org.springframework.validation.Validator(Interface) - Validator for application-specific objects.
 void validate(Object target,Errors errors)
 org.springframework.validation.ValidationUtils(class) - Utility class convenient methods for
invoking a Validator and for rejecting empty fields.
 static void rejectIfEmpty(Errors errors, String field, String errorCode)
 static void rejectIfEmptyOrWhitespace(Errors errors, String field, String errorCode)
 org.springframework.validationErrors(Interface) - Stores and exposes information about data-
binding and validation errors for a specific object.
HARSHIT CHOUDHARY
VALIDATIONS USING JSR303 (HIBERNATE)
 JSR-303 standardizes validation constraint declaration and metadata for the Java platform.
 This API is annotate domain model properties with declarative validation constraints and the runtime
enforces them.
 There are a number of built-in constraints you can can take advantage of.
 You may also define your own custom constraints.
HARSHIT CHOUDHARY
VALIDATIONS USING JSR303 (HIBERNATE)
Create bean class as below –
public class RegistrationBean {
@NotEmpty(message="Name field is mandatory.")
private String name = null;
@NotEmpty(message="Username field is mandatory.")
private String username = null;
@NotEmpty(message="Email field is mandatory.")
private String email = null;
@Length(max=10,min=10,message="Phone number is not valid. Should be of length 10.")
@NotEmpty(message="Phone field is mandatory.") @NumberFormat(style= Style.NUMBER)
private String phone;
@NotEmpty(message="Password should not be empty.")
private String password = null;
// all getter/setter
}
HARSHIT CHOUDHARY
FILE UPLOAD
HARSHIT CHOUDHARY
MULTIPART(FILEUPLOAD) SUPPORT
 Spring’s built-in multipart support handles file uploads in web applications
 This support is enabled with MultipartResolver objects.
 One MultipartResolver implementation is for use with Commons FileUpload
HARSHIT CHOUDHARY
USING A MULTIPART RESOLVER WITH COMMONS FILEUPLOAD
 The jar file required for the same is commons-fileupload.jar
 When DispatcherServlet detects a multi-part request, it activates the resolver and hands over the request
 The resolver then wraps the current HttpServletRequest into a MultipartHttpServletRequest that supports multiple file uploads.
HARSHIT CHOUDHARY
EXCEPTION HANDLING IN SPRING MVC
HARSHIT CHOUDHARY
HANDLING EXCEPTIONS
 Implement interface – HandlerExceptionResolver
 Allows to map Exceptions to specific views declaratively along with some optional Java logic code before
forwarding to these views
 Use already provided implementation – SimpleMappingExceptionResolver
 Enables to take the class name of any exception that might be thrown and map it to a view name.
 Create @ExceptionHandler methods
 Can be used on methods that should be invoked to handle an exception
 These methods may be defined locally within an @Controller
HARSHIT CHOUDHARY
HANDLEREXCEPTIONRESOLVER
 Any Spring Bean that implements HandlerExceptionResolver will be used to intercept and process any
exception raised in the MVC system and not handler by a Controller.
 The handler refers to the controller that generated the exception
 The interface can be implemented to set up our own custom exception handling system.
HARSHIT CHOUDHARY
SIMPLEMAPPINGEXCEPTIONRESOLVER
 Convenient implementation of HandlerExceptionResolver. It provide options to:
 Map exception class names to view names
 Specify a default error page for any exception not handled anywhere else
 Log a message (not enabled by default)
 Set the name of the exception attribute to add to the Model so that it can be used inside a View.
Default name is ‘exception’
HARSHIT CHOUDHARY
CONFIGURING SIMPLEMAPPINGEXCEPTIONRESOLVER
HARSHIT CHOUDHARY
The defaultErrorView property is especially useful as it ensures any uncaught exception generates a
suitable application defined error page.
@EXCEPTIONHANDLER
 @ExceptionHandler methods can be added to the controllers to specifically handle
exceptions thrown by request handling methods in the same controller
 Such methods can
 Handle exceptions without @ResponseStatus annotation
 Redirect the user to a dedicated error view
 Build a totally custom error response
HARSHIT CHOUDHARY
@EXCEPTIONHANDLER
HARSHIT CHOUDHARY

More Related Content

PDF
Spring boot introduction
PDF
Spring Framework - AOP
PPT
Spring Core
PPT
Reflection in C Sharp
PPTX
JPA For Beginner's
PPT
Javascript Basics
PPTX
Introduction to Spring Boot
PPT
Hibernate
Spring boot introduction
Spring Framework - AOP
Spring Core
Reflection in C Sharp
JPA For Beginner's
Javascript Basics
Introduction to Spring Boot
Hibernate

What's hot (20)

PPTX
Spring data jpa
PPTX
Introduction to React JS for beginners
ODP
Spring User Guide
PPTX
React workshop
PPTX
Rest api with node js and express
PDF
Spring Boot
PDF
JavaScript - Chapter 15 - Debugging Techniques
PDF
Spring Data JPA
PDF
JPA and Hibernate
PPTX
Introduction to React JS
PPTX
Jetpack Compose - Android’s modern toolkit for building native UI
PPTX
ReactJS presentation.pptx
PPTX
Spring beans
PPTX
Spring boot
PPTX
Spring Security 5
PPT
Spring Framework
PPTX
Test your microservices with REST-Assured
ODP
Testing RESTful Webservices using the REST-assured framework
PDF
Spring Framework - MVC
PPTX
Introduction to Spring Framework
Spring data jpa
Introduction to React JS for beginners
Spring User Guide
React workshop
Rest api with node js and express
Spring Boot
JavaScript - Chapter 15 - Debugging Techniques
Spring Data JPA
JPA and Hibernate
Introduction to React JS
Jetpack Compose - Android’s modern toolkit for building native UI
ReactJS presentation.pptx
Spring beans
Spring boot
Spring Security 5
Spring Framework
Test your microservices with REST-Assured
Testing RESTful Webservices using the REST-assured framework
Spring Framework - MVC
Introduction to Spring Framework
Ad

Similar to Spring mvc (20)

PDF
Spring MVC Framework
PPT
PPTX
Spring MVC
PDF
Spring mvc
PPTX
Spring Web MVC
PDF
Spring tutorial
PDF
quickguide-einnovator-7-spring-mvc
PPTX
Spring mvc
ODP
Java Spring MVC Framework with AngularJS by Google and HTML5
ODP
springmvc-150923124312-lva1-app6892
PDF
Spring mvc 2.0
PDF
Design & Development of Web Applications using SpringMVC
PDF
Spring Framework-II
PPTX
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
PPTX
Dispatcher
PPT
Spring-training-in-bangalore
PPTX
Spring mvc
PDF
SpringMVC
PDF
Spring MVC - The Basics
PPTX
Presentation DataFlow for java webapp.pptx
Spring MVC Framework
Spring MVC
Spring mvc
Spring Web MVC
Spring tutorial
quickguide-einnovator-7-spring-mvc
Spring mvc
Java Spring MVC Framework with AngularJS by Google and HTML5
springmvc-150923124312-lva1-app6892
Spring mvc 2.0
Design & Development of Web Applications using SpringMVC
Spring Framework-II
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
Dispatcher
Spring-training-in-bangalore
Spring mvc
SpringMVC
Spring MVC - The Basics
Presentation DataFlow for java webapp.pptx
Ad

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Big Data Technologies - Introduction.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Cloud computing and distributed systems.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPT
Teaching material agriculture food technology
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
“AI and Expert System Decision Support & Business Intelligence Systems”
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Review of recent advances in non-invasive hemoglobin estimation
Chapter 3 Spatial Domain Image Processing.pdf
Empathic Computing: Creating Shared Understanding
Big Data Technologies - Introduction.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Cloud computing and distributed systems.
Spectral efficient network and resource selection model in 5G networks
Building Integrated photovoltaic BIPV_UPV.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Mobile App Security Testing_ A Comprehensive Guide.pdf
MYSQL Presentation for SQL database connectivity
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Teaching material agriculture food technology
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Per capita expenditure prediction using model stacking based on satellite ima...

Spring mvc

  • 2. OUTLINE  Introduction to MVC Design Pattern  Configuring Spring in a Web application using Spring MVC  DispatcherServlet front controller  Defining Spring MVC controllers using annotations  Spring MVC in the view layer  Form rendering and type conversion  Form validation using Spring and Bean validation HARSHIT CHOUDHARY
  • 3. INTRODUCTION TO SPRING MVC HARSHIT CHOUDHARY
  • 4. WHAT IS MVC?  Clearly separates business, navigation and presentation logic.  MVC is commonly used design pattern that can be applied to many different architectures like GUI, Web application etc.  MVC suggests that the application is broken up as  Model  Manage the data of the application  The contract between the controller and the view  Contains the data needed to render the view  Populated by the controller  View  Renders the response to the request  Pulls data from the model  Defines how to present the data  Controller  Controllers are responsible for controlling the flow of application execution  They control the application logic and act as the coordinator between the View and Model.  The also perform application-wide tasks like validation, security and navigation HARSHIT CHOUDHARY
  • 5. SPRING WEB MVC  Spring creates a lightweight container that handles incoming HTTP requests by mapping them to Controllers, which return a Model and View that produces the HTTP response.  It works around a single Front Controller 'DispatcherServlet' that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files.  Individual Controllers can be used to handle many different URLs.  Controllers are POJOs and are managed exactly like any other bean in the Spring ApplicationContext. HARSHIT CHOUDHARY
  • 6. FEATURES OF SPRING WEB MVC  Clear separation of roles - controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, etc. Each role can be fulfilled by a specialized object. • Powerful and straightforward configuration of both framework and application classes as JavaBeans  Adaptability, non-intrusiveness, and flexibility. Define any controller method signature you need, possibly using one of the parameter annotations such as @RequestParam, @RequestHeader, @PathVariable, and more.  Reusable business code - no need for duplication.  Flexible in supporting different view types like JSP, Velocity, XML, PDF, OGNL etc HARSHIT CHOUDHARY
  • 7. FEATURES OF SPRING WEB MVC  Customizable binding and validation.  Customizable handler mapping and view resolution.  Flexible model transfer. Model transfer with a name/value Map supports easy integration with any view technology.  Customizable locale and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, and so on.  A simple yet powerful JSP tag library known as the Spring tag library that provides support for features such as data binding and themes.  A JSP form tag library, introduced in Spring 2.0, that makes writing forms in JSP pages much easier. HARSHIT CHOUDHARY
  • 8. REQUEST PROCESSING WORKFLOW IN SPRING WEB MVC HARSHIT CHOUDHARY
  • 9. DISPATCHERSERVLET CONTROLLER  The DispatcherServlet is the Spring Front Controller  It Initializes WebApplicationContext  Uses /WEB-INF/[servlet-name]-servlet.xml by default  WebApplicationContext is bound into ServletContext  HandlerMapping - Routing of requests to handlers  ViewResolver - Maps symbolic name to view  LocaleResolver - Default uses HTTP accept header, cookie, or session HARSHIT CHOUDHARY
  • 10. SPECIAL BEAN TYPES IN THE WEBAPPLICATIONCONTEXT HARSHIT CHOUDHARY Bean Type Explanation HandlerMapping Maps incoming requests to handlers and a list of pre- and post-processors (handler interceptors) based on some criteria the details of which vary by HandlerMapping implementation HandlerAdapter Helps the DispatcherServlet to invoke a handler mapped to a request regardless of the handler is actually invoked. HandlerExceptionResolver Maps exceptions to views also allowing for more complex exception handling code. ViewResolver Resolves logical String-based view names to actual View types. LocaleResolver Resolves the locale a client is using, in order to be able to offer internationalized views ThemeResolver Resolves themes your web application can use, for example, to offer personalized layouts MultipartResolver Parses multi-part requests for example to support processing file uploads from HTML forms.
  • 11. LIFECYCLE OF SPRING MVC APPLICATION 1. Incoming HTTP request is mapped to the Spring DispatcherServlet. 2. The locale resolver is bound to the request to enable elements to resolve the locale to use. 3. The theme resolver is bound to the request to let elements such as views determine which theme to use. 4. If the request is in multiparts and there is a multipart file resolver is specified, the request is wrapped in a MultipartHttpServletRequest for further processing by other elements in the process. 5. An appropriate handler is searched for. If a handler is found, the execution chain associated with the handler (preprocessors, postprocessors, and controllers) is executed in order to prepare a model or rendering. 6. If a model is returned, the view is rendered, If no model is returned, no view is rendered. HARSHIT CHOUDHARY
  • 12. CONFIGURE SPRING WEB MVC IN CASE OF XML CONFIGURATION  Incoming HTTP request is mapped to the Spring DispatcherServlet.  Edit web.xml as below – HARSHIT CHOUDHARY <web-app> <servlet> <servlet-name>first</servlet-name> <servlet-lass> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>first</servlet-name> <url-pattern>*.spring</url-pattern> </servlet-mapping> </web-app>
  • 13. CONFIGURE SPRING WEB MVC  The DispatcherServlet creates a container using the bean definitions found in the Servlet configuration file.  The DispatcherServlet locates the configuration file using the naming convention <servletname>- servlet.xml.  Create WEB-INFfirst-servlet.xml as below HARSHIT CHOUDHARY <mvc:annotation-driven/> <context:component-scan base-package=“com.spring" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>
  • 14. CONFIGURE SPRING MVC USING JAVA-BASED CONFIGURATION HARSHIT CHOUDHARY <servlet> <servlet-name>first</servlet-name> <servlet-lass> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value> spring.config.SpringConfig</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>first</servlet-name> <url-pattern>*.spring</url-pattern> </servlet-mapping>
  • 15. ENABLING THE MVC JAVA CONFIG OR MVC NAMESPACE  To enable MVC Java Config  @EnableWebMVC  Used at @Configuration class  To achieve the same in XML  <mvc:annotation-driven> HARSHIT CHOUDHARY
  • 16. IMPLEMENTING CONTROLLERS  Controllers intercept user input and transform it into a model that is represented to the user by the view.  Since 2.5, Controllers can be implemented using Annotations.  Two important annotations which are used are:  @Controller  @RequestMapping  Controllers implemented in this style do not have to extend specific base class or implement specific interfaces. HARSHIT CHOUDHARY
  • 17. IMPLEMENTING CONTROLLER  @Controller annotation indicates that a particular class serves the role of a controller  The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotation.  The returned value need to be mapped as a JSP page using the View Resolver configuration. HARSHIT CHOUDHARY
  • 18. CONFIGURING VIEW RESOLVERS HARSHIT CHOUDHARY In JavaConfig class In xml file
  • 19. CREATE VIEW PAGE  Create helloworld.jsp as below: HARSHIT CHOUDHARY
  • 20. MAPPING REQUEST WITH @REQUESTMAPPING  @RequestMapping annotation can be used to map URLs onto an entire class or a particular method.  Class-level annotation maps a specific request path on to the controller  Additional method-level annotations narrow down the primary mapping for a specific HTTP request method (GET, POST etc) or an HTTP request parameter condition HARSHIT CHOUDHARY @Controller @RequestMapping(“/order”) Public class OrderController{ @RequestMapping(method=RequestMethod.GET) Public List<Products> getProducts(){} @RequestMapping(path=“/place”, method=RequestMethod.POST) public String placeOrder(){} Request through Get method for URL /order Request through Post method for URL /order/place
  • 21. URI TEMPLATE PATTERNS  URI Template is a URI-like string, containing one or more variable names. When the values are substituted for these variables, the template becomes a URI.  For ex, http://www.example.com/users/{userId} – URI template containing variable userId Providing value to the variable, it becomes a URI http://www.example.com/users/Neelam  To bind the value of a URI template variable, @PathVariable annotation is used on a method argument HARSHIT CHOUDHARY @RequestMapping(“/orders/{orderId}”) public String getOrder(@PathVariable String orderId, Model model){ Order order = OrderService.findOrder(orderId) model.addAttribute(“order”,order); return displayOrder; } Use of PathVariable Annotation
  • 22. URI TEMPLATE PATTERNS  A method can have any number of @PathVariable annotations  A URI template can be assembled from type and method level @RequestMapping annotations HARSHIT CHOUDHARY @RequestMapping(“customer/{customeId}/orders/{orderId}”) public String getOrder(@PathVariable String customerId, @PathVariable String orderId, Model model){ } @Controller @RequestMapping(“/customer/{customerId}”) Public class CustomerController{ @RequestMapping(“/orders/{orderId}”) public String getOrder(@PathVariable String customerId, @PathVariable String orderId, Model model){ } }
  • 23. URI TEMPLATE PATTERNS  @RequestMapping annotation supports the use of regular expression HARSHIT CHOUDHARY @RequestMapping("/spring-web/{symbolicName:[a-z-]+}- {version:d.d.d}{extension:.[a-z]+}" ) public String getOrder(@PathVariable String version, @PathVariable String extension){ }
  • 24. REQUEST PARAMS AND HEADER VALUES  Request Matching can also be narrowed down through request parameter conditions such as “myParams”, “!myParams”, or “myParam=myValue”  The first two test for request parameter presence/absence and the third for a specific parameter value  Example  The same can be done to test for request header presence/absence to match based on a specific request header value HARSHIT CHOUDHARY @RequestMapping(path=“/customer”, params=“myParam=myValue”) public String getCustomer(Model model){ } @RequestMapping(path=“/customer”, headers=“myHeader=myValue”) public String getCustomer(Model model){ }
  • 25. DEFINING @REQUESTMAPPING HANDLER METHODS  @RequestMapping handler methods can have very flexible signatures.  It supports a long list of method arguments and return types, Commonly used arguments and return types are described in next slides  Most arguments can be used in arbitrary order with the only exception being BindingResult arguments (described later) HARSHIT CHOUDHARY
  • 26. SUPPORTED METHOD ARGUMENT TYPES HARSHIT CHOUDHARY Type Description Request or Response objects Servlet API Session Object An argument of this type enforces the presence of a corresponding session @PathVariable annotated parameters for access to URI template variables @RequestParam annotated parameters for access to specific Servlet request parameters @RequestHeader annotated parameters for access to specific Servlet request HTTP headers @RequestBody annotated parameters for access to the HTTP request body @RequestPart annotated parameters for access to the content of a "multipart/form-data" request part @SessionAttribute annotated parameters for access to existing, permanent session attributes
  • 27. SUPPORTED METHOD ARGUMENT TYPES HARSHIT CHOUDHARY Type Description @RequestAttribute annotated parameters for access to request attributes. ModelMap/Model for enriching the implicit model that is exposed to the web view. @ModelAttribute temporarily stored in the session as part of a controller workflow BindingResult validation results for a preceding command or form object
  • 28. SUPPORTED METHOD RETURN TYPES HARSHIT CHOUDHARY Type Description ModelAndView object ModelAndView can store the Model data and view name to be displayed Model object Model object with view name implicitly determined String Logical view name Void If the method handle the response itself View A view object HttpHeaders To return a response with no body
  • 30. DATA VALIDATIONS  Validation in Spring can be done in either of two ways  Using Validator Interface provided by Spring  Using Annotations HARSHIT CHOUDHARY
  • 31. VALIDATOR INTERFACE  Spring features a Validator interface that you can use to validate objects.  The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.  Data binding is useful for allowing user input to be dynamically bound to the domain model of an application HARSHIT CHOUDHARY
  • 32. SPRING VALIDATION API  org.springframework.validation.Validator(Interface) - Validator for application-specific objects.  void validate(Object target,Errors errors)  org.springframework.validation.ValidationUtils(class) - Utility class convenient methods for invoking a Validator and for rejecting empty fields.  static void rejectIfEmpty(Errors errors, String field, String errorCode)  static void rejectIfEmptyOrWhitespace(Errors errors, String field, String errorCode)  org.springframework.validationErrors(Interface) - Stores and exposes information about data- binding and validation errors for a specific object. HARSHIT CHOUDHARY
  • 33. VALIDATIONS USING JSR303 (HIBERNATE)  JSR-303 standardizes validation constraint declaration and metadata for the Java platform.  This API is annotate domain model properties with declarative validation constraints and the runtime enforces them.  There are a number of built-in constraints you can can take advantage of.  You may also define your own custom constraints. HARSHIT CHOUDHARY
  • 34. VALIDATIONS USING JSR303 (HIBERNATE) Create bean class as below – public class RegistrationBean { @NotEmpty(message="Name field is mandatory.") private String name = null; @NotEmpty(message="Username field is mandatory.") private String username = null; @NotEmpty(message="Email field is mandatory.") private String email = null; @Length(max=10,min=10,message="Phone number is not valid. Should be of length 10.") @NotEmpty(message="Phone field is mandatory.") @NumberFormat(style= Style.NUMBER) private String phone; @NotEmpty(message="Password should not be empty.") private String password = null; // all getter/setter } HARSHIT CHOUDHARY
  • 36. MULTIPART(FILEUPLOAD) SUPPORT  Spring’s built-in multipart support handles file uploads in web applications  This support is enabled with MultipartResolver objects.  One MultipartResolver implementation is for use with Commons FileUpload HARSHIT CHOUDHARY
  • 37. USING A MULTIPART RESOLVER WITH COMMONS FILEUPLOAD  The jar file required for the same is commons-fileupload.jar  When DispatcherServlet detects a multi-part request, it activates the resolver and hands over the request  The resolver then wraps the current HttpServletRequest into a MultipartHttpServletRequest that supports multiple file uploads. HARSHIT CHOUDHARY
  • 38. EXCEPTION HANDLING IN SPRING MVC HARSHIT CHOUDHARY
  • 39. HANDLING EXCEPTIONS  Implement interface – HandlerExceptionResolver  Allows to map Exceptions to specific views declaratively along with some optional Java logic code before forwarding to these views  Use already provided implementation – SimpleMappingExceptionResolver  Enables to take the class name of any exception that might be thrown and map it to a view name.  Create @ExceptionHandler methods  Can be used on methods that should be invoked to handle an exception  These methods may be defined locally within an @Controller HARSHIT CHOUDHARY
  • 40. HANDLEREXCEPTIONRESOLVER  Any Spring Bean that implements HandlerExceptionResolver will be used to intercept and process any exception raised in the MVC system and not handler by a Controller.  The handler refers to the controller that generated the exception  The interface can be implemented to set up our own custom exception handling system. HARSHIT CHOUDHARY
  • 41. SIMPLEMAPPINGEXCEPTIONRESOLVER  Convenient implementation of HandlerExceptionResolver. It provide options to:  Map exception class names to view names  Specify a default error page for any exception not handled anywhere else  Log a message (not enabled by default)  Set the name of the exception attribute to add to the Model so that it can be used inside a View. Default name is ‘exception’ HARSHIT CHOUDHARY
  • 42. CONFIGURING SIMPLEMAPPINGEXCEPTIONRESOLVER HARSHIT CHOUDHARY The defaultErrorView property is especially useful as it ensures any uncaught exception generates a suitable application defined error page.
  • 43. @EXCEPTIONHANDLER  @ExceptionHandler methods can be added to the controllers to specifically handle exceptions thrown by request handling methods in the same controller  Such methods can  Handle exceptions without @ResponseStatus annotation  Redirect the user to a dedicated error view  Build a totally custom error response HARSHIT CHOUDHARY