Java&Vue 借助json传递数据

发布于:2024-04-24 ⋅ 阅读:(131) ⋅ 点赞:(0)

由前端向后端发送一个json键值对

<template>
  <div>
    <button @click="sendRequest">发送请求</button>
  </div>
</template>

<script setup>
import axios from 'axios';

const sendRequest = () => {
  const jsonData = {
    key1: 'value1',
    key2: 'value2',
  };

  const jsonString = JSON.stringify(jsonData);

  axios.post('http://localhost:8080/test', jsonString, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
  .then(response => {
    console.log('成功发送请求', response);
    // 处理后端返回的响应
  })
  .catch(error => {
    console.error('发送请求失败', error);
    // 处理请求失败情况
  });
};
</script>

package com.example.myjson;

import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
public class JSONController {

    @PostMapping("/test")
    public String handleJSONRequest(@RequestBody String jsonString) {
        // 这里可以对接收到的JSON字符串进行处理
        System.out.println("接收到的JSON字符串:" + jsonString);

        // 返回一个简单的响应
        return "成功接收到JSON请求";
    }
}

发送一个由前端json包装过的类对象

<template>
  <div>
    <button @click="sendTaskInfo">发送TaskInfo</button>
  </div>
</template>

<script setup>
import axios from 'axios';

const sendTaskInfo = () => {
  // 创建 TaskInfo 对象
  const taskInfo = {
    id: 1,
    task: '完成项目任务',
    startTime: new Date(),
    endTime: new Date(),
    elapsedTime: 3600, // 假设任务耗时为3600秒
  };

  // 将 TaskInfo 对象转换为 JSON 字符串
  const jsonTaskInfo = JSON.stringify(taskInfo);

  // 发送 POST 请求到后端
  axios.post('http://localhost:8080/test', jsonTaskInfo, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
  .then(response => {
    console.log('成功发送 TaskInfo', response);
    // 处理后端返回的响应
  })
  .catch(error => {
    console.error('发送 TaskInfo 失败', error);
    // 处理请求失败情况
  });
};
</script>

public class TaskInfo {
    private int id;
    private String task;
    private Date startTime;
    private Date endTime;
    private long elapsedTime;
}
@PostMapping("/test")
    public ResponseEntity<String> handleJSONRequest(@RequestBody TaskInfo taskInfoJson) {
        // 这里 taskInfoJson 就是前端发送过来的 JSON 转换后的 TaskInfo 对象
        System.out.println("接收到的 TaskInfo 对象:" + taskInfoJson);

        // 在这里可以对 TaskInfo 对象进行进一步处理
        // ...

        // 返回一个简单的响应
        return new ResponseEntity<>("成功接收到 TaskInfo 对象", HttpStatus.OK);
    }

网站公告

今日签到

点亮在社区的每一天
去签到