后端接收请求中的参数
package org.springframework.web.bind.annotation; 中的注解
1.@RequestParam,用于将 HTTP 请求中的参数绑定到控制器方法的参数上。
- 他可以绑定GET/POST/PUT/DELETE请求的查询参数(查询参数附加在 URL 的末尾)
如:GET http://localhost:8080/user?status=active - 可以绑定POST请求中的表单数据(application/x-www-form-urlencoded 或 multipart/form-data格式的表单数据都可以绑定)
2.@RequestBody,用于将POST/PUT请求中,请求体的JSON格式的数据绑定到方法参数上。
1.将参数接收到后端的实体类中
1.1如果前端发出的参数在URL中
如果前端发出的参数在URL中,你可以使用 @ModelAttribute
注解。这样可以将请求中的参数自动绑定到实体类上。
前端发出的请求
GET /users?name=Alice&age=30
你的实体类
public class User {
private String name;
private int age;
// Getter 和 Setter
}
你的Controller
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping
public String getUser(@ModelAttribute User user) {
// 处理用户
return "User received: " + user.getName() + ", Age: " + user.getAge();
}
}
1.2如果前端发出的参数在请求体中
如果前端发出的参数在请求体中,并且请求体中包含与后端实体类属性相对应的数据时,可以使用 @RequestBody
注解来直接将请求体映射到实体类。
前端发出的请求
POST /users
Content-Type: application/json
{
"name": "Alice",
"age": 30
}
你的实体类
public class User {
private String name;
private int age;
// Getter 和 Setter
}
你的Controller
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public String createUser(@RequestBody User user) {
// 处理用户
return "User created: " + user.getName() + ", Age: " + user.getAge();
}
}
2.将URL中的单个参数绑定到后端的单个参数中
说明:使用 @RequestParam,你可以将URL中的单个参数直接绑定到后端方法的单个参数中。如果参数名称与请求参数名称不匹配,可以通过 name 属性指定。
前端发出的请求
/users?name=Alice&age=30
你的Controller
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping
public String getUserInfo(@RequestParam("name") String name, @RequestParam("age") int age) {
// 处理单个参数
return "User info: " + name + ", Age: " + age;
}
}
3.发送并接收表单数据(表单中可以选择文件,把文件发送)
如果想把excel文件导入到后端,可以把文件放入表单中,并把表单提交,后端此时可以通过@RequestParam接收每一个表单项。
@RequestParam 通常用于从 URL 查询参数中获取数据,但在某些情况下(比如表单提交),它也可以从请求体中获取数据。
html中的写法:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
Spring Boot 处理:
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(
@RequestParam String description,
@RequestParam MultipartFile file) {
// 处理文本字段
System.out.println("Description: " + description);
// 处理文件
if (!file.isEmpty()) {
try {
String fileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
// 保存文件到指定路径
// ...
return "File uploaded successfully: " + fileName;
} catch (IOException e) {
e.printStackTrace();
return "File upload failed";
}
} else {
return "No file selected";
}
}
}
ELement框架中的写法:
<!--点击新增按钮后弹出以下对话框,里面是一个表单-->
<el-dialog title="导入数据" :visible.sync="showImportDataDialog" :close-on-click-modal="false" width="600px">
<el-form :inline="true" label-width="148px">
<el-form-item label="版本名称" prop="versionName">
<el-input v-model="newForm.versionName" style="width:220px" placeholder="请输入版本名称"></el-input>
</el-form-item>
<div class="upload1">
<span style="color: red;">温馨提示:请选择文件1;</span>
<input type='file' @change="getFile($event)"/>
</div>
<div class="upload2">
<span style="color: red;">温馨提示:请选择文件2;</span>
<input type='file' @change="getFile2($event)"/>
</div>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click.native="showImportDataDialog = false">取消</el-button>
<el-button type="primary" @click.native="importData($event)">导入</el-button>
</div>
</el-dialog>
// 选择文件1
getFile(event) {
console.log('版本规则管理-选择业务模型')
this.file = event.target.files[0]
console.log(this.file)
},
//选择文件2
getFile2(event) {
console.log('版本规则管理-选择记账规则')
this.file2 = event.target.files[0]
console.log(this.file2)
},
// 新增导入
importData(event) {
console.log('版本规则管理-新增导入')
if (this.file == '' && this.file2 != '') {
this.$message.error('请选择业务模型!')
} else if (this.file != '' && this.file2 == '') {
this.$message.error('请选择记账规则!')
} else if (this.file == '' && this.file2 == '') {
this.$message.error('请选择业务模型和记账规则!')
} else {
// 取消默认行为
event.preventDefault()
// 创建 formData 对象
let formData = new FormData()
// 向 formData 对象中添加文件
formData.append('excelBusTemp', this.file)
formData.append('excelAccTemp', this.file2)
formData.append('versionName', this.newForm.versionName)
console.log('导入文件', formData)
this.$message({
showClose: false,
message: '版本正在创建中,请耐心等待......',
type: 'success'
})
Edition.addEdition(formData).then((res) => {
console.log('新增导入', res)
this.$message({
showClose: true,
message: res.message,
type: 'success'
})
this.showImportDataDialog = false
this.getEditions()
})
}
},
// 新增
addEdition(params) {
return http.post(URL + '/versions/add', params)
},
<style lang="less" scoped>
.upload1 {
margin-bottom: 50px;
margin-top: 35px;
margin-left: 80px;
}
.upload2 {
margin-bottom: 35px;
margin-left: 80px;
}
</style>
后端接收表单中的参数
@ResponseBody
@RequestMapping("/add")
public ResultModel versionAdd(@RequestParam(value = "excelBusTemp", required = true) MultipartFile busMultiFile,
@RequestParam(value = "excelAccTemp", required = true) MultipartFile accMultiFile,
@RequestParam(value = "versionName", required = true) String versionName) {
String versionNo ="";
4.表单的multipart/form-data格式和application/x-www-form-urlencoded格式的区别
表单参数有 application/x-www-form-urlencoded
格式和 multipart/form-data
格式。
注意:application/form-data是一个错误的写法。
application/x-www-form-urlencoded
,格式是最简单的表单数据编码格式。它适用于包含文本数据的表单,但不支持文件上传。
multipart/form-data
,适用于包含文件上传和复杂数据的表单。它可以同时处理文本字段和文件字段。
1. application/x-www-form-urlencoded
特点:
- 文本数据:仅适用于不包含文件的表单。
- 编码方式:数据被编码为
key=value
的形式,多个键值对之间用&
分隔。例如:name=John&age=30
。 - 请求头部:请求头部通常包含
Content-Type: application/x-www-form-urlencoded
。
示例:
HTML 表单:
<form action="/submit" method="post">
<input type="text" name="name" />
<input type="number" name="age" />
<button type="submit">Submit</button>
</form>
提交的请求体:
name=John&age=30
Spring Boot 处理:
@PostMapping("/submit")
public String submitForm(
@RequestParam String name,
@RequestParam int age) {
return "Received: Name=" + name + ", Age=" + age;
}
2. multipart/form-data
特点:
- 文件上传:支持文件上传,多个文件和文本字段可以混合提交。
- 编码方式:数据被分割成多个部分,每个部分表示一个表单字段(文本字段或文件字段)。
- 请求头部:请求头部必须包含
Content-Type: multipart/form-data; boundary=xxx
,其中boundary
是一个分隔符,用于分隔不同的表单字段。
示例:
HTML 表单:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
提交的请求体:
POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="description"
text的内容
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="example.txt"
Content-Type: text/plain
文件中的内容,以二进制发送..................................................
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Spring Boot 处理:
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(
@RequestParam String description,
@RequestParam MultipartFile file) {
// 处理文本字段
System.out.println("Description: " + description);
// 处理文件
if (!file.isEmpty()) {
try {
String fileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
// 保存文件到指定路径
// ...
return "File uploaded successfully: " + fileName;
} catch (IOException e) {
e.printStackTrace();
return "File upload failed";
}
} else {
return "No file selected";
}
}
}