Spring:当我的类已经用@RestController 注释时,为什么我还要使用@RequestBody? [英] Spring : Why should I still use @RequestBody when my class is already annotated with @RestController?
问题描述
我目前正在将 Java 和 Spring 用于我的 Web 服务应用程序.我正在使用 @RestController
注释,希望消除使用 @ResponseBody
和 @RequestBody
注释的需要.不幸的是,删除 @RequestBody
注释会使序列化失败.
I'm currently using Java and Spring for my web service applications. I'm using the @RestController
annotation hoping to remove the need to use the @ResponseBody
and @RequestBody
annotations. Unfortunately, removing the @RequestBody
annotations makes the serialization to fail.
这是我的代码,它没有将请求正文映射到我没有的方法参数:
Here's my code that doesn't map the request body to my method parameter that doesn't :
@RestController
@RequestMapping(value = "/member", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class MemberController {
@Autowired
private MemberService memberService;
@RequestMapping("/create")
public void create(Member member) {
memberService.create(member);
}
@RequestMapping("/read")
public Member read(Member member) {
return memberService.read(member);
}
@RequestMapping("/update")
public void update(Member member) {
memberService.update(member);
}
@RequestMapping("/delete")
public void delete(Member member) {
memberService.delete(member);
}
@RequestMapping("/retrieveById")
public Member retrieveById(Member member) {
return memberService.retrieveById(member);
}
@RequestMapping("/retrieveAll")
public List<Member> retrieveAll(Member member) {
return memberService.retrieveAll();
}
}
当我已经在使用 @RestController
时,我真的需要使用 @RequestBody
注释吗?
Do I really need to use the @RequestBody
annotation when I'm already using the @RestController
?
推荐答案
@RestController
包含 @ResponseBody
所以你不再需要这个了.
@RestController
contains @ResponseBody
so you do not need this any more.
但是你仍然需要@RequestBody
注解,因为你为POST请求调用的方法可能包含多个参数,其中一个映射到请求主体,方法的其他参数可能是 PathVariables
或例如 UriComponentsBuilder
.
But you still need the @RequestBody
annotation, because the method you call for a POST request might contain more than one parameters, one of which is mapped to the request body, other parameters of the method might be PathVariables
or for example a UriComponentsBuilder
.
并且要标记要映射到请求正文的参数,您需要注释.
And to mark the parameter which is to be mapped to the request body, you need the annotation.
这篇关于Spring:当我的类已经用@RestController 注释时,为什么我还要使用@RequestBody?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!