Spring&Vue,四种常用的请求,如何编写

四种请求各是什么意思

post 约等于插入操作 insert

get 就是查询

put 是修改

delete 。。。

DemoController.java

java 复制代码
package com.example.demo.controller;

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

@CrossOrigin
@RequestMapping("/test") // 将公共路径添加到类上
@RestController
public class DemoController {

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

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

    @GetMapping("/get/{id}") // 在路径中定义了一个名为"id"的路径参数
    public String handleGetRequest(@PathVariable("id") String id) {
        // 根据接收到的路径参数进行条件查询逻辑
        // 假设这里根据id查询某个结果,这里只是简单示例
        if ("1".equals(id)) {
            System.out.println("查询到ID为1的结果");
            return "查询到ID为1的结果";
        } else {
            System.out.println("未查询到符合条件的结果");
            return "未查询到符合条件的结果";
        }
    }

    @PutMapping("/put")
    public String handlePutRequest(@RequestBody String data) {
        // 处理PUT请求逻辑
        System.out.println("接收到的PUT请求数据:" + data);
        return "处理PUT请求";
    }

    @DeleteMapping("/delete")
    public String handleDeleteRequest() {
        System.out.println("接收到DELETE请求");
        // 处理DELETE请求逻辑
        return "处理DELETE请求";
    }
}

DemoControllerTest.java

java 复制代码
package com.example.demo.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@SpringBootTest
@AutoConfigureMockMvc
public class DemoControllerTest {
    // 注入MockMvc来模拟HTTP请求
    @Autowired
    private MockMvc mockMvc;

    /**
     * 测试POST请求是否正常处理。
     * 发送一个JSON格式的POST请求到"/test/post"路径,并验证返回状态码和内容。
     */
    @Test
    public void testPost() throws Exception {
        // 发送一个 POST 请求到 "/test/post" 路径
        mockMvc.perform(MockMvcRequestBuilders.post("/test/post")
                        // 设置请求的 Content-Type 为 JSON 格式
                        .contentType(MediaType.APPLICATION_JSON)
                        // 设置请求体为 JSON 格式的字符串,模拟客户端发送的 JSON 数据
                        .content("{\"key\":\"value\"}"))
                // 断言返回的状态码为 OK (200)
                .andExpect(MockMvcResultMatchers.status().isOk())
                // 断言返回的内容为 "成功接收到JSON请求"
                .andExpect(MockMvcResultMatchers.content().string("成功接收到JSON请求"));
    }

    /**
     * 测试GET请求是否正常处理。
     * 发送一个GET请求到"/test/get"路径,并验证返回状态码和内容。
     */
    @Test
    public void testGet() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/test/get/1")
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("查询到ID为1的结果"));
    }

    /**
     * 测试PUT请求是否正常处理。
     * 发送一个JSON格式的PUT请求到"/test/put"路径,并验证返回状态码和内容。
     */
    @Test
    public void testPut() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.put("/test/put")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"key\":\"value\"}"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("处理PUT请求"));
    }

    /**
     * 测试DELETE请求是否正常处理。
     * 发送一个DELETE请求到"/test/delete"路径,并验证返回状态码和内容。
     */
    @Test
    public void testDelete() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.delete("/test/delete")
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("处理DELETE请求"));
    }
}

App.vue

html 复制代码
<template>
  <div>
    <button @click="testPost">测试POST请求</button>
    <button @click="testGet">测试GET请求</button>
    <button @click="testPut">测试PUT请求</button>
    <button @click="testDelete">测试DELETE请求</button>
    <div v-if="response">{{ response }}</div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const response = ref('');
const templateUrl='http://localhost:8081/test';

async function testPost() {
  try {
    const jsonData = {
      key1: 'value1'
    };

    const jsonString = JSON.stringify(jsonData);
    const response = await axios.post(templateUrl + '/post', jsonString, {
      headers: {
        'Content-Type': 'application/json',
      }
    });
    handleResponse(response);
  } catch (error) {
    console.error('Error:', error);
  }
}

async function testGet() {
  try {
    const response = await axios.get(templateUrl + '/get/1');
    handleResponse(response);
  } catch (error) {
    console.error('Error:', error);
  }
}

async function testPut() {
  try {
    const jsonData = {
      key: 'value'
    };

    const jsonString = JSON.stringify(jsonData);
    const response = await axios.put(templateUrl + '/put', jsonString, {
      headers: {
        'Content-Type': 'application/json',
      }
    });
    handleResponse(response);
  } catch (error) {
    console.error('Error:', error);
  }
}

async function testDelete() {
  try {
    const response = await axios.delete(templateUrl + '/delete');
    handleResponse(response);
  } catch (error) {
    console.error('Error:', error);
  }
}

function handleResponse(response) {
  response.value = response.data;
  console.log(response);
}
</script>
相关推荐
.生产的驴2 分钟前
Electron Vue框架环境搭建 Vue3环境搭建
java·前端·vue.js·spring boot·后端·electron·ecmascript
老齐谈电商7 分钟前
Electron桌面应用打包现有的vue项目
javascript·vue.js·electron
爱学的小涛10 分钟前
【NIO基础】基于 NIO 中的组件实现对文件的操作(文件编程),FileChannel 详解
java·开发语言·笔记·后端·nio
吹老师个人app编程教学11 分钟前
详解Java中的BIO、NIO、AIO
java·开发语言·nio
爱学的小涛11 分钟前
【NIO基础】NIO(非阻塞 I/O)和 IO(传统 I/O)的区别,以及 NIO 的三大组件详解
java·开发语言·笔记·后端·nio
北极无雪15 分钟前
Spring源码学习:SpringMVC(4)DispatcherServlet请求入口分析
java·开发语言·后端·学习·spring
琴智冰19 分钟前
SpringBoot
java·数据库·spring boot
binqian19 分钟前
【SpringSecurity】基本流程
java·spring
LIURUOYU42130820 分钟前
vue.js组建开发
vue.js
九圣残炎25 分钟前
【Vue】vue-admin-template项目搭建
前端·vue.js·arcgis