首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@ModelAttribute vs @RequestBody,@ResponseBody

@ModelAttribute vs @RequestBody,@ResponseBody
EN

Stack Overflow用户
提问于 2018-02-18 01:49:58
回答 1查看 4.8K关注 0票数 3

@ModelAttribute

代码语言:javascript
复制
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

代码语言:javascript
复制
@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体传递给服务器

  1. 现在哪一个是最好的方法?
  2. 如果两者都是为了相同的目的绑定到bean..which,那么一个是最佳实践还是被广泛用作标准实践?
  3. 这两种方法都处理多部分文件,并且它们是否都具有相互等效的选项?https://javabeat.net/spring-multipart-file-upload/ How do i upload/stream large images using Spring 3.2 spring-mvc in a restful way
  4. 他们中有谁的能力比另一个弱吗?就像长度限制,方法限制。弊端
  5. 哪一个在安全性方面更安全?
EN

回答 1

Stack Overflow用户

发布于 2018-09-18 08:51:06

正如javadoc所建议的那样,正是这种用法将它们区分开来,也就是说,如果要将对象绑定回web视图,则使用@ModelAttribute,如果不需要使用@RequestBody,则使用@RequestBody

  • @RequestBody
代码语言:javascript
复制
- 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.

  • @ModelAttribute
代码语言:javascript
复制
- 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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48847697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档