新建com.example.controller.JsonController
package com.example.controller;
import com.example.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author Administrator
*/
@Controller
public class JsonController {
@RequestMapping("/json")
@ResponseBody
public String json(@RequestBody User user) {
System.out.println(user);
return "json";
}
}
启动测试
后端控制台打印
[WARNING] Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.example.controller.JsonController.json(com.example.pojo.User)]
pom.xml文件添加依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.3</version>
</dependency>
启动测试
后端打印
User(name=zhangsan, age=12)
注释掉SpringMvcConfig的@EnableWebMvc注解
//@EnableWebMvc//开启SpringMVC的辅助功能,其中就包括字符串转成日期格式的数据、json数据格式的自动转换
启动测试
后端打印
[WARNING] Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported]
在JsonController中添加代码
@RequestMapping("/jsonList")
@ResponseBody
public String jsonList(@RequestBody List<String> list){
System.out.println(list);
return "jsonList";
}
打开SpringMvcConfig中@EnableWebMvc注解
启动测试
后端打印
[a, b, c]
修改jsonList方法
public String jsonList(@RequestBody String[] list) {
System.out.println(Arrays.toString(list));
return "jsonList";
}
启动测试
后端打印
[a, b, c]
添加代码
@RequestMapping("/pojoArrayParamForJson")
@ResponseBody
public String jsonList2(@RequestBody List<User> list) {
System.out.println(list);
return "pojoArrayParamForJson";
}
启动测试
后端打印
[User(name=zhangsan, age=12), User(name=zhangsan, age=12)]
请求参数(传递json数据)
名称:@RequestBody
类型:形参注解
位置:SpringMVC控制器方法形参定义前面
作用:将请求中请求体所包含的数据传递给请求参数,此注解一个处理器方法只能使用一次