0
点赞
收藏
分享

微信扫一扫

SSM整合-表现层与前端数据传输数据协议定义与实现


目录

​​一、表现层数据封装​​

​​二、表现层数据封装实现​​

一、表现层数据封装

前端接收数据格式—创建结果模型类,封装数据到data属性中

SSM整合-表现层与前端数据传输数据协议定义与实现_mybatis

 前端接收数据格式—封装操作结果到code属性中

SSM整合-表现层与前端数据传输数据协议定义与实现_java_02

  前端接收数据格式—封装特殊消息到message(msg)属性中

SSM整合-表现层与前端数据传输数据协议定义与实现_java_03

二、表现层数据封装实现

基于上一篇博客继续进行优化

(2条消息) SSM整合流程(整合配置、功能模块开发、接口测试)_夏志121的博客

 设置统一数据返回结果类

public class Result {
//描述统一格式中的数据
private Object data;
//描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
private Integer code;
//描述统一格式中的消息,可选属性
private String msg;

public Result() {
}

public Result(Integer code,Object data) {
this.data = data;
this.code = code;
}

public Result(Integer code, Object data, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

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;
}
}

注意事项:

Result类中的字段并不是固定的,可以根据需要自行增减

提供若干个构造方法,方便操作

设置统一数据返回结果编码

//状态码
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;

public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
}

注意事项:

Code类的常量设计也不是固定的,可以根据需要自行增减,例如将查询再进行分为GET_OK,GET_ALL_OK,GET_PANE_OK。

根据情况设定合理的Result

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//统一每一个控制器方法返回值
@RestController
@RequestMapping("/books")
public class BookController {

@Autowired
private BookService bookService;

@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
Book book = bookService.getById(id);
Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
String msg = book != null ? "" : "数据查询失败,请重试!";
return new Result(code,book,msg);
}

@GetMapping
public Result getAll() {
List<Book> bookList = bookService.getAll();
Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
String msg = bookList != null ? "" : "数据查询失败,请重试!";
return new Result(code,bookList,msg);
}
}

举报

相关推荐

0 条评论