RestFul风格的接口一些比较复杂的参数会转换成Json通过请求体传递过来。这种时候我们可以使用@RequestBody注解获取请求体中的数据。
配置
SpringMVC可以帮我们把json数据转换成我们需要的类型。但是需要进行一些基本配置。SpringMVC默认会使用jackson来进行json的解析。所以我们需要导入jackson的依赖(前面我们已经导入过)。
<!-- jackson,帮助进行json转换-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
然后还要配置注解驱动(前面已经配置过)
<mvc:annotation-driven>
</mvc:annotation-driven>
使用
范例一
要求定义个RestFul风格的接口,该接口可以用来新建用户。请求路径要求为 /user ,请求方式要求为POST。
用户数据会转换成json通过请求体传递。 请求体数据
{"name":"三更","age":15}
获取参数封装成实体对象
如果我们想把Json数据获取出来封装User对象,我们可以这样定义方法:
@Controller
public class UserController {
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String insertUser(@RequestBody User user){
System.out.println("insertUser");
System.out.println(user);
return "/success.jsp";
}
}
User实体类如下:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private Integer age;
}