Spring Framework: Benefits
Spring Framework: Benefits
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
Spring Bean Life Cycle
Initialization callbacks
4
Spring Bean Life Cycle
Bean Post Processors
The BeanPostProcessors operate on bean (or object) instances which means that the spring IoC container
instantiates the bean instance and then BPP interfaces do their work.
By default, Spring will not be aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have
to either register ‘CommonAnnotationBeanPostProcessor‘ or specify the ‘<context:annotation-config />‘ in
bean configuration file,
5
Spring Bean Life Cycle
Bean Life Cycle Sequence
If (BPP)
postProcessBeforeInitialization()
If (init-method)
init-method()
If (BPP)
postProcessAfterInitialization()
Bean is ready
6
Spring AOP
Inside XML – Enabline @AspectJ Programming Module
<aop:aspectj-autoproxy/> @Before
Define an Aspect Java Class @After
@Aspect @AfterReturning
public class AspectModule {
@AfterThrowing
…
}
@Around
Define the Aspect as a bean in XML
<bean id="myAspect" class="org.xyz.AspectModule">
<!-- configure properties of aspect here as normal -->
</bean>
Declare a PONITCUT in the Aspect
@Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression
private void businessService() {} // signature
Declare an ADVICE in the Aspect
@Around("businessService()")
public void doAroundTask() {
...
}
7
Spring MVC
Spring MVC is part of the Spring Framework as a MVC implementation
The Spring Web model-view-controller (MVC) framework is designed around a
DispatcherServlet that dispatches requests to handlers
8
The Dispatcher Servlet
Spring MVC framework is request-driven, designed around a
central Servlet that dispatches requests to controllers and offers
other functionalities that facilitates the development of web
applications
Spring’s DispatcherServlet is completely integrated with the
Spring IoC container and as such allows you to use every other
feature that Spring has
DispatcherServlet is an expression of the “Front Controller”
design pattern
9
The Dispatcher Servlet
10
src/main/webapp/WEB-INF/web.xml
All incoming requests flow through a DispatcherServlet
DispatcherServlet is an actual Servlet (it inherits from HttpServlet base class) and as such
is declared in the web.xml file.
You need to map requests that you want the DispatcherServlet to handle, by using a URL
mapping in the same web.xml file
11
DispatcherServlet’s WebApplicationContext
In Spring MVC each DispatcherServlet has its own WebApplicationContext. By default, spring always looks for the
context at <dispatcherServletName-servlet.xml>. However this can be overridden with a Servlet init-param
The DispatcherServlet related WebApplicationContext should have MVC-specific configurations such as Controllers,
HandlerMappings, ViewResolvers etc…,
12
ROOT WebApplicationContext
Other non MVC-specific configuration such as the beans for service or persistence layer should be in root WebApplicationContext.
In SpringMVC the root WebApplicationContext is bootstrapped by using ContextLoadListener specified as Listener in web.xml.
So the DispatcherServlet WebApplicationContext will inherit (extend) from the ROOT WebApplicationContext
13
ROOT WebApplicationContext
14
Handler Mappings
HandlerMapping is the class that helps DispatcherServlet to map an incoming
request to a particular Controller class.
There are many HandlerMapping implementations in Spring, however the most
used one is the annotated controllers
HandlerMapping bean has one important property – interceptors to which a user
defined handler interceptor can be injected
RequestMappingHandlerMapping
This HandlerMapping implementation automatically looks for @RequestMapping annotations on all
@Controller beans
The RequestMappingHandlerMapping is the only place where a decision is made about which
method should process the request
<mvc:annotation-driven />
This annotation in the DispatcherServlet WebApplicationContext (file: /WEB-INF/classes/dispatcher-
servlet.xml), will automatically register the RequestMappingHandlerMapping bean
15
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
16
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
17
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
18
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.
19
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
20
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…,
21
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
22
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.
23
TilesViewResolver
Resolves view names to protected .jsp resources within the /WEB-INF/jsp directory
25
/WEB-INF/tiles/industry-tiles.xml
In industry-tiles.xml the base layout is extended for view carrier
The body attribute is overridden with the actual JSP (listCarriers.jsp) which will
render the view to populate with the Carrier Objects.
Now from a Controller class, we return the logical view name which will not be a
jsp name but rather a tiles definition name
26
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.
27
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
28
Annotations, annotations and annotations everywhere….
as
29
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
30
@Controller
The @Controller annotation indicates that a particular class serves the role of a
controller
Is a stereotype annotation extending from @Component.
The DispatcherServlet scans such annotated classes for mapped methods and
detects @RequestMapping annotations (see next slides)
31
@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
32
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:
Note that in the above example, the request data is sent as part of the HTTP
request body which is bind to the method parameter using the @RequestBody
annotation
33
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
34
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
Use the @PathVariable annotation on a method argument to bind it to the value of a URI template
variable
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
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
36
@RequestBody
The @RequestBody method parameter annotation indicates that a method parameter should be
bound to the value of the HTTP request body. For example:
37
@ResponseBody
This annotation can be put on a method and indicates that the return type should be written
straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
For example:
The above example will result in the object “SidCarrierInfo” representation (Example: JSON,
XML etc..,) being written to the HTTP response stream.
As with @RequestBody, Spring converts the returned object to a response body by using an
HttpMessageConverter.
38
@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.
39
@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
40
@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
On the model class, add hibernate validator annotations such as @NotNull, @NotEmpty,
@Range, @Min, @Max etc…,
0 to 9999
@Pattern (regex)
Start with “C” or “c”
Followed by exactly 4 digits
1 to 80 chars
41
@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
42
@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:
43
@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
44
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-tutorials/
45
BACKUP
46
SimpleFormController
47
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.
48
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
49
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.
50