SSM 整合 表现层数据封装
这是 在表现层对上传到页面数据类型做的封装,根据业务需求创建数据格式,对返回数据的状态用不同的状态码进行区分。因为数据有很多不同的状态,为了使前端人员区分数据的情况,如这个数据是作添加,
在对数据状态进行编码时,要与请求状态码相结合,使其更容易区分
操作结果编码
private Integer code;
操作数据结果
private Object data;
消息
private String message;
就像这样的
// 操作结果编码
public static final Integer SAVE_OK = 20011;
public static final Integer UPDATE_OK = 20021;
public static final Integer DELETE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERROR = 20010;
public static final Integer UPDATE_ERROR = 20020;
public static final Integer DELETE_ERROR = 20030;
public static final Integer GET_ERROR = 20040;
// 系统错误编码
// 操作权限编码
// 校验结果编码
* 代码
public class Result {
// 操作结果编码
private Integer code;
// 操作数据结果
private Object data;
// 消息
private String message;
public Result(Integer code) {
this.code = code;
}
public Result(Integer code, Object data) {
this.code = code;
this.data = data;
}
}
状态码常量可以根据自己的业务需求设定
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer SAVE_ERROR = 20010;
//其他编码
}
controller 调用
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public Result save(User user){
boolean flag = userService.save(user);
return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERROR);
}
@PutMapping
public Result update(User user){
boolean flag = userService.update(user);
return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERROR);
}
@DeleteMapping("/{uuid}")
public Result delete(@PathVariable Integer uuid){
boolean flag = userService.delete(uuid);
return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERROR);
}
@GetMapping("/{uuid}")
public Result get(@PathVariable Integer uuid){
User user = userService.get(uuid);
return new Result(null != user ?Code.GET_OK: Code.GET_ERROR,user);
}
@GetMapping("/{page}/{size}")
public Result getAll(@PathVariable Integer page, @PathVariable Integer size){
PageInfo<User> all = userService.getAll(page, size);
return new Result(null != all ?Code.GET_OK: Code.GET_ERROR,all);
}
@PostMapping("/login")
public Result login(String userName,String password){
User user = userService.login(userName,password);
return new Result(null != user ?Code.GET_OK: Code.GET_ERROR,user);
}
}