如果API文档中请求的参数在请求体中,那么controller的对应方法中就要在参数中加上@RequestBody,表示把请求体的内容封装成对象。
如果API文档中的内容是与实体类中属性对应,那么直接用实体类作为参数。
如果是与多个实体类中的部分字段对应,那么用Map
比如登录场景,那么书写方式为:
@RequestMapping(value = "/login",method = RequestMethod.POST)
public Result login(@RequestBody Map<String,String> loginMap){
String mobile = loginMap.get("mobile");
String password = loginMap.get("password");
User user = userService.findByMobile(mobile);
//登录失败没有这样的手机号注册的用户,或者有此用户但是密码不匹配
if (user == null || !user.getPassword().equals(password)){
return new Result(ResultCode.MOBILEORPASSWORDERROR);
}else{
//登录成功
Map<String,Object> map = new HashMap<>();
map.put("companyId",user.getCompanyId());
map.put("companyName",user.getCompanyName());
String token = jwtUtils.createJwt(user.getId(),user.getUsername(),map);
return new Result(ResultCode.SUCCESS,token);
}
}
不要写成这种形式:
public Result login(String mobile,String password){
User user = userService.findByMobile(mobile);
//登录失败没有这样的手机号注册的用户,或者有此用户但是密码不匹配
if (user == null || !user.getPassword().equals(password)){
return new Result(ResultCode.MOBILEORPASSWORDERROR);
}else{
//登录成功
Map<String,Object> map = new HashMap<>();
map.put("companyId",user.getCompanyId());
map.put("companyName",user.getCompanyName());
String token = jwtUtils.createJwt(user.getId(),user.getUsername(),map);
return new Result(ResultCode.SUCCESS,token);
}
}
}