我将我的 messageconverter 配置为 Jackson 的 then
class Foo{int x; int y}
在 Controller 中
@ResponseBody
public Foo method(){
return new Foo(3,4)
}
我希望从服务器返回一个 JSON 字符串 {x:'3',y:'4'} 而无需任何其他配置。但是我的 ajax 请求得到 404 错误响应
If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. The return value will be converted to the declared method argument type using HttpMessageConverters.
我错了吗?或者我应该使用序列化程序自己将我的响应对象转换为 Json 字符串,然后将该字符串作为响应返回。(我可以正确地做出字符串响应)还是应该进行一些其他配置?比如为 Foo 类添加注解
这是我的 conf.xml
<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"/>
</list>
</property>
最佳答案
您需要以下内容:
<mvc:annotation-driven />
在 spring.xml
org.codehaus.jackson:jackson-mapper-asl
)。如下使用:
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public @ResponseBody Foo method(@Valid Request request, BindingResult result){
return new Foo(3,4)
}
这对我有用。
请注意,
@ResponseBody
应用于返回类型,而不是方法定义。@RequestMapping
注释,以便 Spring 检测到它。https://stackoverflow.com/questions/2259551/