This is a consequence of how Spring 3.2+ (I don't remember how 3.1 does it) handles @RequestMapping
methods' return values. Spring uses instances of type HandlerMethodReturnValueHandler
to resolve how the value returned should be handled. Go through the javadoc too see the different types.
When you configure your MVC environment, if you use the default @EnableWebMVC
or <mvc:annotation-driven>
, Spring registers these instances in a specific order. This happens in the RequestMappingHandlerAdapter#getDefaultReturnValueHandlers()
method as shown below
private List<HandlerMethodReturnValueHandler> getDefaultReturnValueHandlers() {
List<HandlerMethodReturnValueHandler> handlers = new ArrayList<HandlerMethodReturnValueHandler>();
// Single-purpose return value types
handlers.add(new ModelAndViewMethodReturnValueHandler());
handlers.add(new ModelMethodProcessor());
handlers.add(new ViewMethodReturnValueHandler());
handlers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.contentNegotiationManager));
handlers.add(new CallableMethodReturnValueHandler());
handlers.add(new DeferredResultMethodReturnValueHandler());
handlers.add(new AsyncTaskMethodReturnValueHandler(this.beanFactory));
// Annotation-based return value types
handlers.add(new ModelAttributeMethodProcessor(false));
handlers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.contentNegotiationManager));
// Multi-purpose return value types
handlers.add(new ViewNameMethodReturnValueHandler());
handlers.add(new MapMethodProcessor());
// Custom return value types
if (getCustomReturnValueHandlers() != null) {
handlers.addAll(getCustomReturnValueHandlers());
}
// Catch-all
if (!CollectionUtils.isEmpty(getModelAndViewResolvers())) {
handlers.add(new ModelAndViewResolverMethodReturnValueHandler(getModelAndViewResolvers()));
}
else {
handlers.add(new ModelAttributeMethodProcessor(true));
}
return handlers;
}
When your method returns a value, Spring iterates through these handlers, calling their supportsReturnType()
method and picking the first it finds that returns true
.
In this case, the ModelMethodProcessor
which handles Model
return values has higher priority (is registered before) the RequestResponseBodyMethodProcessor
which handles @ResponseBody
.
As such, you can't return a Model
and have it be converted to JSON through the @ResponseBody
. In my opinion, you shouldn't do this at all. The Model
is accessible to most parts of the DispatcherServlet
stack and therefore many modules can add/remove attributes which you may not want in the final JSON.
Just use a DTO like you have in your second example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…