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);
    }
相关推荐
电报号dapp1197 小时前
治理代币的质押周期应该如何科学设定?
人工智能·web3·去中心化·区块链·智能合约
程序员秘密基地2 天前
基于html,css,vue,vscode,idea,,java,springboot,mysql数据库,在线旅游,景点管理系统
java·spring boot·mysql·spring·web3
dingzd952 天前
了解去中心化金融在现代经济中的作用——安全交易新时代
安全·金融·web3·去中心化·facebook·tiktok·instagram
mdpmw3 天前
从区块链基础到DApp开发
前端·web3
Cosimac3 天前
Web3.js 实战:基于 Hardhat 的以太坊投票 DApp 开发全流程
web3·以太坊
代码与野兽3 天前
Web3开发者生态终极选择指南:新手如何在激烈竞争中脱颖而出?
前端·后端·web3
电报号dapp1194 天前
链游新纪元——链游平台开发引领游戏新潮流!
游戏·web3·去中心化·区块链
电报号dapp1194 天前
区块链合约交易所开发攻略
web3·去中心化·区块链·智能合约
Sui_Network4 天前
tBTC 现已上线 Sui,带来 5 亿美元的比特币流动性
人工智能·物联网·web3·区块链·量子计算
木西4 天前
ERC721与ERC721A:NFT标准的对比与特性分析
web3·智能合约·solidity