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);
    }
相关推荐
Web3_Daisy3 天前
Pump.fun 与 FOMO 竞争背后的 Meme 市场变局
大数据·人工智能·金融·web3·区块链
磐链科技6 天前
区块链钱包开发新范式:如何用原生技术打造下一代Web3入口
web3·区块链
Web3李李7 天前
如何选择适合自己的Web3项目本位模式?金本位与币本位选型指南
web3·区块链·软件开发·金本位·币本位·dapp经济模型设计·defi质押理财
穗余9 天前
链上套利残酷共学-DAY01
web3
Web3_Daisy10 天前
Uniswap 入局 Robinhood Chain Launchpad
网络·金融·web3·区块链
龙虾PRO10 天前
AI智能化+Web3.0去中心化,落地重构全球贸易
人工智能·web3·去中心化
Web3李李13 天前
自建公链:Web3生态长期可持续发展的核心底层布局
web3·区块链·软件开发·定制开发·公链开发·主链开发·主网开发
Web3_Daisy14 天前
如何在Robinhood Chain创建 Uniswap V3 流动性池
大数据·人工智能·web3·区块链
潜龙952714 天前
Web3.0新测试方案
web3·区块链·新测试方案
明月_清风15 天前
🌐 多链生态对比:EVM vs Solana vs Sui,开发者怎么选?
后端·web3