@ModelAttribute
RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method =
RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) { }
http://.../?name=Something&age=100
public String doSomething(@ModelAttribute User user) { }@RequestBody
@RequestMapping(value = "/user/savecontact", method = RequestMethod.POST
public String saveContact(@RequestBody Contact contact){ }
{ "name": "Something", "age": "100" } in request body
public String doSomething(@RequestBodyUser user) { }@ModelAttribute将接受一个查询字符串。因此,所有数据都通过url传递给服务器。
@RequestBody,所有数据将通过完整的JSON体传递给服务器
发布于 2018-09-18 08:51:06
正如javadoc所建议的那样,正是这种用法将它们区分开来,也就是说,如果要将对象绑定回web视图,则使用@ModelAttribute,如果不需要使用@RequestBody,则使用@RequestBody
- Usecases : Restful controllers (ex: produce and consume json/xml, processing direct document download requests, searching for stuff, ajax requests )
- As the name suggests the if a method argument is annotated with @RequestBody annotation Spring converts the HTTP request body to the Java type of the method argument.
- Is only allowed on method parameters (@Target(value={ PARAMETER}))
- The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request.
- works for Post and not Get method.
- Usecases : web app controllers (ex: binding request query parameters, populating web views with options and defaults)
- Uses data binders & ConversionService
- Is allowed on methods and method params(@Target(value={METHOD, PARAMETER}))
- Useful when dealing with model attributes for adding and retrieving model attributes to and from the Srping’s Model object
- When used on METHODS, those methods are invoked before the controller methods annotated with @RequestMapping are invoked
- binds a method PARAMETER or method return value to a named model attribute & the bound named model attributes are exposed to a web view
- binds request query parameters to bean
有关数据绑定和类型转换的详细信息,请参阅:https://docs.spring.io/spring/docs/5.1.x/spring-framework-reference/core.html#validation
https://stackoverflow.com/questions/48847697
复制相似问题