测试jquery中ajax的post提交与springController接收的一些疑问

1.@RequestBody String类型可接收 ajax中data为对象的数据,并以key=value(utf-8编码)展现:

  • ajax提交:
    data:{aa:"你好 中国 中国"},
    contentType:"application/json"

  • controller接收:
    接收方式
    接收结果
    如果stringify处理过data, map的值就是正常的json串

  • 两点需要注意:

    1.jquery的ajax会把object对象string化
    2.contentType=”application/json”,未指定编码格式,data的中文编码均utf-8格式编码,contetnType如下设置编码格式均无效,
    //contentType:”application/json”,
    contentType:”application/json; charset=gbk”,
    //contentType:”application/json;charset=utf-8”
    并且页面设置了meta依然无效:meta charset=”gbk”

2.data不是json格式时,@RequestBody String body,接收,接口返回400错误(aa没有加双引号,使用了stringify,不加引号也可正常发送)

  • 使用json.stringify()

    //data:{aa:”你好 中国 中国5”}改为下面的方式:
    data:JSON.stringify({aa:”你好 中国 中国5”}),

    否则报错:Status Code: 400 Bad Request

    使用实体接收也是400
    @RequestBody ReceiveModel model

3. 使用JSON.stringify处理data,但不设置contentType=application/json时(默认 application/x-www-form-urlencoded; charset=utf-8)

  • 此时 @requestbody String body 的值会有些特别
    bb=bb&%7B%22aa%22%3A%22%E4%BD%A0%E5%A5%BD++%E4%B8%AD%E5%9B%BD++%E4%B8%AD%E5%9B%BD5%22%7D=
    解码后:bb=bb&{“aa”:”你好 中国 中国5”}=,即body的值作为一个key传入了

  • 此时 @requestbody Entity entity 则报415错误:415 Unsupported Media Type

  • 因此应该呆以认为:x-www-form-urlencoded:charset=utf-8传上来的body都是string类型

4. ajax不使用json.stringify处理data, 后台用@requestbody Entity entity 接收(默认的contentType:x-www-form-urlencoded)

data:{"aa":"你好  中国  中国"},
@RequestBody ReceiveModel model

报错:415 Unsupported Media Type

使用 @requestbody  String body依然报错:
报错:415 Unsupported Media Type

- 不使用json.stringity, 无论是entity还是string都无法接收body

5. List与数组均可以接收 data中的数组属性

实体属性:
private List<String> names;

private String[] names2;

ajax data:
data:JSON.stringify({aa:"你好  中国  中国5","names":    ["a","b","c"],"names2":["a","b","c"]}),
原创文章 20 获赞 21 访问量 3万+

猜你喜欢

转载自blog.csdn.net/lanxing_huangyao/article/details/82315372