【问题标题】:Spring MVC POST @RequestBody don't bind to JSON string in the http requestSpring MVC POST @RequestBody 不绑定到 http 请求中的 JSON 字符串
【发布时间】:2011-09-28 19:09:39
【问题描述】:

这是我的 Spring MVC 控制器的 POST 方法的签名

@RequestMapping(value="/createNewGame", method=RequestMethod.POST)
       public ModelAndView createNewGame(@RequestParam(value="phoneNumber") String param,@RequestBody final SampleDTO sampleDTO) {
        Map model2 = new HashMap();
           model2.put("firstname", "Peter");
           model2.put("secondname", "Schmitt");

           return new ModelAndView("jsonView", model2);
     }

这是 SampleDTO 类的定义:

public class SampleDTO implements Serializable{

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

我无法执行此方法的请求。我从客户端收到此错误:

org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.supports(Ljava/lang/Class;)Z

使用带有这些参数的 RestClient 应用程序执行此 POST 请求后:

http://localhost:8080/SpringExample5/createNewGame.json?phoneNumber=6   (POST)

Content-Type application/json  (Header attribute)

{ "value": "a" }      (Body)

这也是我的web应用中Spring的配置:

<bean name="/gameController.json" 
          class="com.alu.server.games.acquisition.controllers.GameController"/>   


<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>

<bean id="jsonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
    <property name="objectMapper">
            <ref bean="JacksonObjectMapper" />
       </property>
</bean>

    <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonHttpMessageConverter" />            
        </list>
    </property>
</bean>

<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="objectMapper">
         <ref bean="JacksonObjectMapper" />
    </property>
</bean>

<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />

有人可以帮我找出问题吗? 提前致谢!

【问题讨论】:

  • 我猜你不需要在spring配置中定义jsonHttpMessageConverter、JacksonObjectMapper等。如果杰克逊类存在于类路径中,则默认添加它们。如果配置正确,则不应调用 MappingJacksonHttpMessageConverter 的 'supports' 方法。
  • 我已经删除了jsonHttpMessageConverter和JacksonObjectMapper的配置。但是现在我有这个错误:服务器拒绝了这个请求,因为请求实体的格式不受所请求方法的请求资源支持有什么想法吗?
  • 从方法中删除 '@RequestParam' 后尝试。我猜@RequestParam 和@RequestBody 不应该一起使用。
  • 如果我离开@RequestParam,也会出现同样的问题。

标签: json model-view-controller spring


【解决方案1】:

在我使用的设置中,我确实在 Web 服务的注释以及 json 消息转换器的 XML 配置中都将媒体类型指定为“application/json”。
请查看我的常见问题解答here 了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多