Spring Framework: what is the purpose of <mvc:annotation-driven /> - spring-mvc

I'm relatively new to Spring and I'm a little confused about the tag.
After going through the documentation and looking around different posts it seems like the main use of is that it is required by Spring MVC to dispatch requests to #Controllers.
I created a controller with two requestMappings:
#RequestMapping(method=RequestMethod.GET, value="/health")
#RequestMapping(method=RequestMethod.GET, value="/test")
I tested the web app with and without in the servlet.xml and it doesn't seem like any difference was made with being omitted or not. The requests seemed to still reach my controller just fine.
Can anyone explain to me what exactly that tag is used for?
Thanks in advance!

The support for #Controller and #RequestMapping is provided by Spring by default. However, by enabling mvc:annotation-driven you get support for processing the requests that are mapped to annotated controller methods, such as declarative validation, formatting and conversion service. An excerpt from spring's blog that introduced the new config features
It applies sensible defaults based on what is present in your
classpath. Such defaults include:
Using the Spring 3 Type ConversionService as a simpler and more robust alternative to JavaBeans PropertyEditors
Support for formatting Number fields with #NumberFormat
Support for formatting Date, Calendar, and Joda Time fields with #DateTimeFormat, if Joda Time is on the classpath
Support for validating #Controller inputs with #Valid, if a JSR-303 Provider is on the classpath
Support for reading and writing XML, if JAXB is on the classpath
Support for reading and writing JSON, if Jackson is on the classpath
Another related usefull blog post
If this tag is not added to the XML, then you will have to manually
define the beans for components like HandlerAdapter, HandlerMapping,
Binding Initializer, Request Message converters, etc. This tag helps
registering the following components.
DefaultAnnotationHandlerMapping - This is a HandlerMapping
implementation which maps the HTTP requests to the handler methods
defined using the #RequestMapping annotation.
AnnotationMethodHandlerAdapter - It is responsible for scanning the
controllers to identify methods (and parameters) annotated with #MVC
annotations. It scans and caches handler methods annotated with
#RequestMapping. Also handles the #RequestParam, #ModelAttribute,
#SessionAttributes and #InitBinder annotations.
ConfigurableWebBindingInitializer - The initializer for the Web Data
Binder. Helps in declaratively configuring the Web Binder with
validators, conversion services, property editors, etc.
LocalValidatorFactoryBean - Implements the validator interface and
enables JSR303 validation. This is injected into
ConfigurableWebBindingInitializer.
FormattingConversionServiceFactoryBean - A conversion factory that
returns conversion services for basic objects like date and numbers.
This factory is again injected into ConfigurableWebBindingInitializer.
Support for Message Converters
Finally a more formal definition in the official docs

Related

How to make Spring ignore #RequestMapping annotations in specific packages

I've been playing around with the concept outlined in this answer, to share a common 'contract' between server and client. I'm trying to use this concept in a Spring MVC application that contains both REST endpoints and a Feign client. The #RequestMappings on the REST endpoints are picked up like normal by Spring, but: it also picks up the #RequestMapping on the abstract API class I use for my Feign client, i.e., in terms of the linked example, I have a UserService and UserClient in my code, and Spring picks up the #RequestMapping in the UserService class.
I don't understand why this happens in the first place, because:
The UserService class is an interface. Why and how does Spring think it can map an endpoint to an interface method?? This will obviously never work.
The package containing UserService is not included in the basePackage list of the #ComponentScan annotation on my Application class
Any clues on how I can convince Spring to just ignore all classes in this package??
So apparently this is a known issue, see this thread for ways to fix it.

Difference between #RestController and #RepositoryRestController

What is the typical use case code that shows the difference between those two annotations - meaning the #RestController and the #RepositoryRestController - ?
According to the annotation the RepositoryRestController is a way to provide custom controllers that still take advantage of Spring Data REST functionality.
Spring Data REST Reference Guide, 15.6. Overriding Spring Data REST Response Handlers:
Sometimes you may want to write a custom handler for a specific
resource. To take advantage of Spring Data REST’s settings, message
converters, exception handling, and more, use the
#RepositoryRestController annotation instead of a standard Spring MVC
#Controller or #RestController.
Most importantly the RepositoryRestController is aware of the Spring Data REST base path and will be served under this base path.

what are the Spring MVC Corresponding Components for Model, View, and Controller?

