Skip to content
notes.vinhnq.com

Search

SpringMid20 min read

Form binding and validation in Spring MVC

Review 19 cards
On this page

Spring MVC end to end series: 1. Maven and project layout · 2. DispatcherServlet and views · 3. Forms and validation · 4. Form login with Spring Security · 5. Sessions and remember-me · 6. File upload · 7. Cart and checkout · 8. Pagination and dynamic filters

A server-rendered web app lives on forms: create a user, edit a product, sign up, check out. This post follows the data from the moment the browser sends name=value strings to the moment the controller holds a validated object and the page shows each error under the right field. The REST side (errors returned as JSON) is in the post on error handling and DTO validation; this one covers HTML forms.

1. How form data becomes an object

Key idea: the browser sends only strings. Spring creates the form object, uses a WebDataBinder to copy and convert each parameter, records failures in a BindingResult, and only then runs validation.

A form involves two requests. GET opens it: the controller puts an empty object (or existing data) into the Model, and the view uses it to fill the inputs. POST submits it: the body is application/x-www-form-urlencoded, for example fullName=Alice&role=USER.

sequenceDiagram
    participant B as Browser
    participant D as DispatcherServlet
    participant W as WebDataBinder
    participant V as Validator
    participant C as Controller
    B->>D: POST /register (fullName=Al, role=BOSS)
    D->>W: Create RegisterForm, copy and convert each parameter
    W-->>D: Conversion errors go into BindingResult
    D->>V: @Valid present, run Bean Validation
    V-->>D: Constraint errors go into the same BindingResult
    D->>C: register(form, bindingResult)
    C-->>B: Errors mean re-render the form, otherwise redirect
  • Creating the object: a class with a no-arg constructor is created with it, then setters are called. A record, or a class with exactly one public constructor with parameters, gets request parameters passed straight into that constructor (constructor binding, Spring 6.1+).
  • Converting: the ConversionService turns "USER" into Role.USER, "2026-11-18" into a LocalDate (with @DateTimeFormat), "APPLE,DELL" into a List<String>.
  • Conversion errors: role=BOSS isn’t a valid enum constant, so the binder records error code typeMismatch on role and leaves the field empty. In my run: errors=2 [role:typeMismatch, fullName:NotBlank], both kinds in one BindingResult.
Error codes, messages.properties and @InitBinder

Every error carries a list of codes, from specific to general. A @NotBlank error on form.fullName produces:

NotBlank.form.fullName, NotBlank.fullName, NotBlank.java.lang.String, NotBlank

Spring looks them up in messages.properties in that order and uses the first one it finds. So you can write one generic NotBlank=Must not be empty plus a few field-specific ones. Inside an annotation, message = "{user.phone.invalid}" is also resolved as a key.

@InitBinder customises the binder for one controller (or for all of them inside a @ControllerAdvice):

@InitBinder("form")                       // only for the model attribute named "form"
void init(WebDataBinder b) {
    b.registerCustomEditor(String.class, new StringTrimmerEditor(true)); // "  " -> null
}

StringTrimmerEditor(true) trims whitespace and turns empty strings into null, so both @NotNull and @NotBlank catch an empty input, and the database never stores " ".

2. A form DTO instead of the entity

Key idea: the binder copies every parameter whose name matches a field. Bind the entity and the client can change columns that aren’t on the form (role, passwordHash). A form DTO holds only what the user is allowed to send.

The bug is called mass assignment: the app takes a whole object from the request and saves it without filtering fields. A form with no role input doesn’t mean the request has no role; anyone can add one with DevTools or curl.

The course binds the User entity directly in every lab. My lab uses RegisterForm (email, full name, password, confirm password) and UserForm for the admin page (full name, phone, role). The test registerIgnoresInjectedRole adds role=ADMIN to a sign-up: the new user is still USER, and the password is stored as {bcrypt}....

3. Bean Validation: spec and implementation

