I was creating file upload using ExtJS 4 frontend and Spring 3 as backend. File upload works, but the response from server has wrong content type. When I send {success:true} using Map<String, Object> serialized by Jackson, ExtJS returns error
Uncaught Ext.Error: You're trying to decode an invalid JSON String: <pre style="word-wrap: break-word; white-space: pre-wrap;">{"success":true}</pre>
Why is my response wrapped with <pre> tag? I’ve searched and found out that I should change response type to text/html for example. But changing content type in servlet response didn’t help
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> upload(
FileUpload uploadItem, BindingResult result, HttpServletResponse response) {
response.setContentType("text/html");
// File processing
Map<String, Object> jsonResult = new HashMap<String, Object>();
jsonResult.put("success", Boolean.TRUE);
return jsonResult;
}
When I change return value of upload method to String, everything works correctly, but I want to return Map and have it serialized by Jackson
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String upload(
FileUpload uploadItem, BindingResult result, HttpServletResponse response) {
// File processing
return "{success:true}";
}
My Spring configuration
<bean
id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
</bean>
<bean
id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
<ref bean="stringHttpMessageConverter" />
</list>
</property>
</bean>
How to tell Spring to return correct content type? Why is response of this method incorrect when response of other methods is interpreted correctly?
Well, not really the best solution, but it solves the problem. I’ve created class, which has
Mapinside and method for adding parameters intoMap. Also there is implemented methodtoString().So when
Uncaught Ext.Error: You're trying to decode an invalid JSON Stringoccurs, you simply do thisIn other methods which doesn’t have problem with serialization you can simply call
return response;and it will be automatically serialized.Method
toString()will work only for simple classes such as String. For more complicated classes you’ll have to change it.