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);
    }
相关推荐
OpenBuild.xyz1 天前
我是如何从 0 到 1 找到 Web3 工作的?
人工智能·web3·去中心化·区块链·智能合约
Sui_Network1 天前
Sui 如何支持各种类型的 Web3 游戏
大数据·数据库·人工智能·游戏·web3·区块链
yunteng5212 天前
solidity之Foundry安装配置(一)
web3·区块链·solidity·foundry
simplesin5 天前
Web3 通识
web3
TechubNews10 天前
公然上线传销项目,Web3 的底线已经被无限突破
web3
OpenBuild.xyz10 天前
Web3 开发者周刊 36 | 构建自主未来:Agent、可扩展性与赏金
人工智能·web3·去中心化·区块链·智能合约
ThereIsNoCode10 天前
网页版贪吃蛇小游戏开发HTML实现附源码!
web3·html5
TinTin Land10 天前
国际互联网安全日|Web3 世界的安全挑战与防护指南
安全·web3
TechubNews10 天前
DeepSeek与Web3:科技融合的新纪元
科技·web3
dingzd9512 天前
Web3 的虚实融合之路:从虚拟交互到元宇宙构建
web3·交互