SpringBoot RestFul风格API接口开发
本文介绍在使用springBoot如何进行Restful Api接口的开发及相关注解已经参数传递如何处理。
一、概念:
REST全称是Representational State Transfer,中文意思是表述(编者注:通常译为表征)性状态转移。 它首次出现在2000年Roy Fielding的博士论文中,Roy Fielding是HTTP规范的主要编写者之一。 他在论文中提到:"我这篇文章的写作目的,就是想在符合架构原理的前提下,理解和评估以网络为基础的应用软件的架构设计,得到一个功能强、性能好、适宜通信的架构。REST指的是一组架构约束条件和原则。" 如果一个架构符合REST的约束条件和原则,我们就称它为RESTful架构。
REST本身并没有创造新的技术、组件或服务,而隐藏在RESTful背后的理念就是使用Web的现有特征和能力, 更好地使用现有Web标准中的一些准则和约束。虽然REST本身受Web技术的影响很深, 但是理论上REST架构风格并不是绑定在HTTP上,只不过目前HTTP是唯一与REST相关的实例。 所以我们这里描述的REST也是通过HTTP实现的REST。
二、注解说明:
1.Rest控制器
@RestController注释用于定义RESTful Web服务。它提供JSON,XML和自定义响应。其语法如下所示
@RestController public class UserRestController{ }
有了该注解,在响应返回的是json格式的数据,我们就不要写@ResponseBody注解了
2.Java请求映射
@RequestMapping注释用于定义访问REST端点的Request URI。可以定义Request方法来使用和生成对象。默认请求方法是:GET。
@RequestMapping(value = "/user/userCode/{userCode}", method = RequestMethod.GET)
public ApiUser getUserByUserCode(@PathVariable("userCode") String userCode) {
AfaUser user = userService.getAfaUserByUserCode(userCode);
ApiUser apiUser=BeanUtils.copyBean(user,ApiUser.class);
if(user!=null){
List<OrgBean> orgs=this.getOrgParentListByOrgId(user.getMainOrgid());
apiUser.setOrgs(orgs);
}
return apiUser;
}
有人就问了,那要是我有多个参数,GET我怎么操作了:
方法一:换成POST请求,将所有参数封装成一个类,然后使用 @RequestBody注解将参数自动解析成该类的一个实例
@ApiOperation(value = "根据用户对象获取用户列表")
@RequestMapping(value = "/users", method = RequestMethod.POST)
public List<ApiUser> getUserListByApiUser(@RequestBody ApiUser apiUser) {
AfaUser afaUser = BeanUtils.copyBean(apiUser, AfaUser.class);
List<ApiUser> apiUserList=BeanUtils.copyList(userService.getAfaUserList(afaUser), ApiUser.class);
for(ApiUser _user:apiUserList){
if(StringUtils.isNotNullAndBlank(_user.getMainOrgid())){
List<OrgBean> orgs=this.getOrgParentListByOrgId(_user.getMainOrgid());
_user.setOrgs(orgs);
}
}
return apiUserList;
}
有人说那你这样就不符合规范了,不过,这个“规范”只是建议大家这么来遵守,并不是强制要求
方法二:还是使用GET请求,但是将所有请求参数通过JSON格式来传递,controller拿到参数后,使用 JSON 相关的库(如 gson),将该JSON转化为相应的对象
public List<String> getName(@RequestParam String queryDtoStr) { QueryDto queryDto = new Gson().fromJson(queryDtoStr, QueryDto .class); // .... return new ArrayList<>(); }
这样请求的就要像这样:
http://localhost:8080/app/names?queryDtoStr={"query1":12,"query2":2,"query3":2}
3.2 POST主要用于创建资源
HTTP POST请求用于创建资源。 此方法包含请求正文。可以发送请求参数和路径变量来定义自定义或动态URL。例如:
@RequestMapping(value="/user", method = RequestMethod.POST) public void doInsert(@RequestBody ApiUser apiUser) { AfaUser user = BeanUtils.copyBean(apiUser, AfaUser.class); userService.addAfaUser(user); }
3.3 PUT主要用于更新资源
HTTP PUT请求用于更新现有资源,此方法包含请求正文。可以发送请求参数和路径变量来自定义或动态URL。例如:
@RequestMapping(value = "/user", method = RequestMethod.PUT) public void doUpdate(@RequestBody ApiUser apiUser) { AfaUser user = BeanUtils.copyBean(apiUser, AfaUser.class); userService.updateAfaUser(user); }
3.4 DELETE主要用于删除资源
HTTP DELETE请求用于删除现有资源,此方法包含请求正文。可以发送请求参数和路径变量来自定义或动态URL。例如:
@ApiOperation(value = "删除用户") @RequestMapping(value = "/user", method = RequestMethod.DELETE) public void doDelelte(@RequestBody ApiUser apiUser) { AfaUser user = BeanUtils.copyBean(apiUser, AfaUser.class); userService.delAfaUser(user); }
以上方法参数是接收一个对象,如果是单个属性,可以直接跟在url后面。
完整示例:
/** * * @author Shaw * */ @RestController @RequestMapping(value = "/rest", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @Api(value = "/rest", tags = "UserRestController", description = "用户管理接口") public class UserRestController{ @Resource private AfaUserService userService; @Resource private AfaRoleService afaRoleService; @Resource private AfaOrgService orgService; @Resource private MenuHelper menuHelper; @Resource private AfaOrgService afaOrgService; @Resource private AfaAuthPartyService afaAuthPartyService; @ApiOperation(value = "新增用户") @RequestMapping(value="/user", method = RequestMethod.POST) public void doInsert(@RequestBody ApiUser apiUser) { AfaUser user = BeanUtils.copyBean(apiUser, AfaUser.class); userService.addAfaUser(user); } @ApiOperation(value = "更新用户") @RequestMapping(value = "/user", method = RequestMethod.PUT) public void doUpdate(@RequestBody ApiUser apiUser) { AfaUser user = BeanUtils.copyBean(apiUser, AfaUser.class); userService.updateAfaUser(user); } @ApiOperation(value = "删除用户") @RequestMapping(value = "/user", method = RequestMethod.DELETE) public void doDelelte(@RequestBody ApiUser apiUser) { AfaUser user = BeanUtils.copyBean(apiUser, AfaUser.class); userService.delAfaUser(user); } @ApiOperation(value = "修改密码") @RequestMapping(value = "/user/password", method = RequestMethod.PUT) public void resetUserPassWord(@RequestBody ApiUser apiUser) { AfaUser afaUser = BeanUtils.copyBean(apiUser, AfaUser.class); userService.resetUserPassWord(afaUser); } @ApiOperation(value = "根据用户编码获取用户") @RequestMapping(value = "/user/userCode/{userCode}", method = RequestMethod.GET) public ApiUser getUserByUserCode(@PathVariable("userCode") String userCode) { AfaUser user = userService.getAfaUserByUserCode(userCode); ApiUser apiUser=BeanUtils.copyBean(user,ApiUser.class); if(user!=null){ List<OrgBean> orgs=this.getOrgParentListByOrgId(user.getMainOrgid()); apiUser.setOrgs(orgs); } return apiUser; } @ApiOperation(value = "根据用户id获取用户") @RequestMapping(value = "/user/userId/{userId}", method = RequestMethod.GET) public ApiUser getUserByUserId(@PathVariable("userId") String userId) { if(StringUtils.isNotNullAndBlank(userId)){ AfaUser user = userService.getAfaUserByUserId(userId); ApiUser apiUser=BeanUtils.copyBean(user,ApiUser.class); if(user!=null){ List<OrgBean> orgs=this.getOrgParentListByOrgId(user.getMainOrgid()); apiUser.setOrgs(orgs); } return apiUser; } return null; } @ApiOperation(value = "根据角色编码获取用户") @RequestMapping(value = "/user/roleCode/{roleCode}", method = RequestMethod.GET) public List<ApiUser> getUserByRoleCode(@PathVariable("roleCode") String roleCode) { List<AfaUser> user = userService.getUserByRoleCode(roleCode); return BeanUtils.copyList(user, ApiUser.class); } @ApiOperation(value = "获取所有用户") @RequestMapping(value = "/users", method = RequestMethod.GET) public List<ApiUser> getAllUserList() { return BeanUtils.copyList(userService.getAfaUserList(),ApiUser.class); } @ApiOperation(value = "根据用户对象获取用户列表") @RequestMapping(value = "/users", method = RequestMethod.POST) public List<ApiUser> getUserListByApiUser(@RequestBody ApiUser apiUser) { AfaUser afaUser = BeanUtils.copyBean(apiUser, AfaUser.class); List<ApiUser> apiUserList=BeanUtils.copyList(userService.getAfaUserList(afaUser), ApiUser.class); for(ApiUser _user:apiUserList){ if(StringUtils.isNotNullAndBlank(_user.getMainOrgid())){ List<OrgBean> orgs=this.getOrgParentListByOrgId(_user.getMainOrgid()); _user.setOrgs(orgs); } } return apiUserList; } @ApiOperation(value = "根据角色编码获取角色") @RequestMapping(value = "/users/roleCodes", method = RequestMethod.POST) public List<ApiUser> getUserByRoleCodes(@RequestBody List<String> roleList) { return BeanUtils.copyList(userService.getUserByRoleCodes(roleList),ApiUser.class); } @ApiOperation(value = "根据角色编码获取角色") @RequestMapping(value = "/users/page", method = RequestMethod.POST) public Page<ApiUserOrgPos> queryAfaUserPage(@RequestBody Searcher searcher,Page<ApiUserOrgPos> page) { Page<AfaUserOrgPos> apiUserOrgPos = BeanUtils.copyList(page, AfaUserOrgPos.class); return BeanUtils.copyList(userService.queryAfaUserPage(searcher, apiUserOrgPos,null), ApiUserOrgPos.class); } @ApiOperation(value = "根据用户对象获取角色列表") @RequestMapping(value = "/role/user/", method = RequestMethod.POST) public List<ApiRole> getRolesByUser(@RequestBody ApiUser apiUser) { AfaUser afaUser = BeanUtils.copyBean(apiUser, AfaUser.class); String userCode=afaUser.getUserCode(); return BeanUtils.copyList(menuHelper.findRoleByUserCode(userCode, null), ApiRole.class); } @ApiOperation(value = "根据用户Id对象获取角色列表") @RequestMapping(value = "/role/userId/{userId}", method = RequestMethod.GET) public List<ApiRole> getRolesByUserId(@PathVariable("userId") String userId) { AfaUser afaUser=userService.getAfaUserByUserId(userId); String userCode=afaUser.getUserCode(); return BeanUtils.copyList(menuHelper.findRoleByUserCode(userCode, null), ApiRole.class); } @ApiOperation(value = "根据角色编码、机构id获取用户列表") @RequestMapping(value = "/users/{roleCode}/{orgId}", method = RequestMethod.GET) public List<ApiUser> getUsersByRoleCodeAndOrgId(@PathVariable("roleCode") String roleCode, @PathVariable("orgId") String orgId) { List<AfaUser> afaUserList=new ArrayList<AfaUser>(); //1、先获取机构编码 AfaOrg afaOrg=null; if(StringUtils.isNotNullAndBlank(orgId)){ afaOrg=afaOrgService.getAfaOrgByOrgId(orgId); } String orgCode=null; if(afaOrg!=null){ orgCode=afaOrg.getOrgCode(); } //2、根据机构编码和角色获取角色授权表 List<AfaAuthParty> partyList=null; if(StringUtils.isNullOrBlank(roleCode)&&StringUtils.isNullOrBlank(orgId)){ }else{ partyList=afaAuthPartyService.getAfaAuthPartyByRoleCodeAndOrgCode(orgCode,roleCode); } //3、根据party_type类型获取用户。 //当party_type为org的时候,获取该org下的所有用户 //当party_type为user的时候,判断该用户的主机构是不是orgId下的 if(partyList!=null&&partyList.size()!=0){ for(AfaAuthParty _party:partyList){ AfaUser afaUser=new AfaUser(); if(StringUtils.isNotNullAndBlank(orgId)){ afaUser.setMainOrgid(orgId); } if("org".equals(_party.getPartyType())){ afaUserList.addAll(userService.getAfaUserList(afaUser)); } if("user".equals(_party.getPartyType())){ afaUser.setUserCode(_party.getPartyCode()); } afaUserList.addAll(userService.getAfaUserList(afaUser)); } } if(afaUserList.size()!=0){ for (int i = 0; i < afaUserList.size()-1; i++) { for (int j = afaUserList.size()-1; j > i; j--) { if (afaUserList.get(j).getUserCode().equals(afaUserList.get(i).getUserCode())) { afaUserList.remove(j); } } } } return BeanUtils.copyList(afaUserList, ApiUser.class); } @ApiOperation(value = "更新某些机构下用户的状态") @RequestMapping(value = "/users/status", method = RequestMethod.POST) public void changeUserStatusByOrgIdList(@RequestBody UserRequestParam requestParamObject) { if(CollectionUtils.isNotEmpty(requestParamObject.getOrgIdList())){ userService.changeUserStatusByOrgIdList(requestParamObject.getOrgIdList(),requestParamObject.getStatus()); } } @ApiOperation(value = "根据casn获取用户列表") @RequestMapping(value = "/users/casn/{caSn}", method = RequestMethod.GET) public List<ApiUser> getApiUserByCaSn(@PathVariable("caSn")String caSn) { List<AfaUser> afaUser=userService.getApiUserByCaSn(caSn); return BeanUtils.copyList(afaUser, ApiUser.class); } }