Labs ICT
โญ Pro Login

Request Parameters

Reading query parameters and form data.

The @RequestParam Annotation

Request parameters are the key-value pairs that appear after the question mark in a URL โ€” like /search?q=spring&sort=name. The @RequestParam annotation lets you capture these values in your controller methods.

Spring handles the type conversion automatically. If your parameter is a Long, Spring converts the string value. If it's an int, same deal. You just declare the type and Spring does the rest.

Query Parameters in Action

Use @RequestParam to bind query parameters to method parameters. The parameter name in the annotation must match the query parameter name in the URL.

@GetMapping("/products")
public List<Product> search(
        @RequestParam String keyword,
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "10") int size) {
    return productService.search(keyword, page, size);
}

A request to /products?q=laptop&page=2&size=20 populates all three parameters. If page or size are missing, the defaults kick in.

Default Values

Not every parameter should be required. Use the defaultValue attribute to provide fallback values. This way, your API works even when clients don't send all parameters.

Default values also simplify your code โ€” you don't need to write null checks everywhere. The parameter always has a value, whether the client provided one or not.

Required vs Optional Parameters

By default, @RequestParam expects the parameter to be present. If it's missing and there's no default value, Spring throws a MissingServletRequestParameterException.

Set required = false to make a parameter optional. When it's missing, the parameter receives null. Use this for filters, search criteria, or any parameter that enhances the response but isn't essential.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is @RequestParam used for?