java spring项目controller中接收一个string,和一个List为入参报错,前端参数应该怎么传?

只接收一个List作为入参的话不报错,
下方为代码:
前台:
$.ajax({

    type:"post",
    url: 'add',
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    data:JSON.stringify([{id:1,name:"hello"},{id:2,name:"hello"}]),
    success:function(data){
        console.log(data);
    }
})

后台:
@ResponseBody

@RequestMapping(value = "add", consumes = "application/json; charset=utf-8")
public String add(@RequestBody List<Tag> param) {
    System.out.println("param:" + param);
    return "成功";
}

前台控制台显示的数据格式为:
[{id: 1, name: "hello"}, {id: 2, name: "hello"}]
0:{id: 1, name: "hello"}
1:{id: 2, name: "hello"}

那如果我后台想接受一个字符串和一个list该怎么写呢,

后台代码改为:
@ResponseBody

@RequestMapping(value = "add", consumes = "application/json; charset=utf-8")
public String add(@RequestBody String content, @RequestBody List<Tag> param) {

前台应该怎么写?
LEATH
浏览 531回答 2
2回答

冉冉说

两种解决方案1、如果参数比较少 直接url?parm=value, 那么就用@RequestParam注解2、封装成对象 class A { private String parm1; private String parm2; private List<B> list; } 对应的前台 var data =new Object; data.param1="value"; data.param2="value"; var list = new Array(); ....省略list的数据初始化 data.list = list; ajax的data data:JSON.stringify(data)

猛跑小猪

@ResponseBody 接收的是前台你用 JSON 传递过来的一个整体,所以你前台需要将 String 和 List 封装在一个对象里面。 var json = {}; json['content'] = content; json['param'] = [{id: 1, name: "hello"}, {id: 2, name: "hello"}]; // ajax data data:JSON.stringify(json) 后台接收的话,建议是写一个对象来接收比如, public class SomeModel { private String content; private List<Tag> param; // getter and setter } controller @RequestMapping(value = "add", consumes = "application/json; charset=utf-8") public String add(@RequestBody SomeModel someModel) { String content = someModel.getContent(); List<Tag> param = someModel.getParam(); } 或者可以偷懒,用 Map 来接收。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java