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);
    }
相关推荐
郝学胜-神的一滴15 小时前
Three.js光照技术详解:为3D场景注入灵魂
开发语言·前端·javascript·3d·web3·webgl
ZhengEnCi1 天前
FastAPI 项目结构完全指南-从零基础到企业级应用的 Python Web 开发利器
服务器·python·web3
闲谈共视2 天前
web3定义以及应用落地场景展望
web3
OpenBuild.xyz2 天前
Web3 开发者周刊 71 | Solar Mini Hacker House 即将席卷六城!
web3
OpenBuild.xyz2 天前
iExec 隐私工具:Web3 隐私开发 Workshop 回顾+$200 实战任务参与指南!
web3
leijiwen2 天前
什么是 Web3 品牌?
web3
dingzd952 天前
TikTok推荐算法快速解析
算法·机器学习·web3·facebook·推荐算法·tiktok·instagram
友莘居士3 天前
Java基于Web3j调用智能智能合约案例
java·web3·智能合约
leijiwen7 天前
AI × RWA 本地生活品牌数字资产管理与增长平台
人工智能·web3·区块链
dingzd958 天前
Facebook受众挖掘的高效方法
web3·互联网·facebook·tiktok·instagram·指纹浏览器·clonbrowser