在一个完整的项目中,如果每一个控制器的方法都返回不同的结果,那么对项目的维护和扩展都会很麻烦;并且现在主流的开发模式时前后端分离的模式,如果后端返回各式各样的结果,那么在前后端联调时会非常的麻烦,还会增加前后端的格外任务。
所以,在一个项目中统一返回结果就是一个十分必要和友好的做法。接下来就用一个简单的demo来看看统一返回结果的效果。
1.创建Spring Boot项目
这里比较简单,就不详细介绍了;将多余的文件删除,保持项目的整洁;引入必要的依赖。
demo的项目结构
1 | org.springframework.bootspring-boot-starterorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-jdbcorg.mybatis.spring.bootmybatis-spring-boot-starter1.3.2mysqlmysql-connector-javaorg.springframework.bootspring-boot-starter-testtest |
2.返回结果的封装
在common包下创建Result结果类,将需要返回的必要数据封装在Result结果类中;这里封装三个属性,第一个是返回的状态码,第二个是返回的描述信息,第三个是返回的数据,此数据是前端需要接收展示的数据。
Result.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | @Setter @Getter @ToString public class Result implements Serializable { private static final long serialVersionUID = 1L; private int resultCode; private String message; private T data; public Result(){ } public Result( int resultCode, String message){ this .resultCode = resultCode; this .message = message; } // 服务器处理失败 public Result failure(){ return new Result(Constants.RESULT_CODE_SERVER_ERROR, "服务器错误" ); } } |
创建Constants类,规定基本的状态码所代表的含义;这些状态码的基本规定需要符合常见的状态码含义,并且在一个项目能够保证统一即可。
Constants.java
1 2 3 4 5 6 7 8 9 10 | public class Constants { public static final int RESULT_CODE_SUCCESS = 200 ; // 成功处理请求 public static final int RESULT_CODE_BAD_REQUEST = 412 ; // 请求错误 public static final int RESULT_CODE_NOT_LOGIN = 402 ; // 未登录 public static final int RESULT_CODE_PARAM_ERROR = 406 ; // 传参错误 public static final int RESULT_CODE_SERVER_ERROR= 500 ; // 服务器错误 // 等等,可以根据场景继续添加 } |
最后创建结果类生成器ResultGenerator类,用于生成结果类。
ResultGenerator.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | public class ResultGenerator { private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS" ; private static final String DEFAULT_FAIL_MESSAGE = "FAIL" ; public static Result genSuccessResult(){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_SUCCESS); result.setMessage(DEFAULT_FAIL_MESSAGE); return result; } public static Result genSuccessResult(String message){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_SUCCESS); result.setMessage(message); return result; } public static Result genSuccessResult(Object data){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_SUCCESS); result.setMessage(DEFAULT_SUCCESS_MESSAGE); result.setData(data); return result; } public static Result genFailResult(String message){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_SERVER_ERROR); if (StringUtils.isEmpty(message)){ result.setMessage(DEFAULT_FAIL_MESSAGE); } else { result.setMessage(message); } return result; } public static Result genNullResult(String message){ Result result = new Result(); result.setResultCode(Constants.RESULT_CODE_BAD_REQUEST); result.setMessage(message); return result; } public static Result genErrorResult( int code, String message){ Result result = new Result(); result.setResultCode(code); result.setMessage(message); return result; } } |
3.后端接口实现
这里实现简单的增删改查,并且应用统一返回结果。
3.1 创建实体类
User.java
1 2 3 4 5 6 7 8 9 | @Setter @Getter @Generated @ToString public class User { private Integer id; private String name; private String password; } |
3.2 创建dao层
UserDao.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | public interface UserDao { /** * 查询所有的用户 * @return */ public List findAllUsers(); /** * 根据主键查询用户 * @param id * @return */ public User getUserById(Integer id); /** * 添加一个用户 * @param user * @return */ public int insertUser(User user); /** * 修改一个用户信息 * @param user * @return */ public int updateUser(User user); /** * 删除一个用户 * @param id * @return */ public int deleteUser(Integer id); } |
userDao.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | select id,name,password from tb_user order by id desc select id,name,password from tb_user where id = #{id} insert into tb_user(name,password) values(#{name},#{password}) update tb_user set name=#{name},password=#{password} where id=#{id} delete from tb_user where id=#{id} |
3.3 创建Controller层
这里基本没有任何业务逻辑可言,只是单纯的增删改查,所以也就不太需要业务层了。
UserController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | @Controller public class UserController { @Autowired UserDao userDao; /** * 查询所有用户 * @return */ @RequestMapping (value = "/users" , method = RequestMethod.GET) @ResponseBody public Result> queryAll(){ List users = userDao.findAllUsers(); return ResultGenerator.genSuccessResult(users); } /** * 查询一个用户 * @param id * @return */ @RequestMapping (value = "/users/{id}" , method = RequestMethod.GET) @ResponseBody public Result queryOne( @PathVariable ( "id" ) Integer id){ if (id == null || id insert( @RequestBody User user){ if (StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())){ return ResultGenerator.genFailResult( "缺少参数" ); } return ResultGenerator.genSuccessResult(userDao.insertUser(user) > 0 ); } /** * 修改用户信息 * @param user * @return */ @RequestMapping (value = "/users" , method = RequestMethod.PUT) @ResponseBody public Result update( @RequestBody User user){ if (user.getId() == null || user.getId() 0 ); } /** * 删除一个用户 * @param id * @return */ @RequestMapping (value = "/users/{id}" , method = RequestMethod.DELETE) @ResponseBody public Result delete( @PathVariable ( "id" ) Integer id){ if (id == null || id 0 ); } } |
4.前端部分
这里前端使用ajax来与后端进行交互,所以前端资源只需要引入jquery即可。
1 |
user-test.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | < title >统一返回结果 | 请求测试</ title >< div style = "width:720px;margin:7% auto" > < div class = "content" > < div class = "container-fluid" > < div class = "row" > < div class = "col-lg-6" > < hr > < div class = "card" > < div class = "card-header" > < h5 class = "m-0" >详情查询接口测试</ h5 > </ div > < div class = "card-body" > < h6 class = "card-title" >查询接口返回数据如下:</ h6 > < p class = "card-text" id = "result0" ></ p > < a href = "#" class = "btn btn-primary" >发送详情查询请求</ a > </ div > </ div > < br >< hr > < div class = "card" > < div class = "card-header" > < h5 class = "m-0" >列表查询接口测试</ h5 > </ div > < div class = "card-body" > < h6 class = "card-title" >查询接口返回数据如下:</ h6 > < p class = "card-text" id = "result1" ></ p > < a href = "#" class = "btn btn-primary" >发送列表查询请求</ a > </ div > </ div > < br >< hr > < div class = "card" > < div class = "card-header" > < h5 class = "m-0" >添加接口测试</ h5 > </ div > < div class = "card-body" > < h6 class = "card-title" >添加接口返回数据如下:</ h6 > < p class = "card-text" id = "result2" ></ p > < a href = "#" class = "btn btn-primary" >发送添加请求</ a > </ div > </ div > < br >< hr > < div class = "card" > < div class = "card-header" > < h5 class = "m-0" >修改接口测试</ h5 > </ div > < div class = "card-body" > < h6 class = "card-title" >修改接口返回数据如下:</ h6 > < p class = "card-text" id = "result3" ></ p > < a href = "#" class = "btn btn-primary" >发送修改请求</ a > </ div > </ div > < br >< hr > < div class = "card" > < div class = "card-header" > < h5 class = "m-0" >删除接口测试</ h5 > </ div > < div class = "card-body" > < h6 class = "card-title" >删除接口返回数据如下:</ h6 > < p class = "card-text" id = "result4" ></ p > < a href = "#" class = "btn btn-primary" >发送删除请求</ a > </ div > </ div > < hr > </ div > </ div > </ div > </ div > </ div > function requestQuery() { var id = $("#queryId").val(); if (typeof id == "undefined" || id == null || id == "" || id < 0) { return false; } $.ajax({ type: "GET",//方法类型 dataType: "json",//预期服务器返回的数据类型 url: "/users/" + id, contentType: "application/json; charset=utf-8", success: function (result) { $("#result0").html(JSON.stringify(result)); }, error: function () { $("#result0").html("接口异常,请联系管理员!"); } }); } function requestQueryList() { $.ajax({ type: "GET",//方法类型 dataType: "json",//预期服务器返回的数据类型 url: "/users", contentType: "application/json; charset=utf-8", success: function (result) { $("#result1").html(JSON.stringify(result)); }, error: function () { $("#result1").html("接口异常,请联系管理员!"); } }); } function requestAdd() { var name = $("#addName").val(); var password = $("#addPassword").val(); var data = {"name": name, "password": password} $.ajax({ type: "POST",//方法类型 dataType: "json",//预期服务器返回的数据类型 url: "/users", contentType: "application/json; charset=utf-8", data: JSON.stringify(data), success: function (result) { $("#result2").html(JSON.stringify(result)); }, error: function () { $("#result2").html("接口异常,请联系管理员!"); } }); } function requestUpdate() { var id = $("#updateId").val(); var name = $("#updateName").val(); var password = $("#updatePassword").val(); var data = {"id": id, "name": name, "password": password} $.ajax({ type: "PUT",//方法类型 dataType: "json",//预期服务器返回的数据类型 url: "/users", contentType: "application/json; charset=utf-8", data: JSON.stringify(data), success: function (result) { $("#result3").html(JSON.stringify(result)); }, error: function () { $("#result3").html("接口异常,请联系管理员!"); } }); } function requestDelete() { var id = $("#deleteId").val(); if (typeof id == "undefined" || id == null || id == "" || id < 0) { return false; } $.ajax({ type: "DELETE",//方法类型 dataType: "json",//预期服务器返回的数据类型 url: "/users/" + id, contentType: "application/json; charset=utf-8", success: function (result) { $("#result4").html(JSON.stringify(result)); }, error: function () { $("#result4").html("接口异常,请联系管理员!"); } }); } |
5.验证
验证添加效果
验证查询
验证查询多个用户
修改用户
删除用户
测试也基本成功了,这样统一的返回结果在前端接收处理数据时,会十分具有优势,所以在完整的项目中也都是采用这种方案,到这里这个demo也就基本结束了。
以上就是详解如何在SpringBoot项目中使用统一返回结果的详细内容,更多关于SpringBoot使用统一返回结果的资料请关注IT俱乐部其它相关文章!