提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 案例1
- 乘客个人信息
- 方法1:表单提交,以字段数组接收
- 方法2:表单提交,以BeanListModel接收
- 方法3:==将Json对象==序列化成Json字符串提交,以List接收
- 3.1 List<Map<String,Object>
- 3.2 List< User>
- 案例 2:后台接受数组和集合的案例
- 基本user配置
- 场景1: POST提交 -前端传==数组==后台如何接受
- ["2021","2022"]
- 数组 String [ ] 接
- List< String>接
- 场景2: get提交 :前端在URL里面传id1,id2后台如何接受?
- 场景3: 前端传==对象集合==后台如何接受?
- 场景4 :综合情况
案例1
我要在一个表单里同时一次性提交多名乘客的个人信息到SpringMVC,前端HTML和SpringMVC Controller里该如何处理?
乘客个人信息
public class User {private Integer id;private String name;private String pwd;@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", pwd='" + pwd + '\'' +'}';}// .......后面还有getter、setter方法,省略了}
方法1:表单提交,以字段数组接收
- HTML代码如下:
<form action="/user/submitUserList_1" method="post">ID:<input type="text" name="id"><br/>Username:<input type="text" name="name"><br/>Password:<input type="text" name="pwd"><br/><br/>ID:<input type="text" name="id"><br/>Username:<input type="text" name="name"><br/>Password:<input type="text" name="pwd"><br/><br/><input type="submit" value="submit"></form>
- Java代码如下:
@RequestMapping(value = "/submitUserList_1", method ={RequestMethod.POST})@ResponseBodypublic String submitUserList_1(HttpServletResponse response,Integer[] id, String[] name, String[] pwd)throws Exception{String result = "";if(id == null || id.length <= 0){ return "No any ID.中文"; }List<User> userList = new ArrayList<User>();for (int i = 0; i < id.length; i++ ) {User user = new User();user.setId(id[i]);user.setName(name[i]);user.setPwd(pwd[i]);userList.add(user);}result = this.showUserList(userList);return result;}
方法2:表单提交,以BeanListModel接收
- HTML代码如下:
<form action="/user/submitUserList_2" method="post">ID:<input type="text" name="users[0].id"><br/>Username:<input type="text" name="users[0].name"><br/>Password:<input type="text" name="users[0].pwd"><br/><br/>ID:<input type="text" name="users[2].id"><br/>Username:<input type="text" name="users[2].name"><br/>Password:<input type="text" name="users[2].pwd"><br/><br/><input type="submit" value="Submit"></form>
- 除了刚才公用的User类,还要封装一个User的容器类UserModel:
public class UserModel {private List<User> users;public List<User> getUsers() {return users;}public void setUsers(List<User> users) {this.users = users;}public UserModel(List<User> users) {super();this.users = users;}public UserModel() {super();}}
- SpringMVC Controller方法:
@RequestMapping(value = "/submitUserList_2", method ={RequestMethod.POST})@ResponseBodypublic String submitUserList_2(UserModel users)throws Exception{String result = "";List<User> userList = users.getUsers();if(userList == null || userList.size() <= 0){ return "No any ID.中文"; }result = this.showUserList(userList);return result;}
方法3:将Json对象序列化成Json字符串提交,以List接收
- HTML代码:
<head><title>submitUserList_3</title><meta http-equiv="content-type" content="text/html; charset=utf-8"><script language="JavaScript" src="/js/jquery.min.js" ></script><script language="JavaScript" src="/js/jquery.json.min.js" ></script><script type="text/javascript" language="JavaScript">function submitUserList_3() {alert("ok");var customerArray = new Array();customerArray.push({id: "1", name: "李四", pwd: "123"});customerArray.push({id: "2", name: "张三", pwd: "332"});$.ajax({url: "/user/submitUserList_3",type: "POST",contentType : 'application/json;charset=utf-8', //设置请求头信息dataType:"json",//data: JSON.stringify(customerArray), //将Json对象序列化成Json字符串,JSON.stringify()原生态方法data: $.toJSON(customerArray), //将Json对象序列化成Json字符串,toJSON()需要引用jquery.json.min.jssuccess: function(data){alert(data);},error: function(res){alert(res.responseText);}});}</script>
</head><body><h1>submitUserList_3</h1><input id="submit" type="button" value="Submit" onclick="submitUserList_3();">
</body>
3.1 List<Map<String,Object>
@RequestMapping("/createOrder")@ResponseBodypublic int createOrder(@RequestBody List<Map<String,Object>> list ){if (list != null && list.size() > 0){result = this.showList(users);return result;}return 0;}
3.2 List< User>
- Java代码:
@RequestMapping(value = "/submitUserList_3", method ={RequestMethod.POST})@ResponseBodypublic String submitUserList_3(@RequestBody List<User> users)throws Exception{String result = "";if(users == null || users.size() <= 0){ return "No any ID.中文"; }result = this.showUserList(users);return result;}
案例 2:后台接受数组和集合的案例
基本user配置
- 首先我们模拟创建一个user的实例
@Data
public class User {private String id;private String name;private Integer age;}
- 创建一个公共的返回值的Result类
import lombok.Data;@Data
public class Result<T> {private static final long serialVersionUID = 1L;private Integer code;private String msg;private T data;public static Result fail() {Result Result = new Result();Result.setCode(1);Result.setMsg("服务器错误!!!");return Result;}public static Result fail(String msg) {Result Result = new Result();Result.setCode(1);Result.setMsg(msg);return Result;}public static <T> Result success(T data) {Result Result = new Result();Result.setCode(0);Result.setData(data);return Result;}public static Result success() {Result Result = new Result();Result.setCode(0);Result.setMsg("操作成功!");Result.setData("success");return Result;}}
场景1: POST提交 -前端传数组后台如何接受
[“2021”,“2022”]
var ids = ['2021','2022'];
$.ajax({type : 'POST',url: 'course/delete',contentType : "application/json" ,data: JSON.stringify(ids),success : function(data) {}
});
数组 String [ ] 接
@RequestMapping(value = "/delete", method = {RequestMethod.POST})
@ResponseBody
public void delete(@RequestBody String[] id) {for (String string : id) {System.out.println(string);}
}
List< String>接
@PostMapping("/saveUserIds")public Result saveStrings(@RequestBody List<String> list) {logger.info("传入的参数是{}",list);//模拟逻辑层做一个入参校验if (CollectionUtils.isEmpty(list)){return Result.fail();}return Result.success();}
场景2: get提交 :前端在URL里面传id1,id2后台如何接受?
- @RequestParam或@PathVariable
- 前台可以直接URL中通过id1,id2的方式入参,后台直接通过数组或List的的方式来接收,作为动态sql的入参,使用动态sql的foreach语法:
@ApiOperation("通过alarmId删除报警记录")@DeleteMapping("/delete/{alarmIds}")public Result delete(@ApiParam("报警记录id") @PathVariable Long[] alarmIds){return alarmRecordService.deleteAlarmRecordByIds(alarmIds);}
场景3: 前端传对象集合后台如何接受?
[{"id":"1","name":"辰兮","age":"22"},{"id":"2","name":"辰兮要努力","age":"23"}
]
/*** 前端传对象集合 后端用集合接* @param userList* @return*/@PostMapping("/saveList")public Result saveUserList(@RequestBody List<User> userList) {logger.info("传入的参数是{}",userList);//模拟逻辑层做一个入参校验if (CollectionUtils.isEmpty(userList)){return Result.fail();}return Result.success();
场景4 :综合情况
就是前端除了传一个集合外,还要传一个字符串或者数字等属性
- 入参案例如下
{"userList":[{"id ":"1","name":"辰兮","age":"22"},{"id":"2","name":"辰兮要努力","age":"23"}],"open":1
}
再创建一个对象接受
/*** @program: demo* @description: 用户对象接受类*/
@Data
public class UserVo {private List<User> userList;private Integer open;
}
/*** @program: demo* @description: 前后端传值交互案例*/
@RestController
@RequestMapping("/user")
public class UserController {//打印日志private static final Logger logger = LoggerFactory.getLogger(UserController.class);/*** 业务场景:前端传一个数组➕一个字符串或者数字等* @param userVo* @return*/@PostMapping("/saveUserVo")public Result saveUserVoList(@RequestBody UserVo userVo) {logger.info("传入的参数是{}",userVo);return Result.success();}
}
我们可以debug查看一下入参,很清晰的可以看到前端传入的参数