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);
    }
相关推荐
想ai抽10 小时前
web3区块链-小镇店铺的 “借力办事”:call 与 delegatecall 的区别与联系
web3·区块链·智能合约
光影少年11 小时前
web3学习路线
前端·学习·前端框架·web3
想ai抽11 小时前
web3区块链-加密小镇的 “十年庆典徽章”:ERC-721 全流程故事(含所有核心接口)
web3·区块链·nft
Web3VentureView11 小时前
Synbo 产品发布会在吉隆坡举行:重构 Web3 一级市场融资模式
网络·人工智能·重构·web3·区块链·synbo
leijiwen1 天前
Bsin X BDCM:从流量驱动到价值激励驱动的智能增长引擎
大数据·人工智能·web3
1***y1781 天前
Web3.0在去中心化社交的隐私保护
web3·去中心化·区块链
白鹭凡1 天前
WEB3——区块链架构
架构·web3·区块链
Web3_Daisy1 天前
以太坊代币教程:如何添加 Logo 并更新 Token 信息?
大数据·人工智能·web3·区块链·比特币
成长i1 天前
web3钱包Demo
web3
野老杂谈1 天前
【web3】通证(Token)核心解析
web3