Spring Ajax - @ResponseBody - Returning null response
When the user is not logged in, the expected behavior is to return null
That's my expected behaviour because in both Java and Javascript/JSON, null is a valid value, which have a different mean than nothing, empty or error/exception.
I would expect that Spring answer the null response instead of handling it specifically.In that case, the expected convertion for null (Java) would be null (JSON)
My expected conversion table:
Java Exception => HTTP Error Codenull => nullempty map / object => {}void => no response
Why is this happening ?
For Spring, a controller returning null mean "No response" and not "a response which value is null". This rule applies to all controller methods including ones with @ResponseBody annotation.
This allow to write manually to the response without having something appended to the response later:
if (mySpecialCase) { Writer writer = response.getWriter(); writer.write("my custom response"); return null;} else { return myObject;}
So when returning null Spring write nothing to the response, nor Content-type header nor body.
Do I have solutions to obtain the expected behaviour ?
I made the following dirty hack: add a filter on my ajax path that write null to the response when no response have been commited.
public class AjaxEmptyResponseFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); if (!response.isCommitted()) { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); Writer writer = response.getWriter(); writer.write("null"); writer.close(); response.flushBuffer(); } }}
This solution handle methods answering null and method answering nothing (void) the same way.
Do you have a session filter?
I think, you can bind a global ajax event for errors and make your respective validation there.
here is a example on a similar case: How to handle expired session using spring-security and jQuery?