繁体   English   中英

Spring MVC @RequestBody不能与jQuery Ajax一起使用?

[英]Spring MVC @RequestBody not working with jquery ajax?

这是我的ajax请求

var dataModel = {name1:"value1", name2:"value2"};

$.ajax({
              url: "/testURL",
              type: "POST",
              async: false,
              contentType: "application/json",
              data: dataModel,
              success: function(response) {

              }

    })

这是我从Spring XML的相关片段

<annotation-driven>
        <!-- Message converters are added to use custom object mapper in  MappingJackson2HttpMessageConverter.
            StringHttpMessageConverter is required to avoid MappingJackson2HttpMessageConverter from converting a string into json.
        -->
        <message-converters>
            <beans:bean
                class="org.springframework.http.converter.StringHttpMessageConverter">
            </beans:bean>
            <beans:bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <beans:property name="objectMapper" ref="jacksonObjectMapper"/>
            </beans:bean>
        </message-converters>
    </annotation-driven>

这是我的控制器映射

    @RequestMapping(value = "/testURL", method = { RequestMethod.POST })
    public String add(HttpServletRequest request, @RequestBody CustomObject customObject) throws Exception {}

但是我的请求甚至没有到达控制器。 一旦删除@RequestBody CustomObject customObject它就会起作用。 但是我想用@RequestBody将json请求映射到CustomObject,这没有发生。 不知道我在这里想念什么吗?

实际上,当我检查request.getParameterMap()它显示为空,但是一旦删除contentType: "application/json"我看到参数映射已填充,但仍然低于错误

`The server refused this request because the request entity is in a format not supported by the requested resource for the requested method`

这是我的CustomObject定义

public class CustomObject implements Serializable {

private static final long serialVersionUID = 1L;
private String name1;
private String name2;

//getters and setters
}

已经通过JQuery,Spring MVC @RequestBody和JSON-使其可以一起使用但无济于事

实际上,当我检查request.getParameterMap()时,它显示为空,但是一旦我删除contentType:“ application / json”

没错 原因与contentType: "application/json" jQuery在内部将数据转换为字符串。 因此没有请求参数。 如果没有contentType: "application/json" ,则默认的contentType' is form data . So data sent is converted to request parameters based on delimiters contentType' is form data . So data sent is converted to request parameters based on delimitersand =` contentType' is form data . So data sent is converted to request parameters based on delimiters

还尝试data: JSON.stringify(dataModel) ,它应该可以工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM