This is not a trivial problem.
Spring has a common template in which, if the handler method returns null , it should indicate that the handler has already dealt with the creation and writing of the corresponding content of the response and that no further action is required on the front panel.
Spring applied this pattern in its RequestResponseBodyMethodProcesser (implementation of HandlerMethodReturnValueHandler for @ResponseBody ). It checks if the return value is null . It sets the request as processed. If the return value is not null , it attempts to serialize it using the appropriate HttpMessageConverter .
One option is to create your own @ResponseBodyNull annotation and the corresponding HandlerMethodReturnValueHandler , which does the same thing except handles null . Note that you cannot reuse the code from RequestResponseBodyMethodProcess , because some HttpMessageConverters will not be able to use null .
Another similar option is to override RequestResponseBodyMethodProcessor to accept null (with the restrictions mentioned above) and register it explicitly with RequestMappingHandlerMapping , overwriting HandlerMethodReturnValueHandler s by default. You must do this carefully (i.e. register the same ones) if you do not want to lose functionality.
The best solution, IMO, would be to not deal with null in the response body. If getObject nothing, it seems to me 404. Set the appropriate response code and voila!
You can always introduce an HttpServletResponse in your handler method and do something like
Object object = getObject(..); if (object == null) { response.getWriter().print("null");
Assuming you knew this should be serialized in JSON.
source share