I'm new to spring 3. I studied several tutorials about springmvc, but I can't separately identify what are the corresponding components for model view and controller?
Like in struts2
model-action class
view-jsp
controller - filterDispatcher
Can anyone help me to identify these components clearly?
In Spring MVC, a Controller is usually a Plain java class annotated with #Controller, a View is anything that implements org.springframework.web.servlet.View and the model is usually a ModelMap, a specialized Map implementation.
In a standard setup, a controller method usually returns either a String or a business object.
If it returns a String, that is interpreted as a path to the view name (JSP, Freemarker etc.). If it is a business object and the method is annotated with #ResponseBody, then content negotiation starts, one of the key features of Spring MVC. Depending on configurable aspects like the Accept: header, the path extension etc. Spring automatically serializes the business object to JSON, XML, PDF etc.
The whole mechanism is explained in the Spring Reference under
Spring MVC: Implementing Controllers

SpringMVC lifecycle-- the overall view

I'm way new to Spring.
I am looking to verify the following understanding of SpringMVC lifecycle-- to put things into places in the overall view:
The entire process is request-driven.
There is a Front Controller pattern and the Front Controller in Spring MVC is DispatcherServlet.
Upon every incoming request from the user, Spring manages the
entire life cycle as described in here.
In the overall view, DispatcherServlet dispatches the request to a controller for a service at the back-end.
Once this is done, it hands it in to the View component of MVC for its view to be prepared in response to the user.
In more detail,
DispatcherServlet uses Handlers to decide "which controller" to serve that request.
The controllers are/should be "light-weighted"-- should be decoupled from
the service processes at back end as a good design practice-- they hold references to the service(s) and invoke the right one(s).
Their "mission" is to control the service process(es) for building the model and handing
it back to the dispatcher for the next step.
The View component in itself has 2 parts: first the ViewResolver picks the right type of look for View to put the model into the final format for the user.
From the developer's angle-- the DispatcherServlet is a behind-the-scenes thing.
All i do is to define, and configure it, if necessary, in web.xml.
As the developer, I instantiate an ApplicationContext (there are many ApplicationContext types-- i pick one depending on what i need, typically the
WebApplicationContext(?) ). AplicationContext is the factory that creates all the servlets/beans including
the DispatcherServlet, using their descriptions in the .xml files. The DispatcherServlet then runs behind the scenes and manages the
entire process-- goes&gets the controllers, using the annotations or the their .xml descriptions,
views, handlers, validators etc.
I am wondering whether this description is holds-- valid&complete, and whether there are big missing pieces in it.
Thanks in advance.
Let's go into detail step by step
DispatcherServlet uses Handlers to decide "which controller" to serve
that request
The DispatcherServlet maintains an ordered List of HandlerMapping beans (which it loaded from the WebApplicationContext). A HandlerMapping is
Interface to be implemented by objects that define a mapping between
requests and handler objects.
When the DispatcherServlet receives a request, it iterates over this list until it finds a matching handler object for the request in question. For simplicity, let's consider only RequestMappingHandlerMapping.
A bean of this type stores a mapping of #RequestMapping annotated methods (the actual Method object retrieved with reflection) stored as a HandlerMethod instances and wrapped in RequestMappingInfo objects that hold mapping data for matching the request, ie. URL, headers, and request parameters.
The DispatcherServlet retrieves the best matching HandlerMethod from these and any corresponding HandlerInterceptor instances which you may have registered. It retrieves these as a HandlerExecutionChain object. It will first apply any pre-handling by HandlerInterceptors. It will then try to invoke your HandlerMethod. This will typically (but not always) be a #RequestMapping annotated method inside a #Controller annotated class. This produces what Spring calls a dispatch result. The DispatcherServlet then applies post-handling by the HandlerInterceptors. It finally processes the dispatch result depending on what it is. You can see the supported return types for an idea of what that can be.
The controllers are/should be "light-weighted"-- should be decoupled
from the service processes at back end as a good design practice--
they hold references to the service(s) and invoke the right one(s).
Their "mission" is to control the service process(es) for building the
model and handing it back to the dispatcher for the next step.
In an MVC application, the controller controls operations by making changes to the model. You can do this directly in your controller or you can decouple it by implementing and providing service and business classes for that purpose. The controller depends on these, but not the other way around. Check out multilayered architectures.
The controller then builds the model (Model) which the DispatcherServlet possibly makes available to the view. I say possibly because the controller can produce a response directly without any view (think jsp) involved.
The View component in itself has 2 parts: first the ViewResolver picks
the right type of look for View to put the model into the final format
for the user.
In the typical case where the Controller handler method would return a Model, View, ModelAndView, String (and some others) object, then a ViewResolver would handle finding the correct View. The DispatcherServlet then tries to render that view by first merging the model as you said. This usually means taking all Model attributes and putting them into the HttpServletRequest attributes. The rendering step can involve rendering a jsp, generating XML, or anything at all really.
From the developer's angle-- the DispatcherServlet is a
behind-the-scenes thing. All i do is to define, and configure it, if
necessary, in web.xml. As the developer, I instantiate an
ApplicationContext (there are many ApplicationContext types-- i pick
one depending on what i need, typically the WebApplicationContext(?)
).
You don't actually need to instantiate it. The DispatcherServlet will do that itself (or use the ContextLoaderListener's) when the Servlet container calls init() on it. It will generate its own WebApplicationContext. What you can do is decide which subclass of WebApplicationContext to use. This is an important choice if you want to load your context from XML or from a Java configuration. You can do this by providing an <init-param>.
AplicationContext is the factory that creates all the servlets/beans
including the DispatcherServlet, using their descriptions in the .xml
files. The DispatcherServlet then runs behind the scenes and manages
the entire process-- goes&gets the controllers, using the annotations
or the their .xml descriptions, views, handlers, validators etc.
The ApplicationContext is also known as the Inversion of Control Container. It does not include the DispatcherServlet. The DispatcherServlet is managed by the Servlet container and not by Spring. However, it does primarily take its configuration from Spring's ApplicationContext (WebApplicationContext). It registers a number of special beans it finds in the context. You can declare these yourself or let Spring do it for you with this little bit of XML
<mvc:annotation-driven>
This will (mostly) take care of doing what you describe, ie. registering handlers, validators, views, etc.
I am wondering whether this description is holds-- valid&complete, and
whether there are big missing pieces in it.
Don't forget that a Spring MVC web application is a Servlet web application. The lifecycle of the application is therefore tied to the Servlet container.
There is no good answer to your question. "Sure" is as close as I can get.
You can configure spring using xml files or annotations or a combination of both.
You don't need to write servlets with Spring MVC, but you can if you want. Mostly you can (maybe should) create controller classes (either by extending a Spring controller class or marking a class with the #Controller annotation).
The "mission" of the controller is to perform necessary processing of requests. They do not just "control service processes"
There is no "hand it back" to the dispatcher.
The DispatchServlet must be configured in the web.xml file,
this is never optional.
You can (maybe should) have a layer between your controller classes and any web services that you will call from the controller classes.
You can have multiple applicationContexts or use a single applicationContext.
As often as not,
the View is a JSP file.
The Controller should add DTOs (data transfer objects) that are used by the view to display non-static information.
EDIT: I removed the mention of VO objects, I (like many, it seems) incorrectly conflated DTO and VO patterns.
There is no "behind the scenes".
The DispatcherServlet receives a request and passes it to the appropriate controller for processing.
Read section 17 of the Spring Framework Reference

Spring MVC interceptor vs Sitemesh

In a Spring MVC application using Sitemesh to decorate my views, I want to inject into every Model a security attribute called sec of type WebSecurityExpressionRoot.
This way I could call hasAnyRole(), hasAuthority()... in all my views so administrators would be presented extra stuff by the underlying templating engine (Thymeleaf BTW).
A custom HandlerInterceptorAdapter with an overridden postHandle(...) seems to be Spring MVC's way of accomplishing this, but it seems that my master Sitemesh decorator is kind of stealing my security attribute, because whenever I try to reference in some views it is null.
BUT only the views rendered after one of my controllers are affected, the ones
mapped with mvc:view-controller do have the sec attribute.
I'm considering writing a Filter to stash sec into the current HttpServletRequest to solve this issue but I'm maybe missing something.
Thanks in advance!
Are you sure the mvc:view-controller views/path are hitting the interceptor?
Also, I don't know about Thymeleaf, but using JSPs (eg, JstlView) makes Spring MVC copy Model into Request attributes (for purposes of rendering the view) -- the fact that Sitemesh also gets the values via request attributes is, I think, a consequence.

Resources