ajax+post+json+@requestBody走天下

来源:互联网 发布:js控制标签显示隐藏 编辑:程序博客网 时间:2024/05/19 03:44
  1. 什么js对象,json对象,json字符串?它们又长什么样呢?
    js对象:jsObj
    json对象:jsonObj
    json字符串:jsonString
    这里写图片描述

  2. ajax如何发post?

    1:定义json对象var obj = {"factoryId":Id};
    2:写$.ajax

    $.ajax({
    type:”POST”,
    url: “/ASW/wxcurrent.html”,
    data:JSON.stringify(jsonObj),
    dataType: “json”,
    contentType:”application/json”,
    success:function(result){
    console.log(success);
    },
    error:function(){
    alert(“error”);
    }
    })

解释一波:ajax可以发送三种格式的请求+数据

post+json字符串(最常用的方式):post+json对象:get+查询字符串

3.@requestBody接收json字符串
点击:Understanding @RequestBody
网上几乎博客的思路都是:在Java服务端见一个bean或java对象类,MappingJacksonHttpMessageConverter会将json数据转换成这个java对象来属性值。
官方对@requestBody的解释是:
(1)For access to the HTTP request body. Body content is converted to the declared method argument type using HttpMessageConverters.

(2)The @RequestBody method parameter annotation indicates that a method parameter should be bound to the value of the HTTP request body

这里写图片描述

这里写图片描述

看这个下面这个举例,可以知道可以直接获取基本数据类型String,并不是只可以获取引用类型(java对象)

比如:我要获取factortId的值,我的方法参数类型就得是拥有factortId属性的Factory类,

@RequestMapping(value = "/wxcurrent",method=RequestMethod.POST,consumes="application/json")@ResponseBodypublic void wxfactoryCur(@RequestBody Factory factory, HttpServletResponse response) {    System.out.println("factory:"+factory);    System.out.println("factoryId:"+factory.getFactoryId());}

Factory实体类

package cn.edu.hdu.Entity;public class Factory {    private Integer factoryIndex;    private Integer factoryId;    private String systemName;    private String pc_ph;    private Integer modelNum;    private Integer modelId;    public Integer getFactoryIndex() {        return this.factoryIndex;    }    public void setFactoryIndex(Integer factoryIndex) {        this.factoryIndex = factoryIndex;    }    public Integer getFactoryId() {        return this.factoryId;    }    public void setFactoryId(Integer factoryId) {        this.factoryId = factoryId;    }    public String getSystemName() {        return this.systemName;    }    public void setSystemName(String systemName) {        this.systemName = systemName;    }    public String getPc_ph() {        return this.pc_ph;    }    public void setPc_ph(String pc_ph) {        this.pc_ph = pc_ph;    }    public Integer getModelNum() {        return this.modelNum;    }    public void setModelNum(Integer modelNum) {        this.modelNum = modelNum;    }    public Integer getModelId() {        return this.modelId;    }    public void setModelId(Integer modelId) {        this.modelId = modelId;    }}
阅读全文
0 0