Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring MVC @ModelAttribute: allowlist fields before binding a form

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

A @ModelAttribute can bind request parameters onto writable properties; an @InitBinder allowlist limits which setters receive client input.

Download Spring source kit

Do not bind a privilege flag

A dispatch preference form exposes region to the requester, while canApprove belongs to the authorization model. Without a binding rule, a matching request parameter could set that writable property. The controller's binder allows only region. The checked MockMvc request sends canApprove=true and receives WEST:false, proving this local form binding ignored that field.

A dedicated input type with only permitted fields is preferable to exposing a domain object with administrative setters. An allowlist remains useful when a mutable form type is required. This lesson concerns @ModelAttribute parameter binding, not JSON @RequestBody deserialization; request validation and authorization are separate gates.

Keep rejected input handling deliberate

Ignoring an unexpected field can be acceptable for a browser form, but a strict API may reject it. Decide at the transport boundary and test that decision. A field allowlist does not limit raw request size, nested object depth or what an authenticated user may do after binding.

Checked code

Java
@InitBinder("dispatchPreference")
void allowedInput(WebDataBinder binder) {
    binder.setAllowedFields("region");
}

@PostMapping("/contract/dispatch-preference")
String update(@ModelAttribute DispatchPreference dispatchPreference) {
    return dispatchPreference.getRegion() + ":" + dispatchPreference.isCanApprove();
}

Verification boundary

The Maven source kit passes WiringAndBindingContractTest.formBindingIgnoresAnUnapprovedPrivilegeField on its local Spring Boot 4 and Java 21 fixture.

Cost and ownership

Binding cost grows with submitted fields and conversion work; request-size limits belong earlier in the HTTP stack. Standalone MockMvc proves this controller and binder path only. It does not prove the production filter chain, authenticated identity or persistence constraints.

Common Mistakes

  • Do not expose a domain entity with writable privilege fields as an unrestricted form object.
  • Do not mistake an allowlist for authorization.
  • Do not assume this binder constrains JSON request-body deserialization.

Read next

Spring MVC request lifecycle: from servlet filter to response body, Spring MVC request validation: reject invalid commands before mutation, Spring method authorization: reject a cross-tenant read, Spring MockMvc standalone tests: know which HTTP layers were assembled.

spring
spring-boot
mvc-modelattribute-allowed-fields
Storage details