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);
    }
相关推荐
木西19 小时前
拆解 100x 妖币 SIREN:基于 OpenZeppelin v5 与自主 AI 智能体的代币经济学架构实现
web3·智能合约·solidity
TechubNews21 小时前
稳定币下一战:不是谁发币,而是谁掌握结算通道
人工智能·web3·区块链
代码搬运媛3 天前
BFF在Web3中的应用实战
web3
Shota Kishi5 天前
解析 Solana 网络结构:通过领导者调度、验证者分布与质押集中度理解分布式区块生产
分布式·web3·去中心化·区块链
Joker时代6 天前
ANUBIS Labs 的“飞轮战略”如何破解 Web3 增长困局?
web3
OneBlock Community12 天前
波卡 3 月盘点:减半落地、ETF 上线、开发者体验全面升级
web3
TechubNews12 天前
AI 又一次成了「体面理由」:从 Coinbase 裁员 14% 看 Web3 的现实困局
人工智能·web3
木西12 天前
ERC-7579模块化账户标准:智能合约钱包的"乐高"插拔方案
web3·智能合约·solidity
重明链迹实验室12 天前
重明链迹丨每周区块链安全要闻(0427-0503)
安全·web3·区块链
Jiamiren12 天前
WEEX Labs亮相香港Web3嘉年华,深化全球科技生态交流
科技·web3