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);
    }
相关推荐
电报号dapp1191 天前
DeFi开发系统软件开发:技术架构与生态重构
重构·架构·web3·去中心化·区块链·智能合约
电报号dapp1191 天前
公链钱包开发:技术逻辑与产品设计实践
web3·去中心化·区块链·智能合约
清 晨1 天前
基于大数据分析的Facebook隐私保护策略
数据挖掘·数据分析·web3·facebook·tiktok·instagram·clonbrowser
dingzd952 天前
Facebook隐私设置详解:如何保护你的个人信息
web3·互联网·facebook·tiktok·instagram·指纹浏览器·clonbrowser
layneyao2 天前
AI与Web3.0:去中心化智能合约的未来
人工智能·web3·去中心化
TechubNews2 天前
从彼得·蒂尔四象限看 Crypto「情绪变迁」:从密码朋克转向「标准化追求者」
大数据·web3
Sui_Network2 天前
Sui 上线两周年,掀起增长「海啸」
人工智能·物联网·游戏·web3·区块链·智能合约
清 晨2 天前
Facebook如何运用AI实现元宇宙的无限可能?
人工智能·web3·互联网·facebook·tiktok·instagram·clonbrowser
这个懒人3 天前
第一节:Web3开发概述
web3·区块链
dingzd953 天前
Facebook隐私保护措施的优缺点解析
web3·互联网·facebook·tiktok·instagram·指纹浏览器·clonbrowser