Master Spring Boot 3 Parameter Binding: From @RequestBody to Custom Converters
This tutorial walks through Spring Boot 3.5.0 request parameter binding techniques—including @RequestBody for POST, automatic GET binding, field restrictions, required fields, nested objects, validation annotations, custom enum conversion, and programmatic data binding—providing code samples and execution results for each case.
Introduction
Environment: Spring Boot 3.5.0. In Spring MVC, POST requests with JSON payload are commonly handled using the @RequestBody annotation, which automatically maps the request body to a Java object. GET requests can also bind query parameters directly to object fields without @RequestBody.
@GetMapping("/query2")
public User query2(User user) {
return user;
}
public class User {
private String name;
private String password;
}Example request URL:
/user/create?name=pack_xg&password=1231232. Practical Cases
2.1 Restrict Field Binding
Use @InitBinder to disallow specific fields (e.g., password) from being bound, preventing malicious or unwanted data injection.
@InitBinder
public void init(WebDataBinder binder) {
binder.setDisallowedFields("password");
}
@GetMapping("/query2")
public User query2(User user) {
return user;
}Result:
2.2 Set Required Fields
Define mandatory fields with binder.setRequiredFields. If required fields are missing, BindingResult captures errors.
@InitBinder
public void init(WebDataBinder binder) {
binder.setRequiredFields("email", "name");
}
@GetMapping("/query2")
public Object query2(@Validated User user, BindingResult error) {
if (error.hasErrors()) {
return error.getFieldErrors()
.stream()
.map(err -> "【%s】字段%s".formatted(err.getField(), err.getDefaultMessage()))
.toList();
}
return user;
}Result (missing email which is not in User):
2.3 Nested Field Binding
Spring MVC can automatically map hierarchical query parameters to nested objects.
public class User {
private String name;
private String password;
private Order order;
}
public class Order {
private String sno;
private Address address;
}
public class Address {
private String city;
}Accessing the endpoint with parameters like order.sno and order.address.city yields a fully populated object.
2.4 Parameter Validation
Apply validation annotations such as @NotEmpty on fields and use @Validated in the controller to trigger checks.
public class User {
@NotEmpty(message = "姓名必须填写")
private String name;
@NotEmpty(message = "密码必须填写")
private String password;
private Order order;
}
@GetMapping("/query2")
public Object query2(@Validated User user, BindingResult error) {
// validation logic
}Validation errors are returned as a list.
2.5 Custom Type Conversion
When default converters are insufficient, register a custom editor for an enum type.
public enum Sex {
MALE(1, "男"),
FEMALE(2, "女");
private final Integer code;
private final String value;
@JsonValue
public String getValue() { return value; }
public static Sex getByCode(Integer code) {
if (code == null) return null;
for (Sex s : values()) {
if (s.code.equals(code)) return s;
}
return null;
}
}
@InitBinder
public void init(WebDataBinder binder) {
binder.registerCustomEditor(Sex.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(Sex.getByCode(Integer.valueOf(text)));
}
});
}
@GetMapping("/query4")
public Object query4(User user) {
return user;
}Without the custom converter, the request fails (error screenshot). After registration, the enum is correctly bound.
2.6 Programmatic Data Binding
Bind request parameters manually using ServletRequestDataBinder.
@GetMapping("/query3")
public Object query3(HttpServletRequest request) {
User target = new User();
ServletRequestDataBinder binder = new ServletRequestDataBinder(target);
binder.bind(request);
return target;
}Another approach sets values directly via MutablePropertyValues before binding.
@GetMapping("/query3")
public Object query3() {
User target = new User();
ServletRequestDataBinder binder = new ServletRequestDataBinder(target);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("name", "Pack_xg");
pvs.addPropertyValue("order.sno", "T0001");
pvs.addPropertyValue("order.address.city", "重庆");
binder.bind(pvs);
return target;
}Conclusion
The article demonstrates a comprehensive set of Spring Boot 3 request‑binding techniques, ranging from simple GET/POST mapping to advanced field restrictions, required‑field enforcement, nested object handling, validation, custom enum conversion, and programmatic binding, each illustrated with runnable code and output screenshots.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
