簡體   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