API接口:添加一条记录
@PostMapping(path="/addUser") //用请求参数 @ResponseBody //必须加@RequestBody才能接收到postForObject发来的数据 public int addUser(@RequestBody User user) { try { userCrudReposity.save(user); return 0; } catch(Exception e){ return -1; } }
调用代码
RestTemplate restTemplate = new RestTemplate();
User user=new User("王","宏伟","email");
int ret = restTemplate.postForObject("http://localhost:8888/demo/addUser",user,int.class); //int.class是http://localhost:8888/demo/addUser返回的类型
return ret;
API接口:添加多条记录
@PostMapping(path="/addUsers") //用请求参数 @ResponseBody //必须加@RequestBody才能接收到postForObject发来的数据 public int addUsers(@RequestBody List<User> list) { try { userCrudReposity.saveAll(list); return 0; } catch(Exception e){ return -1; } }
调用代码:
List<User> list=new ArrayList<User>();
RestTemplate restTemplate = new RestTemplate();
User user1=new User("王","宏伟1","email");
User user2=new User("王","宏伟2","email");
list.add(user1);
list.add(user2);
int ret = restTemplate.postForObject("http://localhost:8888/demo/addUsers",list,int.class);