// Controller 代码
@RequestMapping(value = "/test", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public String test(User user) {
return user.toString();
}
// 用于接收参数的类
@NoArgsConstructor
@Data
public class User {
private String username;
private String password;
private Detail detail;
@Data
public class Detail {
private String gender;
private String location;
public Detail() {
}
}
}
// 前端请求代码
$.post("http://localhost:8083/rrt/test", {
"username": "aaaa",
"password": "bbbb",
"detail": {
"gender": "male",
"location": "Beijing"
}
})
当这么发送数据时,后端就会报错:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.NullValueInNestedPathException: Invalid property 'detail' of bean class [com.example.demo.param.User]: Could not instantiate property type [com.example.demo.param.User$Detail] to auto-grow nested property path; nested exception is java.lang.NoSuchMethodException: com.example.demo.param.User$Detail.<init>()] with root cause
在 application/json 发送时,采用 @ResponseBody 就可以正确的绑定嵌套参数;那么在 form-data 的请求方式中,该如何做呢?