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);
    }
相关推荐
长安链开源社区2 小时前
长安链开发大赛决赛入围名单揭晓
web3·区块链·共识算法
程序员李程峰3 小时前
基础知识——各种钱包之间的联系与区别
web3·去中心化·区块链·智能合约·同态加密·零知识证明·信任链
程序员李程峰3 小时前
基础知识②区块链的链是什么
web3·去中心化·区块链·智能合约·同态加密·共识算法·信任链
深念Y3 小时前
当加密遇见分布式:Web3、去中心化与元宇宙的底层逻辑
分布式·web3·去中心化·区块链·元宇宙·加密·价值
Alex艾力的IT数字空间1 天前
大模型的“Think 模式”(思考模式)关闭的配置方式
人工智能·机器人·web3·github·开源软件·量子计算·开源协议
木西2 天前
从零搭建 Amiko 受控金库|Solidity 链下签名链上执行实战
web3·智能合约·solidity
Web3VentureView3 天前
SYNBO深度参与Ethereum on Tour 上海交大站:从高校 Builder 到链上一级市场基础设施
人工智能·web3·区块链·加密货币·synbo
ithadoop4 天前
Solana入门:区块链新手速成指南(第二阶段:开发入门)
rust·web3·区块链·智能合约·solana
潇楠Web3哨兵4 天前
桌面级Web3交易终端的底层炼狱:自研多源报价引擎、移除重型依赖、跨进程钱包桥接与强制安全拦截
算法·web3
Web3VentureView5 天前
SYNBO维港私享局:在香港Web3嘉年华最后一天,打开链上一级市场的共识现场
人工智能·web3·区块链·加密货币·synbo