Skip to lesson

Validating path and query parameters

A shop URL like /api/v1/products/0 or ?size=100000 is input too. Left unchecked, it gives a confusing 404 or makes the server send a whole table to one client.

Constraints directly on parameters: @Positive id, @Max(100) size

A parameter constraint is a constraint annotation written on a controller method parameter instead of on a field, such as @PathVariable @Positive long id or @RequestParam @Min(1) @Max(100) int size. The same annotations and messages as on records work.

Ids and page sizes arrive in the URL. Here the rules sit directly on the parameters, and Spring MVC checks them before the controller method runs. The example shows the controller and four requests.

Example 1 · src/main/java/com/shoplite/lab/product/ProductQueryController.java

Runs in: the validation-lab practice project (Spring Boot 4.1)

ProductQueryController.javaJava
package com.shoplite.lab.product;
import java.math.BigDecimal;
import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.Positive;import jakarta.validation.constraints.PositiveOrZero;
import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/api/v1/products")public class ProductQueryController {
    private final ProductService productService;
    public ProductQueryController(ProductService productService) {        this.productService = productService;    }
    @GetMapping("/{id}")    public ResponseEntity<ProductResponse> getById(            @PathVariable @Positive(message = "must be a positive id") long id) {        return ResponseEntity.of(productService.findById(id));    }
    @GetMapping    public PageResponse<ProductResponse> list(            @RequestParam(required = false)            @DecimalMin(value = "0.00", message = "must be 0 or more") BigDecimal minPrice,            @RequestParam(defaultValue = "0")            @PositiveOrZero(message = "must be 0 or more") int page,            @RequestParam(defaultValue = "20")            @Min(value = 1, message = "must be between 1 and 100")            @Max(value = 100, message = "must be between 1 and 100") int size) {        long total = productService.search(minPrice, null).count();        return PageResponse.of(productService.page(minPrice, null, page, size), page, size, total);    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/3
HTTP/1.1 200
Content-Type: application/json

{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true}

$ curl -i http://localhost:8080/api/v1/products/0
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:59:19.014Z","status":400,"error":"Bad Request","path":"/api/v1/products/0"}

$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404

$ curl -i "http://localhost:8080/api/v1/products?minPrice=40000&size=2"
HTTP/1.1 200
Content-Type: application/json

{"content":[{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true},{"id":4,"sku":"LAP-IPS3","name":"Lenovo IdeaPad Slim 3","categoryId":3,"categoryName":"Laptops","price":42990.00,"stock":12,"isActive":true}],"page":0,"size":2,"totalElements":3,"totalPages":2}

$ curl -i "http://localhost:8080/api/v1/products?size=500&page=-1"
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:59:20.624Z","status":400,"error":"Bad Request","path":"/api/v1/products"}

What this code does

  • No @Validated on the class: the constraints on id, page and size are checked by Spring MVC's built-in method validation. /products/0 and ?size=500&page=-1 get 400 without reaching the service.
  • /products/99 passes validation (99 is positive) and gets 404 from ResponseEntity.of, because no such product exists. Validation answers "is this a possible id?", the service answers "does it exist?".
  • minPrice is optional (required = false), and page and size have defaults, so ?minPrice=40000&size=2 gives the first page of 2 with the real totals.

Without parameter constraints, /api/v1/products/0 or ?size=100000 reach the service. An id of 0 can never exist, so the client gets a confusing 404, and a page size of 100000 makes the server load and send the whole table, a cheap way for one client to slow down the app for everyone.

The ShopLite contract is exact about lists: page must be 0 or more and size must be 1 to 100, and a bad value is a 400, "never silently clamped". Silently changing 500 to 100 would hide the client's mistake.

Built-in method validation and HandlerMethodValidationException

HandlerMethodValidationException is the exception Spring MVC 6.1+ throws when a controller parameter breaks its constraint. Built-in method validation checks all constrained parameters of the call, and the exception becomes a 400.

A bad id now returns 400 without any extra setup. The command below shows the short default body; the example after it shows what the exception holds, with development settings.

Example 2 · application.properties with include-binding-errors (development only)

Runs in: the validation-lab practice project (Spring Boot 4.1)

Terminal
curl -i http://localhost:8080/api/v1/products/0curl -i "http://localhost:8080/api/v1/products?size=500&page=-1"
Sample output
$ curl -i http://localhost:8080/api/v1/products/0
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:00:03.039Z","status":400,"error":"Bad Request","message":"Validation failed for method='public org.springframework.http.ResponseEntity com.shoplite.lab.product.ProductQueryController.getById(long)'. Error count: 1","errors":[{"arguments":[{"arguments":null,"code":"id","codes":["productQueryController#getById.id","id"],"defaultMessage":"id"}],"codes":["Positive.productQueryController#getById.id","Positive.id","Positive.long","Positive"],"defaultMessage":"must be a positive id"}],"path":"/api/v1/products/0"}

$ curl -i "http://localhost:8080/api/v1/products?size=500&page=-1"
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:00:04.296Z","status":400,"error":"Bad Request","message":"Validation failed for method='public com.shoplite.lab.product.PageResponse com.shoplite.lab.product.ProductQueryController.list(java.math.BigDecimal,int,int)'. Error count: 2","errors":[{"arguments":[{"arguments":null,"code":"page","codes":["productQueryController#list.page","page"],"defaultMessage":"page"}],"codes":["PositiveOrZero.productQueryController#list.page","PositiveOrZero.page","PositiveOrZero.int","PositiveOrZero"],"defaultMessage":"must be 0 or more"},{"arguments":[{"arguments":null,"code":"size","codes":["productQueryController#list.size","size"],"defaultMessage":"size"},100],"codes":["Max.productQueryController#list.size","Max.size","Max.int","Max"],"defaultMessage":"must be between 1 and 100"}],"path":"/api/v1/products"}

What this code does

  • The lab ran with spring.web.error.include-binding-errors=always and spring.web.error.include-message=always (the development-only settings from the @Valid lesson), so the body shows what HandlerMethodValidationException holds.
  • The message says Validation failed for method=...getById(long): parameter errors, one per parameter (page, size), each with your message. Note that it leaks the class and method name, another reason to keep these settings off in production.

Method validation checks the parameters of a method call against their constraints. Spring MVC does it by itself for controller methods (Spring Framework 7 in Boot 4.1); when any parameter has a constraint, it validates all of them.

The exception differs from MethodArgumentNotValidException: it reports parameter errors for id, page or size, not field errors of one object. By default Spring does not even log it, so a 400 with no WARN line usually means a parameter rule failed. If a method has a constrained parameter and also @Valid @RequestBody, a bad body is reported inside HandlerMethodValidationException too, so a global error handler should handle both exceptions.

Predict the output

Which exception?

Read the method and the request, then pick the exception Spring throws.

Round 1 of 3

@GetMapping("/{id}")
ProductResponse get(@PathVariable @Positive long id)
GET /api/v1/products/0

The older @Validated-on-the-class style and ConstraintViolationException

ConstraintViolationException is the Bean Validation exception thrown by the older @Validated-on-the-class style, where Spring wraps the controller in a proxy. Spring MVC does not know it, so it becomes a 500 unless you handle it.

Many older tutorials put @Validated on the controller class. The example adds that one annotation to the same controller and repeats the bad requests.

Example 3 · ProductQueryController.java with @Validated on the class

Runs in: the validation-lab practice project (Spring Boot 4.1)

ProductQueryController.javaJava
package com.shoplite.lab.product;
import java.math.BigDecimal;
import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.Positive;import jakarta.validation.constraints.PositiveOrZero;
import org.springframework.http.ResponseEntity;import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;
@Validated // the older style: validation through a Spring proxy@RestController@RequestMapping("/api/v1/products")public class ProductQueryController {
    private final ProductService productService;
    public ProductQueryController(ProductService productService) {        this.productService = productService;    }
    @GetMapping("/{id}")    public ResponseEntity<ProductResponse> getById(            @PathVariable @Positive(message = "must be a positive id") long id) {        return ResponseEntity.of(productService.findById(id));    }
    @GetMapping    public PageResponse<ProductResponse> list(            @RequestParam(required = false)            @DecimalMin(value = "0.00", message = "must be 0 or more") BigDecimal minPrice,            @RequestParam(defaultValue = "0")            @PositiveOrZero(message = "must be 0 or more") int page,            @RequestParam(defaultValue = "20")            @Min(value = 1, message = "must be between 1 and 100")            @Max(value = 100, message = "must be between 1 and 100") int size) {        long total = productService.search(minPrice, null).count();        return PageResponse.of(productService.page(minPrice, null, page, size), page, size, total);    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/0
HTTP/1.1 500
Content-Type: application/json

{"timestamp":"2026-10-16T05:04:17.863Z","status":500,"error":"Internal Server Error","path":"/api/v1/products/0"}

$ curl -i "http://localhost:8080/api/v1/products?size=500"
HTTP/1.1 500
Content-Type: application/json

{"timestamp":"2026-10-16T05:04:18.141Z","status":500,"error":"Internal Server Error","path":"/api/v1/products"}

Server console (shortened):
2026-10-16T10:34:17.836+05:30 ERROR 5880 --- [validation-lab] [io-18613-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: jakarta.validation.ConstraintViolationException: getById.id: must be a positive id] with root cause
jakarta.validation.ConstraintViolationException: getById.id: must be a positive id

What this code does

  • One extra annotation changes the result from 400 to 500: the proxy throws ConstraintViolationException, which Spring MVC does not turn into a client error.
  • The log shows an ERROR with a full stack trace for a client typo, which also makes real server errors harder to spot. Remove @Validated from the controller to get the 400 back.

Before Spring 6.1, parameter constraints worked only with @Validated, which makes Spring wrap the controller in a proxy (a generated object in front of yours) that validates each call. Without your own handler the client gets a 500 Internal Server Error for a simple bad id: the server blames itself for the client's mistake.

On Spring Boot 3.2+ and 4.x, remove @Validated from controllers and let the built-in method validation give a proper 400. @Validated still has uses: on service classes for method validation there, and with groups on a single parameter, as the custom validator lesson shows.

Validating a page and size pair

A parameter object is a record whose components are bound from query parameters by name, such as ProductSearchParams(minPrice, maxPrice, page, size). With @Valid on it, its constraints are checked like a body.

Paging and search filters belong together. One record can hold page, size and the filters, with defaults and a rule that involves two of them. The example builds ProductSearchParams.

Example 4 · ProductSearchParams.java, ProductQueryController.java

Runs in: the validation-lab practice project (Spring Boot 4.1)

ProductSearchParams.javaJava
// src/main/java/com/shoplite/lab/product/ProductSearchParams.javapackage com.shoplite.lab.product;
import java.math.BigDecimal;
import jakarta.validation.constraints.AssertTrue;import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.PositiveOrZero;
public record ProductSearchParams(        @DecimalMin(value = "0.00", message = "must be 0 or more") BigDecimal minPrice,        @DecimalMin(value = "0.00", message = "must be 0 or more") BigDecimal maxPrice,        @PositiveOrZero(message = "must be 0 or more") Integer page,        @Min(value = 1, message = "must be between 1 and 100")        @Max(value = 100, message = "must be between 1 and 100") Integer size) {
    public ProductSearchParams {        page = page == null ? 0 : page;     // defaults when the client leaves them out        size = size == null ? 20 : size;    }
    @AssertTrue(message = "minPrice must not be greater than maxPrice")    public boolean isPriceRangeValid() {        return minPrice == null || maxPrice == null || minPrice.compareTo(maxPrice) <= 0;    }}
// src/main/java/com/shoplite/lab/product/ProductQueryController.javapackage com.shoplite.lab.product;
import jakarta.validation.Valid;import jakarta.validation.constraints.Positive;
import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/api/v1/products")public class ProductQueryController {
    private final ProductService productService;
    public ProductQueryController(ProductService productService) {        this.productService = productService;    }
    @GetMapping("/{id}")    public ResponseEntity<ProductResponse> getById(            @PathVariable @Positive(message = "must be a positive id") long id) {        return ResponseEntity.of(productService.findById(id));    }
    @GetMapping    public PageResponse<ProductResponse> list(@Valid ProductSearchParams params) {        long total = productService.search(params.minPrice(), params.maxPrice()).count();        return PageResponse.of(                productService.page(params.minPrice(), params.maxPrice(), params.page(), params.size()),                params.page(), params.size(), total);    }}
Sample output
$ curl -i "http://localhost:8080/api/v1/products?minPrice=1000&maxPrice=2000&size=2"
HTTP/1.1 200
Content-Type: application/json

{"content":[{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Accessories","price":1299.00,"stock":120,"isActive":true},{"id":14,"sku":"HK-COOK3L","name":"Prestige Pressure Cooker 3L","categoryId":7,"categoryName":"Home & Kitchen","price":1899.00,"stock":15,"isActive":true}],"page":0,"size":2,"totalElements":2,"totalPages":1}

$ curl -i "http://localhost:8080/api/v1/products?minPrice=5000&maxPrice=1000&size=0"
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:05:00.810Z","status":400,"error":"Bad Request","path":"/api/v1/products"}

$ curl -i "http://localhost:8080/api/v1/products?page=-1"
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:05:01.621Z","status":400,"error":"Bad Request","path":"/api/v1/products"}

Server console (shortened):
2026-10-16T10:35:00.767+05:30  WARN 3768 --- [validation-lab] [io-18613-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed ... [Field error in object 'productSearchParams' on field 'priceRangeValid': rejected value [false]; ... default message [priceRangeValid]] [Field error in object 'productSearchParams' on field 'size': rejected value [0]; ... default message [minPrice must not be greater than maxPrice]]

What this code does

  • list(@Valid ProductSearchParams params) binds minPrice, maxPrice, page and size by name. No annotation is needed for binding; @Valid turns on the checks.
  • The compact constructor fills in page 0 and size 20 when they are missing, so defaults live next to the rules.
  • minPrice=5000&maxPrice=1000&size=0 breaks two rules, reported as field errors priceRangeValid and size in one MethodArgumentNotValidException.

GET /api/v1/products?minPrice=1000&maxPrice=2000&size=2 fills the record by name, and failures come as MethodArgumentNotValidException. The compact constructor keeps the defaults (page 0, size 20) next to rules that involve two parameters, such as "minPrice must not be greater than maxPrice".

@AssertTrue on a boolean isXxx() method is the quick way to write such a rule. Its error is reported on a made-up property, here priceRangeValid; the custom validator lesson shows a class-level constraint that reports it on minPrice instead.

Find the bug

Find the missing rule

Each endpoint lets bad input through. Click the line to blame.

A search with size=0 and minPrice above maxPrice gets 200.

Round 1 of 3

Type errors (abc for a number) vs constraint errors (-5)

MethodArgumentTypeMismatchException is thrown when text from the URL cannot be converted to the parameter type, such as abc for a long. It happens before validation; a number that converts but breaks a rule is a constraint error.

/products/abc and /products/-5 both fail, for different reasons. The example sends bad values to a path variable, a query parameter and a parameter record.

Example 5 · Type errors in a path variable, a query parameter and a parameter record

Runs in: the validation-lab practice project (Spring Boot 4.1)

Terminal
curl -i http://localhost:8080/api/v1/products/abccurl -i "http://localhost:8080/api/v1/products?size=abc"
Sample output
$ curl -i http://localhost:8080/api/v1/products/abc
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:59:20.186Z","status":400,"error":"Bad Request","path":"/api/v1/products/abc"}

$ curl -i "http://localhost:8080/api/v1/products?size=abc"
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:59:20.977Z","status":400,"error":"Bad Request","path":"/api/v1/products"}

Server console (shortened), Example 1's controller:
2026-10-16T11:29:20.184+05:30  WARN 27572 --- [validation-lab] [io-18611-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Method parameter 'id': Failed to convert value of type 'java.lang.String' to required type 'long'; For input string: "abc"]
2026-10-16T11:29:20.973+05:30  WARN 27572 --- [validation-lab] [io-18611-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Method parameter 'size': Failed to convert value of type 'java.lang.String' to required type 'int'; For input string: "abc"]

Server console (shortened), Example 4's record:
2026-10-16T10:35:02.291+05:30  WARN 3768 --- [validation-lab] [o-18613-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed ... [Field error in object 'productSearchParams' on field 'size': rejected value [abc]; ... default message [size]]

What this code does

  • With plain parameters, abc fails before validation as MethodArgumentTypeMismatchException ("Failed to convert value of type String to required type long").
  • With the parameter record, the same size=abc becomes a field error with code typeMismatch inside MethodArgumentNotValidException, so it can be listed together with the other field errors.
  • All are 400s, but each comes from a different exception; one global handler should turn every one of them into the same error shape.

A type error happens before validation: abc cannot become a long. A constraint error happens after conversion: -5 is a fine number that breaks @Positive, giving HandlerMethodValidationException. Both are 400, but they need different messages: "must be a number" versus "must be a positive id". In a parameter record, a type error becomes a typeMismatch field error inside MethodArgumentNotValidException.

The Exception handling module maps all of these exceptions, plus unreadable JSON, to one validation-failed or malformed-request shape, so clients see the same format whatever went wrong.

Next step

Check your understanding

12 quick questions