SpringMVC中@ModelAttribute與@RequestBody的區(qū)別及說明
@ModelAttribute與@RequestBody的區(qū)別
最近在寫代碼的過程中,發(fā)現(xiàn)之前項目都是使用的@ModelAttribute注解,而自己的一貫使用都是@RequestBody,在網(wǎng)上找資料也沒有發(fā)現(xiàn)寫的十分具體的博客,因此自己寫了個SpringBoot的樣例進行了測試驗證。
@ModelAttribute與@RequestBody都是用來注解解析前端發(fā)來數(shù)據(jù),并自動對應到所定義的字段名稱。
這里先放結論
使用@ModelAttribute注解的實體類接收前端發(fā)來的數(shù)據(jù)格式需要為"x-www-form-urlencoded",@RequestBody注解的實體類接收前端的數(shù)據(jù)格式為JSON(application/json)格式。
(若是使用@ModelAttribute接收application/json格式,雖然不會報錯,但是值并不會自動填入)
測試
首先新建一個SpringBoot項目,這個不需要像SpringMVC項目那么配置麻煩,因為十分推薦這個。
導入需要的spring-boot-starter-web包。由于測試的前端發(fā)送的為json數(shù)據(jù),因此還需要導入json依賴。
? ? ? ? <dependency> ?? ??? ??? ?<groupId>net.sf.json-lib</groupId> ?? ??? ??? ?<artifactId>json-lib</artifactId> ?? ??? ??? ?<version>2.4</version> ?? ??? ??? ?<classifier>jdk15</classifier> ?? ??? ?</dependency> ?? ??? ?<dependency> ?? ??? ??? ?<groupId>commons-lang</groupId> ?? ??? ??? ?<artifactId>commons-lang</artifactId> ?? ??? ??? ?<version>2.5</version> ?? ??? ?</dependency> ?? ??? ?<dependency> ?? ??? ??? ?<groupId>commons-beanutils</groupId> ?? ??? ??? ?<artifactId>commons-beanutils</artifactId> ?? ??? ??? ?<version>1.9.2</version> ?? ??? ?</dependency> ?? ??? ?<dependency> ?? ??? ??? ?<groupId>commons-collections</groupId> ?? ??? ??? ?<artifactId>commons-collections</artifactId> ?? ??? ??? ?<version>3.2.1</version> ?? ??? ?</dependency> ?? ??? ?<dependency> ?? ??? ??? ?<groupId>commons-logging</groupId> ?? ??? ??? ?<artifactId>commons-logging</artifactId> ?? ??? ??? ?<version>1.2</version> ?? ??? ?</dependency>
根據(jù)前端發(fā)送的數(shù)據(jù),定義自己的接收實體類RuleModify,其字段名與前端發(fā)送的key值一致,若是需要改變,可以使用@SerializerName("")進行對應相應的key值。這里就不貼出代碼。
在Controller層對于要測試的方法使用@RequestBody接收前端數(shù)據(jù),可以看到數(shù)據(jù)都一一對應到實體類中了(測試工具為postman)。
@RestController @RequestMapping("/") public class TestController { ? ? ? @RequestMapping(value = "/test" ,method = RequestMethod.POST) ? ? public String testJson(@RequestBody RuleModify rule){ ? ? ? ? System.out.println("執(zhí)行"); ? ? ? ? JSONObject jsonObject = JSONObject.fromObject(rule); ? ? ? ? System.out.println(jsonObject); ? ? ? ? return "hello"; ? ? } ? ?? }
postman模擬前端發(fā)送請求。
可以看到成功打印出實體類,數(shù)據(jù)已經(jīng)對應到字段中了。
接下來使用@ModelAttribute注解RuleModify類,可以看到JSON(application/json) 格式下,數(shù)據(jù)為空,字段沒有進行注入。
使用postman的x-www-form-urlencoded方式進行模擬
可以看到后端成功的注入了數(shù)據(jù)。
至于這兩個注解的選擇,還是看前端會發(fā)送什么格式的數(shù)據(jù)之后來進行自由的選擇吧。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。