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);
    }
相关推荐
加速财经10 小时前
聚焦青年力量,MGBX打造全球Web3教育与创新平台
web3
Rockbean1 天前
10分钟-AI × Solana:2.MCP服务器——AI代理接入Solana的标准化通道
rust·web3·智能合约
Joker时代2 天前
重塑Web3安全防线:Vkey验证器正式登陆安卓与iOS平台,开启数字资产防护新纪元
安全·web3
木西4 天前
破局科研“死亡之谷”:基于 OpenZeppelin V5 与 Viem 深度复刻 VitaDAO 核心治理与资助系统
web3·智能合约·solidity
加速财经4 天前
MGBX全球社区建设提速,持续完善Web3生态版图
大数据·人工智能·web3
Rockbean4 天前
10分钟Solana-性能web3-5.4 项目搭建核心环节
rust·web3·智能合约
Rockbean4 天前
10分钟Solana-性能web3-5.3 项目搭建
rust·web3·智能合约
TechubNews5 天前
马云金融公司斥资4400万美元购买以太坊,布局Web3扩展
web3·区块链
Rockbean6 天前
10分钟Solana-性能web3-4.3 跨合约调用
rust·web3·智能合约
磐链科技6 天前
链游技术服务全景透视:从基建到工具链的实战指南
架构·web3·区块链