我有一个弹簧控制器方法,String
就像整个RequestBody
一样:
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody DTO method(@PathVariable("userId") long userId, @RequestBody String page) {
// Controller contents here
}
以前,我能够发布"裸体"字符串到此方法,即使用字符串作为正文的请求(而不是json对象)。例如(来自chrome dev工具):
在我尝试将Jackson Hibernate 4 module添加到Jackson2ObjectMapperFactoryBean(处理hibernate延迟集合)之后,我的xml配置文件中使用了以下内容,这停止了工作:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="modulesToInstall"
value="com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module"/>
<property name="featuresToEnable">
<array>
<util:constant static-field="com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES"/>
</array>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
像这样自定义ObjectMapper后,我在上面发布请求时收到以下错误:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'Testing': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@5e6a19fe; line: 1, column: 13]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Testing': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@5e6a19fe; line: 1, column: 13]
为此工作(使用角度js)是在发布到API之前调用JSON.stringify()
,因此角度代码变为
$http.post(Url + userId, JSON.stringify(string)).then(function (result) {
return result.data;
});
并且请求变为
在此之后,API就像以前一样工作,接受字符串本身。
虽然我知道没有封装"
的字符串不是有效的JSON字符串,但我不明白为什么在这种情况下更改ObjectMapper bean会产生这样的差异?我使用的是弹簧版本4.3.4和杰克逊版本2.8.5,如果这些都是有用的信息。
答案 0 :(得分:0)
在引入自定义MappingJackson2HttpMessageConverter
之前,您的调度程序servlet配置和依赖关系配置是什么样的?
由于Spring使用您的请求的Content-type
标头来确定要使用哪个消息转换器,当您的请求主体显然不是JSON时,为什么要显式发送application/json
?
正确的“解决方法”是发送Content-type: text/plain
,这将使Spring使用StringHttpMessageConverter
,这也是我在开始配置MappingJackson2HttpMessageConverter