ResponseBodyAdvice 返回处理
基础学习:
– 个人整理文档
– 参考文档:
----- SpringBoot全局处理统一返回类型
----- springboot的接口返回值统一标准格式
源代码:
– codechina.csdn
– CSDN
目录结构说明
请转至目录结构说明
Entity层
在entity目录下创建configResultCode.java 和 configResult.java文件
- configResultCode.java
package com.west.server.entity;
public enum configResultCode {
/* 成功状态码 */
SUCCESS(0, "成功"),
/* 系统500错误*/
SYSTEM_ERROR(10000, "系统异常,请稍后重试"),
UNAUTHORIZED(10401, "签名验证失败"),
/* 参数错误:10001-19999 */
PARAM_IS_INVALID(10001, "参数无效"),
/* 用户错误:20001-29999*/
USER_HAS_EXISTED(20001, "用户名已存在"),
USER_NOT_FIND(20002, "用户名不存在");
private Integer code;
private String message;
configResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer code() {
return this.code;
}
public String message() {
return this.message;
}
}
- configResult.java
package com.west.server.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class configResult<T> implements Serializable {
/**
* statu状态值:代表本次请求response的状态结果。
*/
private Integer code;
/**
* response描述:对本次状态码的描述。
*/
private String msg;
/**
* data数据:本次返回的数据。
*/
private T data;
/**
* count数据:本次返回的数据数量
*/
private Integer count;
/**
* 成功,创建ResResult:没data数据
*/
public static configResult createSuccess() {
configResult result = new configResult();
result.setResultCode(configResultCode.SUCCESS);
return result;
}
/**
* 成功,创建ResResult:有data数据
*/
public static configResult createSuccess(Object data) {
configResult result = new configResult();
result.setResultCode(configResultCode.SUCCESS);
result.setData(data);
return result;
}
/**
* 成功,创建ResResult:有data数据,有页面数量展示
*/
public static configResult createSuccess(Object data,Integer count) {
configResult result = new configResult();
result.setResultCode(configResultCode.SUCCESS);
result.setData(data);
result.setCount(count);
return result;
}
/**
* 失败,指定code,msg
*/
public static configResult createFail(Integer code, String msg) {
configResult result = new configResult();
result.setCode(code);
result.setMsg(msg);
return result;
}
/**
* 失败,指定configResultCode枚举
*/
public static configResult createFail(configResultCode resultCode) {
configResult result = new configResult();
result.setResultCode(resultCode);
return result;
}
/**
* 把configResultCode枚举转换为ResResult
*/
private void setResultCode(configResultCode code) {
this.code = code.code();
this.msg = code.message();
}
}
Utils层
在utils目录下创建responseHandler.java文件
package com.west.server.utils;
import com.west.server.entity.configResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import cn.hutool.json.JSONUtil;
@ControllerAdvice(basePackages = "com.west.server.controller")
public class responseHandler implements ResponseBodyAdvice<Object> {
/**
*
* 处理response的具体业务方法
*/
@Override
public Object beforeBodyWrite(Object arg0, MethodParameter arg1, MediaType arg2,
Class<? extends HttpMessageConverter<?>> arg3, ServerHttpRequest arg4, ServerHttpResponse arg5) {
// TODO Auto-generated method stub
// 获取返回数据类型
String returnType = arg1.getParameterType().getSimpleName();
// 根据返回数据类型作相应处理
switch (returnType) {
case "void":
return configResult.createSuccess();
case "Result":
return (configResult) arg0;
case "String":
//需要做转换,否则报错
return JSONUtil.toJsonStr(configResult.createSuccess(arg0));
case "JSONObject":
return configResult.createSuccess(JSONUtil.parseObj(arg0).getObj("body"),
JSONUtil.parseObj(arg0).size(),
JSONUtil.parseObj(arg0).isNull("col") ? null : JSONUtil.parseObj(arg0).isNull("col"));
default:
return JSONUtil.toJsonStr(configResult.createSuccess(arg0));
}
}
/**
* 是否支持advice功能 treu=支持,false=不支持
*/
@Override
public boolean supports(MethodParameter arg0, Class<? extends HttpMessageConverter<?>> arg1) {
// TODO Auto-generated method stub
// 默认开启,后续遇到需求再进行判断
return true;
}
}
Controller层
修改controller目录下的dbManagerController.java文件
package com.west.server.controller;
import java.sql.SQLException;
import java.util.List;
import com.west.server.service.dbManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.meta.MetaUtil;
import cn.hutool.db.meta.Table;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
@RequestMapping("/dbManager")
@RestController
public class dbManagerController {
@Autowired
dbManagerService dManagerService;
/**
* 获取当前库的所有表名
* API测试URL:http://localhost:8080/dbManager/getAllTablesName?groupname=mssql
*
* @return jsonObject { "code": 0, "msg": "", "count": 1000, "data": [{}, {}] }
*/
@GetMapping("/getAllTablesName")
public JSONObject getAllTablesName(@RequestParam("groupname") String groupname){
return JSONUtil.createObj().putOnce("list", dManagerService.getAllTablesName(groupname));
}
/**
* 获取表结构
* API测试URL:http://localhost:8080/dbManager/getTableStructure/?tablename=sarticle&groupname=mssql
*
* @param tablename 对应数据库的表名
* @return
*/
@GetMapping("/getTableStructure")
public JSONObject getTableStructure(@RequestParam("tablename") String tablename,
@RequestParam("groupname") String groupname) {
return JSONUtil.createObj().putOnce("list",dManagerService.getTableStructure(groupname, tablename));
}
/**
* 插入数据 API测试URL:http://localhost:8080/dbManager/addData
*
* @param request 传入数据:JSON 格式: { "#groupname":"数据库对应组名",
* "groupname":"{{groupname}}", "#table":"对应数据库的表名", "tablename"
* : "{{tablename}}",
* "#data":"需要插入的数据,例如:{id:1,title:你好},data能为空", "data":{{data}}
* }
* @return
*/
@PostMapping("/addData")
public String addData(@RequestBody JSONObject request) {
Entity data = Entity.create(request.getStr("tablename")).parseBean(request.get("data"));
return dManagerService.addData(request.getStr("groupname"), data)?"success":"false";
}
/**
* 插入数据并返回自增主键 API测试URL:http://localhost:8080/dbManager/addDataForGeneratedKey
*
* @param request 传入数据:JSON 格式: { "#groupname":"数据库对应组名",
* "groupname":"{{groupname}}", "#table":"对应数据库的表名", "tablename"
* : "{{tablename}}",
* "#data":"需要插入的数据,例如:{id:1,title:你好},data能为空", "data":{{data}}
* }
* @return
*/
@PostMapping("/addDataForGeneratedKey")
public Long addDataForGeneratedKey(@RequestBody JSONObject request) {
Entity data = Entity.create(request.getStr("tablename")).parseBean(request.get("data"));
return dManagerService.addDataForGeneratedKey(request.getStr("groupname"), data);
}
/**
* 删除数据 API测试URL:http://localhost:8080/dbManager/delData
*
* @param request 传入数据:JSON 格式: { "#groupname":"数据库对应组名",
* "groupname":"{{groupname}}", "#table":"需要修改的数据库表名",
* "tablename" : "{{tablename}}",
* "#where":"限制条件,例如:{id:1},where不能为空", "where":{{where}} }
* @return
*/
@PostMapping("/delData")
public String delData(@RequestBody JSONObject request) {
Entity where = Entity.create(request.getStr("tablename")).parseBean(request.get("where"));
return dManagerService.delData(request.getStr("groupname"), where)?"success":"false";
}
/**
* 更新数据 API测试URL:http://localhost:8080/dbManager/updateData
*
* @param request 传入数据:JSON 格式: { "#groupname":"数据库对应组名",
* "groupname":"{{groupname}}", "#table":"对应数据库的表名", "tablename"
* : "{{tablename}}",
* "#data":"需要插入的数据,例如:{id:1,title:你好},data不能为空",
* "data":{{data}}, "#where":"限制条件,例如:{id:1},where不能为空",
* "where":{{where}} }
* @return
*/
@PostMapping("/updateData")
public String updateData(@RequestBody JSONObject request) {
Entity data = Entity.create(request.getStr("tablename")).parseBean(request.get("data"));
Entity where = Entity.create(request.getStr("tablename")).parseBean(request.get("where"));
return dManagerService.updateData(request.getStr("groupname"), data, where)?"success":"false";
}
/**
* 查询表全部数据
* API测试URL:http://localhost:8080/dbManager/findTableAllList?tablename=sarticle&groupname=mssql
*
* @param tablename 对应数据库的表名
* @return
*/
@GetMapping("/findTableAllList")
public JSONObject findAllList(@RequestParam("tablename") String tablename,
@RequestParam("groupname") String groupname) {
List<Entity> lis = dManagerService.findAllList(groupname, tablename);
JSONArray cols = JSONUtil.createArray();
for (String str : IterUtil.getFirst(lis.iterator()).getFieldNames()) {
cols.put(JSONUtil.createObj().putOnce("field", str).putOnce("title", str));
}
JSONObject jsonObject = JSONUtil.createObj().putOnce("cols", cols).putOnce("list", lis);
return jsonObject;
}
/**
* 按条件进行查询,含模糊查询 API测试URL:http://localhost:8080/dbManager/findTableAllList
*
* @param request 传入数据:JSON 格式: { "#groupname":"数据库对应组名",
* "groupname":"{{groupname}}", "#table":"需要修改的数据库表名",
* "tablename" : "{{tablename}}",
* "#where":"限制条件,例如:{id:1},where不能为空", "where":{{where}} }
* @return
*/
@PostMapping("/findTableAllList")
public JSONObject findAllList(@RequestBody JSONObject request) {
Entity where = Entity.create(request.getStr("tablename")).parseBean(request.get("where"));
return JSONUtil.createObj().putOnce("list", dManagerService.findAllList(request.getStr("groupname"), where));
}
/**
* 模糊查询
* API测试URL:http://localhost:8080/dbManager/findTableLikeList?tablename=sarticle&field=id&value=1&groupname=mssql
*
* @param tablename 对应数据库的表名
* @param field 字段名
* @param value 对应值
* @return
*/
@GetMapping("/findTableLikeList")
public JSONObject findLikeList(@RequestParam("tablename") String tablename, @RequestParam("field") String field,
@RequestParam("value") String value, @RequestParam("groupname") String groupname) {
return JSONUtil.createObj().putOnce("data", dManagerService.findLikeList(groupname, tablename, field, value));
}
/**
* 分页查询 API测试URL:http://localhost:8080/dbManager/getPage
*
* @param request 传入数据:JSON 格式: { "#groupname":"数据库对应组名",
* "groupname":"{{groupname}}", "#table":"需要修改的数据库表名",
* "tablename" : "{{tablename}}",
* "#where":"限制条件,例如:{id:1},where不能为空", "where":{{where}},
* "#pages":"页码", "pages":{{pages}}, "#pageSize":"每页数量",
* "pageSize":{{pagesize}} }
* @return
*/
@PostMapping("/getPage")
public JSONObject getPage(@RequestBody JSONObject request) {
Entity where = Entity.create(request.getStr("tablename")).parseBean(request.get("where"));
List<Entity> lis = dManagerService.getPage(request.getStr("groupname"), where, request.getInt("pages"),
request.getInt("pageSize"));
IterUtil.getFirst(lis.iterator()).getFieldNames();
JSONObject jsonObject = JSONUtil.createObj().putOnce("code", 0).putOnce("cols", "value")
.putOnce("count", lis.size()).putOnce("data", lis);
return jsonObject;
}
/**
* 自定义查询语句 API测试URL:http://localhost:8080/dbManager/customerRSqL
*
* @param request 传入数据:JSON 格式: { "#groupname":"数据库对应组名",
* "groupname":"{{groupname}}", "#sql": "自定义sql语句", "sql":
* "{{selectSQL}}" }
* @return
*/
@PostMapping("/customerRSqL")
public JSONObject customerRSqL(@RequestBody JSONObject request) {
return JSONUtil.createObj().putOnce("list", dManagerService.customerRSqL(request.getStr("groupname"), request.getStr("sql")));
}
/**
* 自定义查询语句 API测试URL:http://localhost:8080/dbManager/customerCUDSql
*
* @param request 传入数据:JSON 格式: { "#groupname":"数据库对应组名",
* "groupname":"{{groupname}}", "#sql": "自定义sql语句", "sql":
* "{{selectSQL}}" }
* @return
*/
@PostMapping("/customerCUDSql")
public String customerCUDSql(@RequestBody JSONObject request) {
return dManagerService.customerCUDSql(request.getStr("groupname"), request.getStr("sql"))?"success":"false";
}
}
测试数据
- 按dbManagerController 测试URL进行测试
- 自行下载源代码,获取postmanData配置文件导入到postman进行测试
PS:因为两个数据库的字段不一样,所以将变量数据分成两个分支,可自行获取相应的分支进行测试