Map Spring GET request (URL parameter) to complex object (Bean).
--Nested structure --List structure
Do not use annotations for Mapping.
Or
Use @ModelAttribute
.
Spring Boot:2.1.6
lombok
Parent object
@Data
@ToString
public class ComplexBean {
private String hoge;
private ChildBean childBean;
private List<ItemBean> itemBeans;
}
Child object for nesting
@Data
@ToString
public class ChildBean {
private String piyo;
}
Object for list
@Data
@ToString
public class ItemBean {
private String fuga;
}
@Data
and @ToString
are annotations of lombok
@ToString
is for verification@RestController
public class DemoRestController {
@GetMapping(value = "/param")
@ResponseBody
public String getParam(@RequestParam ComplexBean bean) {
System.out.println(bean.toString());
return bean.toString();
}
@GetMapping(value = "/model")
@ResponseBody
public String getModel(@ModelAttribute ComplexBean bean) {
System.out.println(bean.toString());
return bean.toString();
}
@GetMapping(value = "/direct")
@ResponseBody
public String getDirect(ComplexBean bean) {
System.out.println(bean.toString());
return bean.toString();
}
}
Restlet Client-Access each endpoint using REST API Testing
hoge=hoge&childBean.piyo=piyo&itemBeans[0].fuga=fuga0&itemBeans[2].fuga=fuga2
When using @RequestParam
(http://localhost:8080/param?hoge=hoge&childBean.piyo=piyo&itemBeans[0].fuga=fuga0&itemBeans[2].fuga=fuga2
)
Since the mapping information is insufficient, parsing cannot be performed and an error occurs.
Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required ComplexBean parameter 'bean' is not present]
When using @ModelAttribute
(http://localhost:8080/model?hoge=hoge&childBean.piyo=piyo&itemBeans[0].fuga=fuga0&itemBeans[2].fuga=fuga2
)
Mapped as expected.
Without annotation
(http://localhost:8080/direct?hoge=hoge&childBean.piyo=piyo&itemBeans[0].fuga=fuga0&itemBeans[2].fuga=fuga2
)
Mapped as expected.
Even with URL parameters that have the following structure --Nested structure --List structure
Do not use annotations for Mapping.
Or
Use @ModelAttribute
.
If so, it can be mapped ~~, but let's review the design when it becomes necessary to map to such an object with a GET request ~~.
If the sequence number is skipped as in verification, null
is set for the skipped branch number. (⇒ It will not be an empty object)
Recommended Posts