Spring - and - Springmvc by Yog
Spring - and - Springmvc by Yog
Benefits…
1
Spring Framework
2
Spring IOC Container
The core of the spring framework.
Create Objects
Wire them together
Configure them
Manage their complete life cycle from creation till destruction
3
WEB-INF/classes/dispatcher-servlet.xml
Import any other context configuration files. For example to import
the main ROOT application context file:
<import resource="app-context.xml"/>
Configure the @Controller programming model
<mvc:annotation-driven />
Configure all the View Resolvers
TilesViewResolver (and TilesConfigurer)
JSPViewResolver
MultiPartResolver
ExceptionResolver
CookieLocaleResolver
4
WEB-INF/classes/app-context.xml
Initiate a component scan
Note that at run-time, these property files will typically be placed at:
/WEB-INF/classes folder so they get detected in the classpath scanning
5
WEB-INF/classes/app-context.xml
Property place holder configurer (This is a BeanFactroy
PostProcessor)
Sample Contents
spring bean
lifecycle
callback
method
How to use
6
WEB-INF/classes/app-context.xml
Configure Resource Bundle Message Resource (i18n)
Note that at run-time, these properties files will typically be placed at: /WEB-
INF/classes folder so they get detected in the classpath scanning
The basenames property of the messageSource bean will by default look for
files with the “.properties” extension.
7
WEB-INF/classes/app-context.xml
i18n
There should be multiple resource messages files one for each locale
messages.properties – Default and English
messages_zh_CN.properties – Chinese
Sample Contents
8
WEB-INF/classes/app-context.xml
Session Factory (Depends on DataSource)
Spring support for hibernate LocalSessionFactory
dataSource
mappingLocations – List of *.hbm.xml files
hibernateProperties – Such as show_sql, dialect etc…,
9
View Resolver
All the handler methods in the controller class must
resolve to a logical view name explicitly by returning a
String
ViewResolver interface
Provides a mapping between view names and the actual views
There are many implementation is spring, but the prominent ones
used are InternalResourceViewResolver and TilesViewResolver
10
InternalResourceViewResolver
What’s internal resource views?
In Spring MVC or any web application, for good practice, it’s always
recommended to put the entire views or JSP files under “WEB-INF” folder, to
protect it from direct access via manual entered URL. Those views under
“WEB-INF” folder are named as internal resource views, as it’s only accessible
by the servlet or Spring’s controllers class.
In Spring MVC, InternalResourceViewResolver is used to
resolve “internal resource view” (in simple, it’s final output, jsp
or html page) based on a predefined URL pattern. In additional,
it allow you to add some predefined prefix or suffix to the view
name (prefix + view name + suffix), and generate the final view
page URL.
If let’s say controller returns a string “carrierDetails”; the actual (physical)
view it resolves to is
/WEB-INF/jsp/carrierDetails.jsp
11
TilesViewResolver
Resolves view names to protected .jsp resources within the
/WEB-INF/jsp directory
12
/WEB-INF/tiles/tiles.xml
In tiles.xml we have defined a template “base.definition“
This layout has a base template jsp = /WEB-INF/jsp/layout/layout.jsp in
which attributes (as place holders) are defined.
This layout contains attributes such as
resources - /WEB-INF/jsp/layout/resources.jsp
Header - /WEB-INF/jsp/layout/header.jsp
appmenu - /WEB-INF/jsp/layout/appmenu.jsp
body – “”
footer - /WEB-INF/jsp/layout/footer.jsp
This layout is then extended and if required, the attributes are overridden
/WEB-INF/jsp/layout/layout.jsp
13
/WEB-INF/tiles/industry-tiles.xml
In industry-tiles.xml the base layout is extended for view
carrier
14
Redirecting to views
Redirect – redirect:
A Note on InternalResourceViewResolver
Convenient subclass of UrlBasedViewResolver that supports InternalResourceView (in effect, Servlets
and JSPs) and subclasses such as JstlView and TilesView. You can specify the view class for all views
generated by this resolver by using setViewClass(..).
If a view name is returned that has the prefix redirect:, the UrlBasedViewResolver
(and all subclasses) will recognize this as a special indication that a redirect is
needed. The rest of the view name will be treated as the redirect URL.
In this example, the controller handler method does a “delete” operation and after
this it is desirable that the user is presented back with the list of objects. So here
the response is delegated to another controller method – Here in this case, the
list.do URL is called again by the client.
15
ExceptionResolver - Handling Exceptions in a generic way
SimpleMappingExceptionResolver
Takes the class name of any exception (ex: java.lang.Exception) that
might be thrown from a handler method and map it to a view name.
Map exception class names to view names
Specify a default (fallback) error page for any exception not handled anywhere else
Configuration
16
Annotations, annotations and annotations everywhere….
as
17
Implementing Controllers
Controllers provide access to the application behavior that you typically define
through a service interface
Controllers interpret user input and transform it into a model that is represented to
the user by the view
19
@RequestMapping
@RequestMapping is used to map URLs such as /viewCarrier.do
onto a methods in the Controller class
Can be used both at class level and methods levels
Typically the class-level annotation maps a specific request path
(or path pattern) onto a form controller, with additional method-
level annotations narrowing the primary mapping for a specific
HTTP method request method ("GET", "POST", etc.) or an HTTP
request parameter condition.
Spring 3.1+
The RequestMappingHandlerMapping is the only place where a
decision is made about which method should process the request
Think of controller methods as a collection of unique service endpoints
with mappings for each method derived from type (class level) and
method-level @RequestMapping information
20
Consumable Media Types
You can narrow the primary mapping by specifying a list of
consumable media types. The request will be matched only if
the Content-Type request header matches the specified media
type. For example:
21
Producible Media Types
You can narrow the primary mapping by specifying a list of producible
media types. The request will be matched only if the Accept request header
matches one of these values. Furthermore, use of the produces condition
ensures the actual content type used to generate the response respects the
media types specified in the produces condition. For example:
Note that in the above example, the response data is sent back to the client
as HTTP response (Not to a view) using the @ResponseBody annotation.
Spring does the automatic conversion of the returned object to a HTTP
Response to a format of JSON or XML – Spring uses Jackson for JSON and
JAXB for XML
22
URI Template Patterns - @PathVariable
URI Template
Is a URI-like string, containing one or more variable names
http://www.example.com/users/{userId} – variable name is userId
When you substitute values for these variables, the template becomes a URI
The URI Template " /owners/{ownerId}" specifies the variable name ownerId. When
the controller handles this request, the value of ownerId is set to the value found in
the appropriate part of the URI. For example, when a request comes in for
/owners/arun, the value of ownerId is arun
23 This is the beginning of Spring RESTful services
@RequestParam
Use the @RequestParam annotation to bind request parameters to a method
parameter in your controller
Parameters using this annotation are required by default, but you can specify
that a parameter is optional by setting @RequestParam's required attribute to
false
Type conversion is applied automatically if the target method parameter type is
not String
24
@RequestBody
The @RequestBody method parameter annotation indicates that a method
parameter should be bound to the value of the HTTP request body. For
example:
26
@ModelAttribute
An @ModelAttribute on a method argument indicates the argument should
be retrieved from the model.
For the object in the model, the argument’s fields should be populated from
all request parameters that have matching names. This is known as data
binding in Spring MVC.
This is usually used when the form-backing (or command) object is filled up
and submitted from the client form.
27
@InitBinder
Annotating controller methods with @InitBinder allows you to configure web
data binding within your controllers
@InitBinder identifies methods that initialize the WebDataBinder that will be
used to populate command and form object arguments of annotated
handler methods
28
@Valid (JSR 303)
In Spring, you can enable “mvc:annotation-driven” to support JSR303 bean
validation via @Valid annotation on the handler method parameter, if any
JSR303 validator framework is in the classpath
Hibernate Validator is the RI for JSR303
0 to 9999
@Pattern (regex)
Start with “C” or “c”
Followed by exactly 4 digits
1 to 80 chars
29
@Valid (JSR 303)
An @RequestBody method parameter can be annotated with @Valid, in which
case it will be validated using the configured Validator instance.
The validator was initialized using @InitBinder (from previous slides)
Validator runs the validation code and based on PASS/FAIL, it sets the
BindingResult
BindingResult will now examined in the Controller as shown above for any
errors
30
@Valid (JSR 303) – JSP
If there are any validation errors, they will be automatically bind to the
model object
On the JSP Page, using Spring custom tags, we can display the error
messages:
31
@Valid (JSR 303) – Error Messages
There are default error messages that will be displayed for each of
the JSR 303 validation annotations.
This can be overridden in the message resources as key value
pairs.
Key is @annotationName.object.feildName
objectname here refers to the command/model object name (reference) used
in the JSP
32
References
Theory
http://docs.spring.io/spring/docs/3.0.x/reference/
mvc.html
http://docs.spring.io/spring/docs/2.5.6/reference/
mvc.html
Examples
http://www.mkyong.com/tutorials/spring-mvc-tut
orials/
33
BACKUP
34
SimpleFormController
35
formView
1. Create an instance of the form object (a.k.a command bean)
Using the formBackingObject() method
By default this method will return an instance of the class specified with
setCommandClass() (remember commandName & commandClass
properties?)
formBackingObject() can be overridden to manipulate the form object
before it enters the formView
2. Creates the DataBinder and calls the initBinder()
Override this method to register any custom PropertyEditors required
when binding to the form object
3. At this point, the view (formView) is ready to be rendered to the
user. But before this…
referenceData() call-back method is called
This life cycle method allows you to assemble and return any auxiliary
objects required to render the view. The form object will automatically be
sent to the view, so use this method to put anything else into the model
the form page might need.
36
Form Submission with the onSubmit() method
1. Create an instance of the form object (a.k.a command bean)
Using the formBackingObject() method
2. Creates the DataBinder and calls the initBinder()
Override this method to register any custom PropertyEditors required
when binding to the form object
With the form bean created , and the DataBinder created , the request
parameters are now bound to the form bean
3. Allow each configured validator (thru the validator
property) to validate the form bean object
4. After validation, the controller makes a decision based on
whether any error exists
If there are any errors – display the original form view
The referenceData() method is called once more to populate the model with object
for the form. Finally, the form view is displayed again, with the errors and the form
bean
If no error exists – Then the form bean can finally be processed in the
onSubmit()method
37
Spring custom tags
<spring:bind path=“comamndName.attributeName” > ....
</spring:bind>
<spring:bind path="carrier.carrierName">
<td><input name="<c:out value="${status.expression}"/>" value="<c:out value="$
{status.value}"/>" /></td>
</spring:bind>
The <spring:bind> tag extracts information about a single field (“carrierName" in this example)
from the command object (named “carrier" in this case) and places it in a status variable.
${status.expression} contains the name that the field should have and ${status.value} contains
the value of the field (blank initially, but populated with previously submitted values if the form is
redisplayed after submission errors).
New Way
<form:form commandName=“carrier">
<td><form:input path=“carrierName” /></td>
</form:form>
The "comandName" attribute tells the form the name of the command object that contains our
form data (specified in your form controller by calling setCommandName())
The "path" attribute gives the command object property that will be bound to the input
field. Unlike the "path" attribute in <spring:bind> I didn't have to specify the command
name here because the <form:form> tag already identifies the command object we'll
binding to.
38