Key idea: Jakarta Bean Validation is the shared rulebook (annotations like @NotBlank, @Email, the Validator API); Hibernate Validator is the library that implements it. Adding spring-boot-starter-validation is all you need.

The course asks “Hibernate Validator or Jakarta Validation, pick one” and adds hibernate-validator:8.0.1.Final by hand. Both ideas are off.

Table of common annotations
Annotation Checks Note
@NotNull not null empty string "" passes
@NotEmpty not null, length > 0 " " passes
@NotBlank at least one non-whitespace character use it for typed-in text
@Size(min, max) string length, collection size null counts as valid
@Email email shape a@b passes; real check is a confirmation email
@Pattern(regexp) whole string matches the regex null counts as valid
@Min, @Max, @Positive numbers
@Past, @Future dates and times

Most constraints treat null as valid so you can combine them freely: @NotBlank @Size(max = 100).

@Valid (from the spec) tells Spring to validate that parameter and cascade into nested objects. @Validated (from Spring) does the same but accepts groups, for example an OnCreate group that requires a password and an OnUpdate group that doesn’t.

4. BindingResult and parameter order

Key idea: a BindingResult belongs to the parameter right before it. With it, Spring lets the controller handle errors; without it, or in the wrong place, Spring throws and the user gets a 400 error page.

@PostMapping("/register")
String register(@Valid @ModelAttribute("form") RegisterForm form, BindingResult result,
                RedirectAttributes ra) {
    if (result.hasErrors()) return "auth/register";   // re-render: keeps input + errors
    users.save(new AppUser(form.getEmail(), encoder.encode(form.getPassword()),
                           form.getFullName(), Role.USER));
    ra.addFlashAttribute("message", "Signed up, please log in");
    return "redirect:/login";                         // PRG
}

On errors the controller returns the view name, not a redirect: the form object and its BindingResult are still in the model, so the view refills the inputs and prints the errors. Redirecting here would lose both.

5. Showing errors in the view

Key idea: Thymeleaf reads the BindingResult through th:object, th:field, th:errors and #fields. Field errors go under their input; object-level (global) errors go at the top of the form.

<form th:action="@{/register}" th:object="${form}" method="post">
  <div th:if="${#fields.hasGlobalErrors()}" th:each="e : ${#fields.globalErrors()}" th:text="${e}"></div>

  <input th:field="*{email}" class="form-control" th:errorclass="is-invalid">
  <div class="invalid-feedback" th:errors="*{email}"></div>

  <input type="password" th:field="*{password}" class="form-control" th:errorclass="is-invalid">
  <div class="invalid-feedback" th:errors="*{password}"></div>
  <button>Sign up</button>
</form>
  • th:field="*{email}" generates id, name and value from the object, so after an error the input keeps what was typed. For password inputs Thymeleaf deliberately leaves the value out.
  • th:errorclass="is-invalid" adds Bootstrap’s class when the field has errors; Bootstrap’s invalid-feedback only shows when it follows an input with is-invalid.
  • th:action="@{...}" with method="post" inserts the hidden _csrf input when Spring Security is present. A form whose action is a raw string misses the token and gets a 403.
The JSP equivalent (form:form, form:errors)

The course uses JSP with Spring’s tag library. The same form:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form action="/register" method="post" modelAttribute="form">
  <form:errors cssClass="alert alert-danger" element="div"/>          <%-- global errors --%>
  <form:input path="email" cssClass="form-control" cssErrorClass="form-control is-invalid"/>
  <form:errors path="email" cssClass="invalid-feedback"/>
  <form:password path="password" cssClass="form-control" cssErrorClass="form-control is-invalid"/>
  <form:errors path="password" cssClass="invalid-feedback"/>
  <button>Sign up</button>
</form:form>

Mapping: modelAttribute ↔ th:object, path ↔ th:field, form:errors path ↔ th:errors, cssErrorClass ↔ th:errorclass. <form:form> also adds the _csrf input. The course’s approach of using <spring:bind> to read the error state and build the class by hand works, but cssErrorClass is shorter. Why Spring Boot leans towards Thymeleaf rather than JSP is in part 2.

