前端部分(Vue表单):
<template>
<div class="form-container">
<form @submit.prevent="handleSubmit">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" v-model="form.name" required />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" v-model="form.email" required />
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" v-model="form.password" required />
</div>
<button type="submit">Submit</button>
</form>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'MyForm',
data() {
return {
form: {
name: '',
email: '',
password: ''
}
}
},
methods: {
async handleSubmit() {
// async指明该函数包含异步操作 配合await等待promise完成
// Promise 是 JavaScript 中用于处理异步操作的一个对象。异步操作是指在某个操作完成之前不会阻塞代码的其余部分执行的操作。例如,从服务器获取数据、读取本地文件或其他可能需要一些时间来完成的操作。
// Promise 对象代表了一个最终可能成功或失败的值。它有三种状态:
// Pending(进行中):初始状态,既不是成功,也不是失败。
// Fulfilled(已成功):表示操作成功完成。
// Rejected(已失败):表示操作失败。
try {
// 发送数据到后端的地址 api(本地运行环境)
const url = 'http://localhost:8080/api/submit-form'
// 发送 POST 请求到后端
const response = await axios.post(url, this.form)
// 当你使用 axios.post 方法,并将一个 JavaScript 对象作为第二个参数传递时,
// axios 会自动将该对象转换为 JSON 格式,
// await 等待关键字,等待promise解析完成
// axios库 向指定 URL(地址) 发送POST请求的方式(可以同比换get请求)
} catch (error) {
// 处理错误
console.error('表单发生错误:', error)
}
}
}
}
</script>
<style>
.form-container {
max-width: 400px;
margin: auto;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
</style>
后端部分(springboot)
package com.example.super_springboot;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FormController {
public static class FormData {
// 静态内部类
public String name;
public String email;
public String password;
// getters and setters
}
@PostMapping("/api/submit-form")
// 这个注解表示下面的方法应该处理所有发送到/api/submit-form的HTTP POST请求
public ResponseEntity<?> submitForm(@RequestBody FormData formData) {
// @RequestBody FormData formData 这个注解告诉Spring Boot应该尝试将请求体(JSON或其他格式)反序列化为FormData对象。
// 该对象的字段应该与请求体中的JSON键匹配。
System.out.println("Name: " + formData.name);
System.out.println("Email: " + formData.email);
System.out.println("Password: " + formData.password);
// 返回成功响应
return ResponseEntity.ok().body("Form submitted successfully");
}
}
表单效果: