在控制层类的接口中一般需要返回响应结果的数据包,如果采用接口返回类型设置为JSONObject,比如
public JSONObject getUserList...){
JSONObject json = new JSONObject();
}
通过使用json.put("","")的方式手工设置返回值会比较繁琐,这种情况可以实现一个通用的响应类来封装返回的业务数据,在封装过程中同时把返回的code、message配置在响应的数据包中。
在openjweb-common模块的org.openjweb.common.response下创建一个响应类ResponseResult:
import java.io.Serializable; import java.util.HashMap;/*** 通用的结果返回类* @param <T>*/ public class ResponseResult<T> implements Serializable {private Integer code;private String msg="操作成功";private T data;public ResponseResult() {this.code = 0;}public ResponseResult(Integer code, T data) {this.code = code;this.data = data;}public ResponseResult(Integer code, String msg, T data) {this.code = code;this.msg = msg;this.data = data;}public ResponseResult(Integer code, String msg) {this.code = code;this.msg = msg;this.data = (T)new HashMap();}public static ResponseResult errorResult(int code, String msg) {ResponseResult result = new ResponseResult();return result.error(code, msg);}public static ResponseResult okResult(int code, String msg) {ResponseResult result = new ResponseResult();return result.ok(code, new HashMap<>(), msg);}public static ResponseResult okResult(Object data) {ResponseResult result = new ResponseResult();return result.ok(data);}public ResponseResult<?> error(Integer code, String msg) {this.code = code;this.msg = msg;this.data = (T) new HashMap();return this;}public ResponseResult<?> ok(Integer code, T data) {this.code = code;this.data = data;return this;}public ResponseResult<?> ok(Integer code, T data, String msg) {this.code = code;this.data = data;this.msg = msg;return this;}public ResponseResult<?> ok(T data) {this.data = data;return this;}public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public T getData() {return data;}public void setData(T data) {this.data = data;}}
在openjweb-sys中引入openjweb-common依赖:
<dependency><groupId>org.openjweb</groupId><artifactId>openjweb-common</artifactId><version>0.0.1-SNAPSHOT</version> </dependency>
现在在前面章节的openjweb-sys模块的org.openjweb.sys.api包的DemoDBApi.java中增加一个使用ResponseResult封装的返回结结果的示例:
@GetMapping("queryUser2")public ResponseResult getStudent(){CommUser user = new CommUser();user.setLoginId("abao");user.setRealName("王先生");user.setUserSex("男");return ResponseResult.okResult(user); }
启动openjweb-sys模块的application后,在浏览器中输入测试URL:
http://localhost:8001/demo/queryUser2
页面返回:
{"code":0,"msg":"操作成功","data":{"loginId":"abao","username":null,"realName":"王先生","userSex":"男"}},如果返回错误,可以使用errorResult方法,在实际项目中可以进一步完善resultResult类。
项目代码见Github: https://github.com/openjweb/cloud/tree/master