6. Custom validators: field level and class level

Key idea: write an annotation with @Constraint(validatedBy = ...) and a ConstraintValidator class. Put it on a field to check one value; put it on the class to compare several fields.

The sign-up form needs two rules that don’t exist out of the box: the email isn’t taken, and both password inputs match. The test registerShowsFieldAndClassLevelErrors submits a taken email, a 2-character name, a short password and a wrong confirmation: the page returns 200 with view auth/register, errors on all four fields, and the text “Email đã được dùng” (email already used).

@PasswordsMatch                       // class level: sees the whole object
public class RegisterForm {
    @NotBlank @Email @UniqueEmail     // field level: sees one string
    private String email;
    // fullName, password, confirmPassword...
}
  • Field level (@UniqueEmail): Spring creates the validator as a bean, so its constructor can take a UserRepository.
  • Class level (@PasswordsMatch): by default the error is a global error. Call addPropertyNode("confirmPassword") to attach it to the confirmation input so it shows right under it.
Full code of both validators
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueEmailValidator.class)
public @interface UniqueEmail {
    String message() default "Email đã được dùng";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> {
    private final UserRepository users;
    public UniqueEmailValidator(UserRepository users) { this.users = users; }  // injected by Spring
    @Override public boolean isValid(String email, ConstraintValidatorContext ctx) {
        return email == null || !users.existsByEmailIgnoreCase(email);        // null is @NotBlank's job
    }
}

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordsMatchValidator.class)
public @interface PasswordsMatch {
    String message() default "Mật khẩu nhập lại không khớp";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class PasswordsMatchValidator implements ConstraintValidator<PasswordsMatch, RegisterForm> {
    @Override public boolean isValid(RegisterForm f, ConstraintValidatorContext ctx) {
        if (f.getPassword() == null || f.getPassword().equals(f.getConfirmPassword())) return true;
        ctx.disableDefaultConstraintViolation();                 // drop the default global error
        ctx.buildConstraintViolationWithTemplate(ctx.getDefaultConstraintMessageTemplate())
           .addPropertyNode("confirmPassword").addConstraintViolation();
        return false;
    }
}

A validator with an injected repository only works when Spring creates it (LocalValidatorFactoryBean). If you put @UniqueEmail on an entity, Hibernate also validates the entity before insert, usually with its own validator factory that doesn’t go through Spring, and a constructor that needs arguments breaks. Keep this kind of validator on DTOs.

7. String length: @Size, varchar(255) and text types

Key idea: Hibernate creates a varchar(255) column for a String by default. The @Size limit on the form must match the column length, or a long string passes validation and fails in the database as a 500.

  • For a product description of a few thousand characters, the course uses @Column(columnDefinition = "MEDIUMTEXT"). It works on MySQL but ties the code to MySQL (H2 in tests and PostgreSQL have no MEDIUMTEXT).
  • More portable: @Column(length = 10_000) and let Hibernate pick the type for the dialect, or @Lob (the lab does this). Better still, let migrations (Flyway) own the schema and have the entity just describe it (ORM and JPA).
  • Put @Size(max = 10_000) with the same number on the form DTO. Keep the number in one constant so you change it in one place.

8. Lab: user CRUD on the admin page

Key idea: a paginated list, an edit page with a form DTO plus an avatar upload, update followed by a redirect with a flash message, delete over POST with CSRF.

Task (paraphrased from the course): an admin page with a user list, user detail, edit (full name, phone, role, avatar) and delete. The course builds each screen in JSP, binds the entity, deletes through a GET link /admin/user/delete/{id}, and updates by loading the entity and copying fields by hand.

Concern Course Lab
Object receiving the form User entity UserForm (no email, no password)
After saving redirect redirect + flash message
Delete GET, or a form with unclear method POST /admin/users/{id}/delete + CSRF
List findAll() Pageable, 10 rows per page
Not found null → 500 NotFoundException → 404 page

The test deleteUserNeedsPostAndAdmin: GET .../delete returns 405, POST without CSRF returns 403, POST with CSRF redirects to /admin/users and the user is gone. The test checkoutFormValidated shows a record (CheckoutForm) works as a form DTO too: a missing receiver name and a bad phone number re-render cart/checkout with errors on exactly those fields.

Solution: AdminUserController
@Controller
@RequestMapping("/admin/users")
public class AdminUserController {
    private final UserRepository users; private final FileStorageService storage;
    public AdminUserController(UserRepository users, FileStorageService storage) {
        this.users = users; this.storage = storage;
    }

