Spring Framework
Benefits…
Spring enables developers to develop enterprise-class applications using POJOs.
You do not need an EJB container such as an application server
Use only robust servlet container such as Tomcat
Spring is organized in modular fashion
Worry only about the ones your need and ignore the rest
Spring makes use of the existing technologies easer
ORM frameworks (Hibernate/JPA), JEE, and other view technologies
Testing with spring is easier (Thanks to POJO’s & Spring DI)
Support for various test frameworks such as Junit, TestNG
Spring MVC – a well-designed web MVC framework
Spring provides API to translate technologic-specific exceptions into consistent, unchecked
exceptions (Ex: Exceptions thrown by JDBC, Hibernate)
Spring IOC Container is lightweight compared to EJB containers
Spring has a good transaction management support (Both local [single DB] and global
transactions [JTA])
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 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
Open for extension…. Closed for modification
4
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
5
The Dispatcher Servlet
6
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
7
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…,
8
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
9
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
10
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
11
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
12
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.
13
Annotations, annotations and annotations everywhere….
as
14
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
In this example, the method is called for a URL – “…/app-name/viewCarrier.do”
Call from a JSP: <a href="viewCarrier.do"><spring:message code='carrier.label' /></a>
The methods takes Model as input parameter and return a Model and View Object – The View is
a string which is mapped either to a tiles definition name or an actual jsp file
15
@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)
<context:component-scan base-package="com.tnsi" />
16
@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
17
@RequestParam
Use the @RequestParam annotation to bind request parameters to a method parameter in
your controller
The above method can be invoked something like below:
var actionUrl = "carrier.do?action=" + action + "&id=" + id;
Note that the request params (action & id) are passed as part of the request URL
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
18
@RequestBody
The @RequestBody method parameter annotation indicates that a method parameter should
be bound to the value of the HTTP request body. For example:
HttpMessageConverter is responsible for converting from the HTTP request message to an
object and converting from an object to the HTTP response body.
The RequestMappingHandlerAdapter supports the @RequestBody (and @ResponseBody)
annotations with the a set of default HttpMessageConverters
The <mvc:annotation:driven /> configuration in the DispatcherServlet context configuration
will enable the RequestMappingHandlerMapping and RequestMappingHandlerAdapter beans.
19
@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.
20
@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
21
@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
22
@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:
23
@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
24
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/
25