Web开发-问题-前后端交互数据不一致

0x01 问题描述

  • 所用的技术:Vue+Spring Boot
  • 后端传给前端数据:
cpp 复制代码
[Student(studentId=1, person=org.fatmansoft.teach.models.Person@4abe6020, major=软件工程, className=一班, grade=一年级), Student(studentId=2, person=org.fatmansoft.teach.models.Person@5207b9e6, major=软件工程, className=二班, grade=二年级)]
  • 前端接收数据:

前后端通讯数据明显不同,非常疑惑???(・∀・(・∀・(・∀・*)

0x02 解决

问题原因

javascript 复制代码
export interface StudentItem {
  studentId: number;
  personId: number;
  num: string;
  name: string;
  dept: string;
  major: string;
  className: string;
  card: string;
  gender: string;
  genderName: string;
  birthday: string;
  email: string;
  phone: string;
  address: string;
  grade: string;
  url: string;
  introduce: string;
}
  • 前端的学生数据定义,和后端传的不一致,后端传的person是封装过的,所以前端获取不到person内的数据
  • 要想获取到数据,就要在后端将person里封装的数据给拿到Student下

解决方案

定义一个模板类StudentDto继承Student,将Student中没有的数据(此处是url和name),从person里拿到StudentDto里,然后返回一个StudentDto的list。

java 复制代码
   public DataResponse getStudentListByMajor(@Valid @RequestBody DataRequest dataRequest){
        Optional<Student> student = studentRepository.findStudentByStudentId((Integer) dataRequest.get("studentId"));
        Student s = student.get();
        String major = s.getMajor();
        List<Student> list = studentRepository.findStudentListByMajor(major);
        List<StudentDto> collect = list.stream().map((item) -> {
            StudentDto dto = new StudentDto();
            BeanUtils.copyProperties(item, dto);
            dto.setName(item.getPerson().getName());
            dto.setUrl(item.getPerson().getUrl());
            return dto;
        }).collect(Collectors.toList());
        return CommonMethod.getReturnData(collect);
    }
相关推荐
木西1 天前
React Native DApp 开发全栈实战·从 0 到 1 系列(兑换-合约部分)
web3·智能合约·solidity
全干engineer2 天前
区块链web3项目实战-Truffle petshop
web3·区块链
Armonia生态2 天前
Armonia Mall超级数字生态WEB3商城的引领者
web3·armonia-mall
alex1003 天前
【一天一个Web3概念】Web3.0赛道分析:新一轮技术浪潮下的机遇与挑战
web3
Web3_Daisy4 天前
克隆代币 + 捆绑开盘:多链环境下的低成本发币玩法
人工智能·web3·区块链·比特币
清 晨4 天前
Web3:去中心化网络指南
web3·去中心化·区块链·facebook·tiktok·instagram·clonbrowser
清 晨4 天前
Web3.0应用成功的诀窍
web3·互联网·facebook·tiktok·instagram·指纹浏览器·clonbrowser
moz与京5 天前
【面试向】热门技术话题(上)
人工智能·物联网·机器学习·面试·web3·区块链·元宇宙
木西5 天前
React Native DApp 开发全栈实战·从 0 到 1 系列(永续合约交易-前端部分)
react native·web3·智能合约
OpenBuild.xyz6 天前
Web3 开发者周刊 66 | 重新审视L2:跨链桥与定序器背后的信任裂痕
web3·区块链·业界资讯·周报·数字货币