How to stop implicit enriching of model with command object in Spring handlers when dispatching to View?
if you look at the handler return types, it all says, that the model is enriched with commandObject before it gets to a View.
How to stop it ? I want to return only data that I set in the handler to get into the View, not the commandObject that was passed to the handler.
Map map = new HashMap();
map.put("sucess", "sucess");
return new ModelAndView("ajaxResponse", map);
It's because Spring's AnnotationMethodHandler开发者_开发知识库Adapter processing, it is merged for every return type.
if (returnValue instanceof ModelAndView) {
ModelAndView mav = (ModelAndView) returnValue;
mav.getModelMap().mergeAttributes(implicitModel);
return mav;
}
else if (returnValue instanceof Model) {
return new ModelAndView().addAllObjects(implicitModel).addAllObjects(((Model) returnValue).asMap());
}
else if (returnValue instanceof View) {
return new ModelAndView(returnValue).addAllObjects(implicitModel);
}
else if (handlerMethod.isAnnotationPresent(ModelAttribute.class)) {
addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel);
return new ModelAndView().addAllObjects(implicitModel);
}
else if (returnValue instanceof Map) {
return new ModelAndView().addAllObjects(implicitModel).addAllObjects((Map) returnValue);
}
else if (returnValue instanceof String) {
return new ModelAndView((String) returnValue).addAllObjects(implicitModel);
}
From the comments it looks like you're rendering JSON as response. When using Jackson (one of Spring's default options for JSON processing), you can specify "RenderedAttributes" so that not all fields of your model get put into the response JSON but only those you explicitly specify.
"By default, the entire contents of the model map (with the exception of framework-specific classes) will be encoded as JSON. For cases where the contents of the map need to be filtered, users may specify a specific set of model attributes to encode via the RenderedAttributes property." (from the reference guide, section 16.10
Add Spring's ModelMap to handler method and clear it. After dispatching to VIEW, there won't be any implicitModel stuff.
public ModelAndView handleRequest(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
modelMap.clear();
...
}
What Spring calls model in the controller method is actually a dump of objects, that will be exposed to the view. You shouldn't use all of it as the response data for a request. Your response data may be a part of it.
I suggest you try returning the map that you want to be converted to JSON annotated with @ResponseBody. You will need Jackson on the classpath. Spring will do the conversion. Or if you want to stick to your solution, place your map to the model map under some standard key, e.g. "response".
精彩评论