    @GetMapping
    String list(@PageableDefault(size = 10, sort = "id") Pageable pageable, Model model) {
        model.addAttribute("page", users.findAll(pageable));
        return "admin/users/list";
    }

    @GetMapping("/{id}/edit")
    String edit(@PathVariable Long id, Model model) {
        AppUser u = find(id);
        UserForm f = new UserForm();
        f.setFullName(u.getFullName()); f.setPhone(u.getPhone()); f.setRole(u.getRole());
        model.addAttribute("form", f); model.addAttribute("user", u);
        return "admin/users/edit";
    }

    @PostMapping("/{id}")
    String update(@PathVariable Long id, @Valid @ModelAttribute("form") UserForm form, BindingResult result,
                  @RequestParam(name = "avatar", required = false) MultipartFile avatar,
                  Model model, RedirectAttributes ra) {
        AppUser u = find(id);
        if (result.hasErrors()) { model.addAttribute("user", u); return "admin/users/edit"; }
        u.setFullName(form.getFullName()); u.setPhone(form.getPhone()); u.setRole(form.getRole());
        if (avatar != null && !avatar.isEmpty()) u.setAvatar(storage.store(avatar, "avatar"));
        users.save(u);
        ra.addFlashAttribute("message", "Saved");
        return "redirect:/admin/users";
    }

    @PostMapping("/{id}/delete")
    String delete(@PathVariable Long id, RedirectAttributes ra) {
        users.deleteById(id);
        ra.addFlashAttribute("message", "Deleted");
        return "redirect:/admin/users";
    }

    private AppUser find(Long id) {
        return users.findById(id).orElseThrow(() -> new NotFoundException("user " + id));
    }
}

The delete button in the list is a tiny form; th:action inserts the CSRF token:

<form th:action="@{/admin/users/{id}/delete(id=${u.id})}" method="post"
      onsubmit="return confirm('Delete this user?')"><button>Delete</button></form>

The avatar upload in this form is explained in part 6.

PRG (Post/Redirect/Get): after a successful POST, return redirect: so the browser GETs the next page. Pressing F5 then reloads that GET, not the form submission. A flash attribute is data that survives exactly one redirect: Spring keeps it in the session, puts it into the next request’s model, and removes it.

What a senior would add: move the update logic into a @Transactional service (the controller only reads the form and picks a view); stop an admin from demoting themselves or deleting the last admin; soft delete instead of hard delete once a user has orders (deleting old data safely); remove the old avatar file after commit.

What ran: the tests mentioned above (23/23 in ShopTests), plus three separate experiments on BindingResult order, typeMismatch errors and setAllowedFields with constructor binding, on Spring Boot 3.5.9, JDK 21, H2. Not run: the JSP version and messages.properties.

Remember

  • Can you walk through the steps from a name=value string to a validated object, and tell a binding error from a validation error?
  • Can you explain why a form DTO is safer than the entity plus setAllowedFields?
  • Do you know where BindingResult must go and what happens without it?
  • Can you write a class-level validator that attaches its error to one specific field?
  • Do you know why you still need a unique constraint despite @UniqueEmail, and why you redirect after a POST?

Interview questions

Junior

How do Bean Validation and Hibernate Validator differ?

Bean Validation (Jakarta Validation) is the spec with the annotations and API; Hibernate Validator is its reference implementation.

Your code imports jakarta.validation.*; at runtime Hibernate Validator does the checking. In Spring Boot, spring-boot-starter-validation brings it in with a managed version.

What’s the difference between @NotNull, @NotEmpty and @NotBlank?

@NotNull only rejects null; @NotEmpty also rejects empty strings or collections; @NotBlank also rejects whitespace-only strings.

Typed-in text uses @NotBlank. Note that @Size, @Pattern and @Email treat null as valid, so they’re usually combined with a “not” constraint.

Why redirect after a successful form submission instead of returning a view?

So that F5 doesn’t resend the POST (two orders, two users); that’s the Post/Redirect/Get pattern.

The “saved” message travels as a flash attribute that lives for one redirect. On validation errors it’s the opposite: return the view directly to keep the input and errors.

Mid

What happens if you drop the BindingResult from a handler with @Valid @ModelAttribute?

The handler doesn’t run; Spring throws MethodArgumentNotValidException (a kind of BindException) and returns 400 by default.

BindingResult has to come right after the parameter it belongs to. With it, the controller decides: re-render the form with errors. In REST you usually let the exception escape and a @ControllerAdvice turns it into a JSON error.

What is mass assignment and how do you prevent it in Spring MVC?

It’s when the app binds every request parameter onto an object and saves it, so a client can change fields that aren’t on the form, like role or id; prevent it with a form DTO holding only the allowed fields.

@InitBinder with setAllowedFields is a secondary layer: in my test it didn’t block parameters passed through constructor binding (Spring 6.1+). Copy from DTO to entity in explicit code and check permissions in the service.

How do you write a validator that checks two fields match and shows the error under the right input?

Write a class-level constraint (@Target(TYPE)); in isValid, disable the default violation and build a new one with addPropertyNode("confirmPassword").

Without the property node the error is global and can only be shown at the top of the form. A field-level validator can’t do this because it only sees one value.

How do @Valid and @Validated differ?

@Valid is from the spec and validates the object, cascading into nested objects; Spring’s @Validated also takes validation groups, and on a class it enables method validation.

Group example: creating a user requires a password, editing doesn’t. Many teams avoid groups because they’re hard to read, and use two separate DTOs for create and update instead.

Senior

You already have a validator that checks for duplicate emails. Do you still need a unique constraint?

Yes. The validator reads before it writes, so two concurrent requests both see “not taken” and both insert; only a unique constraint in the database stops that.

Catch DataIntegrityViolationException (or check the constraint name) and turn it into a field error. The validator is still useful for the normal case because its message shows up alongside the other errors. Normalise emails to lower case before comparing in both layers.

Review this: @PostMapping update(@ModelAttribute User user) { repo.save(user); }. What do you say?

Three problems: mass assignment (the client changes role, id), save is a merge so columns not on the form become null, and there’s no validation or permission check.

Fix: a UserForm with @Valid + BindingResult, the id from the path, findById and field-by-field copying inside a @Transactional service, a check that the caller may edit that user, then a redirect with a flash message.

Useful phrases for interviews

  • “Data binding turns request parameters into a typed form object; a type mismatch is a binding error, not a validation error.”
  • “Binding the entity directly opens the door to mass assignment, so each screen gets its own form object.”
  • “In my test, setAllowedFields didn’t stop constructor binding, so I don’t rely on it as the main defence.”
  • “Hibernate Validator is the reference implementation of Bean Validation, and the Boot starter manages its version.”
  • “BindingResult has to follow the validated parameter, otherwise Spring throws and returns a 400.”
  • “Without a property node, a class-level constraint shows up as a global error.”
  • “The validator gives a friendly message, but only the unique constraint is safe under concurrency.”
  • “save() is effectively an upsert: persist when new, merge otherwise, and merge copies every field.”
  • “Post/Redirect/Get stops the browser from resubmitting the form on refresh, and the message travels as a flash attribute.”

Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.