Mastering Parameter Validation in Spring: From Controllers to Custom Annotations

This article explains how to perform parameter validation in Spring applications, covering the distinction between controller‑level and service‑level checks, using Hibernate Validator and commons‑lang3, and creating custom validation annotations for complex scenarios.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Mastering Parameter Validation in Spring: From Controllers to Custom Annotations

Recently during a code review a colleague pointed out that parameter validation should be placed in the controller layer. This article shows how to implement parameter validation properly in Spring.

Controller Layer vs Service Layer

Generally, validation unrelated to business logic belongs in the controller, while business‑related validation belongs in the service layer.

Common Validation Tools

Using Hibernate Validator

Dependency:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.3.1.Final</version>
</dependency>

Common annotations are illustrated in the following image:

Usage: combine @Validated or @Valid on controller methods. The difference is minor; @Validated adds grouping and ordering capabilities.

Annotations are placed on entity fields.

Define an entity:

public class DataSetSaveVO {
    @NotBlank(message = "user uuid is empty")
    @Pattern(regexp = "^[a-z0-9]+$", message = "user names can only be alphabetic and numeric")
    @Length(max = 48, message = "user uuid length over 48 byte")
    private String userUuid;

    @Pattern(regexp = "^[A-Za-z0-9]+$", message = "data set names can only be letters and Numbers")
    @Length(max = 48, message = "file name too long")
    @NotBlank(message = "file name is empty")
    private String name;

    @Length(max = 256, message = "data set description length over 256 byte")
    @NotBlank(message = "data set description is null")
    private String description;
}

The message attribute defines the exception message when validation fails.

Controller method example:

@PostMapping
public ResponseVO createDataSet(@Valid @RequestBody DataSetSaveVO dataSetVO) {
    return ResponseUtil.success(dataSetService.saveDataSet(dataSetVO));
}

Note: add @Valid or @Validated next to the entity parameter.

Using commons‑lang3

Dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

Common utility methods are illustrated in the following image:

Test code demonstrating StringUtils and CollectionUtils methods:

//StringUtils.isEmpty
System.out.println(StringUtils.isEmpty(""));  // true
System.out.println(StringUtils.isEmpty("  ")); // false
//StringUtils.isNotEmpty
System.out.println(StringUtils.isNotEmpty("")); // false
//StringUtils.isBlank
System.out.println(StringUtils.isBlank(""));   // true
System.out.println(StringUtils.isBlank(" "));  // true
//StringUtils.isNotBlank
System.out.println(StringUtils.isNotBlank(" ")); // false

List<Integer> emptyList = new ArrayList<>();
List<Integer> nullList = null;
List<Integer> notEmptyList = new ArrayList<>();
notEmptyList.add(1);

//CollectionUtils.isEmpty
System.out.println(CollectionUtils.isEmpty(emptyList));   // true
System.out.println(CollectionUtils.isEmpty(nullList));    // true
System.out.println(CollectionUtils.isEmpty(notEmptyList));// false

//CollectionUtils.isNotEmpty
System.out.println(CollectionUtils.isNotEmpty(emptyList));   // false
System.out.println(CollectionUtils.isNotEmpty(nullList));    // false
System.out.println(CollectionUtils.isNotEmpty(notEmptyList));// true

Custom Annotations

If built‑in validators cannot meet the requirements, you can create custom annotations. Refer to the author's previous article on Spring custom annotations for guidance.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentspringvalidationHibernate Validator
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.