Springboot前后端如何交互
时间: 2024-03-20 09:33:47 浏览: 12
Spring Boot 前后端交互可以通过 RESTful API 实现。具体步骤如下:
1. 定义后端接口
在后端 Controller 中定义需要提供的接口,例如:
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@PostMapping("/users")
public User addUser(@RequestBody User user) {
return userService.addUser(user);
}
// 其他接口...
}
```
2. 实现前端请求
前端通过 AJAX 或 Fetch 等方式向后端发送请求,例如:
```javascript
// 获取所有用户
fetch('/api/users').then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// 添加用户
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Tom',
age: 20
})
}).then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```
3. 处理前端请求
后端接收到前端请求后,可以通过 Spring 提供的 @RequestBody 注解解析请求体,并返回 JSON 格式的数据,例如:
```java
@RestController
@RequestMapping("/api")
public class UserController {
// ...
@PostMapping("/users")
public User addUser(@RequestBody User user) {
User newUser = userService.addUser(user);
return newUser;
}
}
```
4. 处理跨域请求
如果前端和后端不在同一个域名下,需要处理跨域请求。可以通过在后端 Controller 中添加 @CrossOrigin 注解来实现,例如:
```java
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:8080", maxAge = 3600)
public class UserController {
// ...
}
```
其中,origins 指定允许的跨域访问地址,maxAge 指定缓存时间。如果需要允许所有跨域访问,可以设置 origins = "*"。