SlideShare una empresa de Scribd logo
1 de 44
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

Más contenido relacionado

La actualidad más candente

Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCFunnelll
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 

La actualidad más candente (20)

Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Les Servlets et JSP
Les Servlets et JSPLes Servlets et JSP
Les Servlets et JSP
 

Similar a Spring mvc

quickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvcquickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvcjorgesimao71
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVCJohn Lewis
 
Spring MVC framework features and concepts
Spring MVC framework features and conceptsSpring MVC framework features and concepts
Spring MVC framework features and conceptsAsmaShaikh478737
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To MvcVolkan Uzun
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Fioriela Bego
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Commit Software Sh.p.k.
 
Spring MVC introduction HVA
Spring MVC introduction HVASpring MVC introduction HVA
Spring MVC introduction HVAPeter Maas
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanGigin Krishnan
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and ODataAnil Allewar
 

Similar a Spring mvc (20)

quickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvcquickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvc
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring mvc 2.0
Spring mvc 2.0Spring mvc 2.0
Spring mvc 2.0
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
 
Day7
Day7Day7
Day7
 
Spring MVC framework features and concepts
Spring MVC framework features and conceptsSpring MVC framework features and concepts
Spring MVC framework features and concepts
 
Oip presentation
Oip presentationOip presentation
Oip presentation
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
Web api
Web apiWeb api
Web api
 
Spring MVC introduction HVA
Spring MVC introduction HVASpring MVC introduction HVA
Spring MVC introduction HVA
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
 
Session 1
Session 1Session 1
Session 1
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
 

Último

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Último (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

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