@RequestBody无法正常工作 - 返回Http状态415 Jquery中不支持的媒体类型

时间:2012-02-11 06:48:59

标签: ajax json spring-mvc

我正在使用Spring 3.1来开发我的项目。在工作期间,我坚持了一点,真的需要你的帮助。

我的要求是来自客户端我将收到JSON对象并且也将返回JSON对象。当我使用从服务器发送的发送和删除请求时,我成功实现了相同的功能。但是,当我使用PUT方法发送我的数据时遇到一些问题。由于PUT无法在@ModelAttribute中接收数据,因此我使用@RequestBody注释来接收从客户端发送的数据。

当我使用@RequestBody MultiValueMap<String, String>正文时出错

  

Http Status 415不支持的媒体类型。

当我尝试使用@RequestBody DemandBean(我的项目Bean)接收数据时,收到以下错误。

  

org.codehaus.jackson.JsonParseException:意外字符('o'(代码111)):预期有效值(数字,字符串,数组,对象,'true','false'或'null')   在[来源:org.apache.catalina.connector.CoyoteInputStream@19 d688; line:1,column:2]

但是我很确定我已经正确映射了我的jackson库,因为使用@RequestBody我可以将json接收回客户端并且还可以发送Json并且spring可以使用@ModelAttribute解析方法是GETPOSTDELETE

下面我给出了代码:

Html FIle发送数据:

 var jsonStr = $("#searchDemand_frm").serializeArray();

 $("#searchResultTable td").remove();

 alert(JSON.stringify(jsonStr)); // Return proper form data in json format

 $.ajax({
    contentType : "application/json",
    dataType : 'json',
    type : "PUT",
    url : targetUrl,
    data : jsonStr,
    async : false,
    success : function(data) {
       alert("In Success");
    },
    error : function(request, status, error) {
       showPermissionDenied(request);
    }
});

Json格式发送到服务器:

[{"name":"opportunityId","value":"ad"},{"name":"dem andId","value":"hgh"},{"name":"demandCreator","val ue":"hghhgh"},{"name":"demandOwner","value":"hg"}, {"name":"status","value":"IP"},{"name":"region","v alue":"hgh"}]

-servlet.xml后缀:

<mvc:annotation-driven />

<context:component-scan base-package="com.ericsson.rms.controller.*" />
<context:component-scan base-package="com.ericsson.rms.application.authorizatio n" />
<context:annotation-config/>

<aop:aspectj-autoproxy proxy-target-class="true" />

<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>
</bean>

控制器类:

@RequestMapping(method = RequestMethod.PUT)
public @ResponseBody
   List<DemandBean> searchDemandDetailsWithPut(@RequestBody DemandBean demand, 
                                               HttpServletResponse response) throws IOException {
}

2 个答案:

答案 0 :(得分:1)

尝试将您从一组对象提交的json更改为包含其他对象的对象,即:

{{"name":"opportunityId","value":"ad"},{"name":"dem andId","value":"hgh"},{"name":"demandCreator","val ue":"hghhgh"},{"name":"demandOwner","value":"hg"}}

而不是

[{"name":"opportunityId","value":"ad"},{"name":"dem andId","value":"hgh"},{"name":"demandCreator","val ue":"hghhgh"},{"name":"demandOwner","value":"hg"}]

答案 1 :(得分:0)

我有一个类似的问题,在我的情况下,问题不是ajax帖子:因为我已经将ajax调用与单击表单按钮关联,在发出ajax请求后表单已提交并导致错误。阻止提交表单解决了问题:

$('#btn_confirm').click(function (e) {
    e.preventDefault();     // do not submit the form
    // your ajax call here
}