总结下springmvc获取前端传来的json数据方式:

1、以RequestParam接收

前端传来的是json数据不多时:[id:id],可以直接用@RequestParam来获取值

@Autowired
private AccomodationService accomodationService;

@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestParam ("id") int id) {
    int res=accomodationService.deleteData(id);
    return "success";
}

 

2、以实体类方式接收

前端传来的是一个json对象时:{【id,name】},可以用实体类直接进行自动绑定

@Autowired
private AccomodationService accomodationService;

    @RequestMapping(value = "/add")
    @ResponseBody
    public String addObj(@RequestBody Accomodation accomodation) {
        this.accomodationService.insert(accomodation);
        return "success";
    }

3、以Map接收

前端传来的是一个json对象时:{【id,name】},可以用Map来获取

@Autowired
private AccomodationService accomodationService;

@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody Map<String, String> map) {
    if(map.containsKey("id"){
        Integer id = Integer.parseInt(map.get("id"));
    }
    if(map.containsKey("name"){
        String objname = map.get("name").toString();
    }
    // 操作 ...
    return "success";
}

4、以List接收

当前端传来这样一个json数组:[{id,name},{id,name},{id,name},...]时,用List<E>接收

@Autowired
private AccomodationService accomodationService;

@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody List<Accomodation> list) {
    for(Accomodation accomodation:list){
        System.out.println(accomodation.toString());
    }
    return "success";
}

补充4

SpringMVC接收List型参数


1、controller


复制代码
@RequestMapping("/postList")
    @ResponseBody
    public String postList(@RequestBody List<TestL> testL){
        System.out.println(testL);
        return null;
    
    }
复制代码

需要注意点:参数前面必须有注解 @RequestBody


2、ajax请求


复制代码
var testList=[];
var user={};
user.id=1;
user.name='jack';
testList.push(user);
var user2={};
user2.id=2;
user2.name='tom';
testList.push(user2);
$.ajax({
    // headers必须添加,否则会报415错误
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
  type: 'POST',
  dataType: "json", //表示返回值类型,不必须
  data: JSON.stringify(testList),
  url: '/test/postList',
  success: function(){
      alert('success');
  }
  
});
复制代码

需要注意点:1、参数是数组类型


      2、传入data时,转换 JSON.stringify(testList)


      3、必须有headers: {


                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }

最后再看下TestL类,没有特别之处(不用包装)。

复制代码
public class TestL {
    private Integer id;
    private String name;
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
}
复制代码