前后端分离,后端用@RequestBody Map<String,Integer> map可以接收到值,用Integer id接收不到
时间: 2024-03-08 11:49:45 浏览: 18
@RequestBody 注解表示请求体中的数据会被映射到方法的参数上。在这个例子中,请求体是一个 JSON 对象,它被映射到了一个 Map<String,Integer> 对象上。
如果后端使用 Integer id 参数接收请求体中的数据,那么就需要在请求体中指定 id 的键名,例如:
{
"id": 123
}
这样,后端就可以通过 @RequestBody Integer id 参数接收到请求体中的 id 值了。
如果你不想在请求体中指定键名,可以将 Map<String,Integer> 对象转化为一个自定义的 Java 对象,例如:
```
public class MyRequest {
private Integer id;
// getter and setter
}
```
然后在后端使用 @RequestBody MyRequest request 参数接收请求体中的数据。这样做的好处是可以在请求体中使用更加直观的属性名,同时也能够避免键名写错的问题。
相关问题
uniapp中这样写:this.$api.jsonHttp.post('/api/TechnologicalItem/addOrUpdateItem', this.array,this.total).then(res => { console.log(res) }) 后端: @PostMapping("addOrUpdateItem") public ResponseResult<List<AsStmTechnologicalItemEntity>> save(@RequestBody Map<String, List<AsStmTechnologicalItemEntity>> map,Integer total) { System.out.println(total); asStmTechnologicalItemJpaRestService.save(map); return ResponseResult.SUCCEED; } total接收不到值,帮我修正一下
在前端代码中,你使用的是POST方法传递数据,但是total参数是通过URL传递的,因此在后端代码中需要通过@RequestParam注解来接收total参数。你可以按照以下方式修改后端代码:
@PostMapping("addOrUpdateItem")
public ResponseResult<List<AsStmTechnologicalItemEntity>> save(@RequestBody Map<String, List<AsStmTechnologicalItemEntity>> map, @RequestParam Integer total) {
System.out.println(total);
asStmTechnologicalItemJpaRestService.save(map);
return ResponseResult.SUCCEED;
}
在前端代码中,你需要将total参数改为URL参数的形式,可以按照以下方式修改:
this.$api.jsonHttp.post('/api/TechnologicalItem/addOrUpdateItem?total=' + this.total, this.array).then(res => {
console.log(res)
})
这样就可以在后端代码中正确接收total参数了。
/** * 取消收藏图书 * * @param params */ @DeleteMapping("/deleteCollect") public void deleteCollectById(@RequestBody Map<String, Object> params) { Integer userId = (Integer) params.get("userId"); Integer bookId = (Integer) params.get("bookId"); collectService.deleteCollectById(userId, bookId); }void deleteCollectById(Integer userId, Integer bookId);@Override public void deleteCollectById(Integer userId, Integer bookId) { collectMapper.deleteCollectById(userId, bookId); }void deleteCollectById(@Param("userId") Integer userId, @Param("bookId") Integer bookId);<delete id="deleteCollect" parameterType="Integer"> delete from collect where user_id = #{userId} and book_id = #{bookId} </delete>这些是后端数据,结合前端分析错误
根据你提供的后端代码,可以看出在 `deleteCollectById()` 方法中,参数类型应该是 `Map<String, Object>` 而不是 `Integer`。也就是说,应该将 `deleteCollect()` 方法中的 `data` 修改为以下内容:
```
data: {
userId: _this.userId,
bookId: bookId
}
```
另外,在 `collectMapper.xml` 文件中,`deleteCollectById()` 方法的参数应该为 `Map<String, Object>`,而不是 `@Param("userId") Integer userId` 和 `@Param("bookId") Integer bookId`。修改后的代码如下:
```
void deleteCollectById(Map<String, Object> params);
<delete id="deleteCollect" parameterType="java.util.Map">
delete from collect where user_id = #{userId} and book_id = #{bookId}
</delete>
```
修改后,重新测试是否能够正常删除收藏。