Spring Boot + Angular Frontend and Backend Data Interaction (Including File Upload)
Prerequisites
Development Environment
Angular 12, Spring Boot 2.2.12.RELEASEFrontend Variable Declaration
preUrl: string = "http://127.0.0.1:8080/user";
user: any = { username: "Lingnian", age: 6, classname: "Class One" };- Backend Entity Code
@Data
public class User {
private String username;
private String classname;
private int age;
private MultipartFile[] files;
}1. Passing Values via GET
- Path Variables
A way to pass values by placing parameters in the path, such as user/userInfo/6.
Frontend Code:
getPath() {
const { username, age } = this.user;
this.http.get(`${this.preUrl}/${username}/${age}`).subscribe((res) => {
console.log(res);
});
}Backend controller using the @PathVariable annotation code:
@GetMapping("/{username}/{age}")
public Result getPath(@PathVariable int age, @PathVariable String username) {
log.info("Received information: username: {}, age: {}", username, age);
return Result.message("success");
}- Query Parameters
Appending parameters to the end of the URL, generating an address like user/userInfo?id=6.
Frontend Code:
getQuery() {
this.http
.get(`${this.preUrl}/getQuery`, { params: this.user })
.subscribe((res) => {
console.log(res);
});
}Backend controller using the @RequestParam annotation or no annotation code: (When not using an annotation, ensure the field names match)
@GetMapping("/getQuery")
public Result getQuery(@RequestParam("age") int age, String username) {
log.info("Received information: username: {}, age: {}", username, age);
return Result.message("success");
}2. Passing Values via POST
- JSON Payload
The most commonly used method for passing values via POST.
Frontend Code:
jsonPostBody() {
this.http.post(`${this.preUrl}/postUserInfo`, this.user).subscribe((res) => {
console.log(res);
});
}Backend using the @RequestBody annotation:
@PostMapping("/postUserInfo")
public Result postUserInfo(@RequestBody User user) {
String username = user.getUsername();
int age = user.getAge();
log.info("Received information: username: {}, age: {}", username, age);
return Result.message("success");
}- Form Data
Frontend Code:
formPostBody() {
const form = new FormData();
for (let key of Object.keys(this.user)) {
form.append(key, this.user[key]);
}
this.http.post(`${this.preUrl}/postFormUserInfo`, form).subscribe((res) => {
console.log(res);
});
}Backend Code:
@PostMapping("/postFormUserInfo")
public Result postFormUserModel(User user) {
log.info("Received information: username: {}, age: {}", user.getUsername(), user.getAge());
for (MultipartFile file : user.getFiles()) {
System.out.println(file.getOriginalFilename());
}
return Result.message("success");
}Or using the @RequestParam annotation:
@PostMapping("/postFormUserInfo")
public Result postFormUserInfo(@RequestParam("username") String username, int age) {
log.info("Received information: username: {}, age: {}", username, age);
return Result.message("success");
}*Note:
- GET value passing methods are also applicable to POST, but note that the Body is required for the frontend POST method.
- Query Parameters and Form Data can actually share the same backend code when using POST for value passing.
- POST Value Passing with File Upload
Frontend Code:
postFormUserModel() {
const form = new FormData();
for (let key of Object.keys(this.user)) {
form.append(key, this.user[key]);
}
for (let file of this.files) {
form.append('files', file);
}
this.http.post(`${this.preUrl}/postFormUserModel`, form, {
// headers: {
// enctype: 'multipart/form-data',
// },
}).subscribe((res) => {
console.log(res);
});
}Backend Code:
@PostMapping("/postFormUserModel")
public Result postFormUserModel(User user) {
log.info("Received information: username: {}, age: {}", user.getUsername(), user.getAge());
for (MultipartFile file : user.getFiles()) {
System.out.println(file.getOriginalFilename());
}
return Result.message("success");
}
// Or
@PostMapping("/postFormUserModel")
public Result postFormUserModel(String username, int age, MultipartFile[] files) {
log.info("Received information: username: {}, age: {}", username, age);
for (MultipartFile file : files) {
System.out.println(file.getOriginalFilename());
}
return Result.message("success");
}References:
- Spring Boot Learning (4) --- Spring Boot Parameter Passing Methods
- Repository Address: https://gitee.com/zechen21/demo-pass-value.git
AI Translation | AI 翻译
This article was translated from Chinese to English by AI. If there are any inaccuracies, please refer to the original Chinese version.
本文由 AI 辅助从中文翻译为英文。如遇不准确之处,请以中文原版为准。
