【发布时间】:2012-03-03 13:11:54
【问题描述】:
我正在使用 Spring 3.1 来开发我的项目。在工作期间,我卡在一个点上,真的需要你的帮助。
我的要求是来自客户端,我将接收 JSON 对象并将返回 JSON 对象。当我使用从服务器发送的获取发布和删除请求时,我成功地实现了相同的功能。但是当我使用PUT 方法发送我的数据时遇到了一些问题。因为PUT 无法接收@ModelAttribute 中的数据,所以我使用@RequestBody 注释来接收我从客户端发送的数据。
当我使用@RequestBody MultiValueMap<String, String> body 时出现错误
Http Status 415 媒体类型不受支持。
当我尝试使用 @RequestBody DemandBean(我的项目 Bean)接收数据时,我收到以下错误。
org.codehaus.jackson.JsonParseException:意外字符('o'(代码 111)):需要一个有效值(数字、字符串、数组、对象、'true'、'false' 或 'null') 在 [来源:org.apache.catalina.connector.CoyoteInputStream@19 d688;行:1,列:2]
但我很确定我已经正确映射了我的 jackson 库,因为使用@RequestBody 我可以将 json 接收回客户端,也可以发送 Json 并且 spring 可以使用@ModelAttribute 解析,以防方法为GET ,POST,DELETE.
下面我给出代码:
Html 文件发送数据:
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 {
}
【问题讨论】:
标签: ajax json spring-mvc