SpringBoot中前后端数据交互

不只适用于SpringBoot

工具:postman、IDEA

目的:测试前后端数据的交互情况、交互过程出现的明确各种问题及其解决方法

基础知识:

  Content-Type发送信息至服务器时内容编码类型,默认是( application/x-www-form-urlencoded 这种格式的特点就是,name/value 成为一组,每组之间用 & 联接)。

POST请求

① Content-Type:application/x-www-form-urlencoded

  前端请求:

  后端响应1:只是对应,没有任何注解

  后端响应2:参数添加@RequestParam注解

 

  后端响应3:参数添加@RequestBody注解,出现错误

错误:Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]

  后端响应4:参数用@RequestBody注解,是一个Java bean

错误:solved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]

 结论:

   当前端以application/x-www-form-urlencoded格式上传数据时,后台可以使用@RequestParam或者不使用任何注解来获取参数。 后台不可以使用@RquestBody来获取参数,使用的话会报错误。

② Content-Type:application/json

  前端请求:

  后端响应1:只是对应,没有任何注解,出错

首先它不会获取到任何值,然后因为age是int的,无法进行null的转换,导致报错

 java.lang.IllegalStateException: Optional int parameter 'age' is present but cannot be translated into a null value ....

  

  后端响应2:参数添加@RequestParam注解,出错

 

Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present]

结论:

 当前端以application/json格式上传即使用JSON字符串,后台使用@RequestParam是无法一一对应来获取参数的。

  后端响应3:参数添加@RequestBody注解,出错

错误:Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.panlei.practiceboot.controller.UserController.addUser(java.lang.String,int,java.lang.String,java.lang.String)]

结论:

 当前端以application/json格式上传即使用JSON字符串,后台使用@RequestBody是无法一一对应来获取参数的。

   

  后端响应4:参数用@RequestBody注解,是一个Java bean,成功

   后端响应4:参数用@RequestBody注解,是一个Map,成功

总的结论:

  当前端使用application/json来传递数据的时候,后端只能使用 @RequestBody 以及 Java bean或者 map 的方式来接收数据。

原文地址:https://www.cnblogs.com/panlei3707/p/11208811.html