【问题标题】:Spring MVC @RequestBody not working with jquery ajax?Spring MVC @RequestBody 不能与 jquery ajax 一起使用?
【发布时间】:2018-03-19 20:24:36
【问题描述】:

这是我的ajax请求

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

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

              }

    })

这是我来自 spring xml 的相关 sn-p

<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,它就会起作用。但我想将 json 请求映射到 @RequestBody 的 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 and JSON - making it work together但没有帮助

【问题讨论】:

    标签: java jquery json ajax spring-mvc


    【解决方案1】:

    事实上,当我检查 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&and=`

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

    【讨论】:

    • 我在列表中有数据,当我执行 JSON.stringify(data) 时它将变为空白,editForm.credentials=[{attribute:'username', value:'t2'}, {attribute:'password', value:'t2'}]; 同样在邮递员中工作。$.ajax({url : getContextPath()+ "/abc/update", type : 'POST', data : dataTosend, contentType : 'application/json', success : function(data) {} });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    相关资源
    最近更新 更多