Now we're moving to an important part of working with requests — their parameters. In this lecture we'll walk through how to extract values from the URL (path variables) and how to handle request parameters (request parameters). These two techniques are the foundation for building flexible and practical web apps.
What are request parameters and why you need them
When a user sends a request to the server (for example, to find a specific article or a user profile), data can be sent with the request. That data can be part of the URL or sent as parameters in the query string. Spring MVC gives a simple and powerful way to extract this data using the annotations @PathVariable and @RequestParam.
But why would you need this at all? Well, imagine instead of a generic response like "all articles", you want to show a specific article by its id (for example, /articles/42). Or, say, find products by category with a certain filter (for example, /products?category=books&sort=price-desc). In both cases we need to handle request parameters to give the user the data they asked for.
Handling path variables: the @PathVariable annotation
Let's start with @PathVariable. This annotation is used to pull values straight from the URI (URL). It lets you define dynamic parts of a route.
Usage example
Say you want to show a user's profile by their ID. The URL could look like /users/123. Here 123 is the path variable value.
Code example:
@RestController
@RequestMapping("/users")
public class UserController {
// Handle a request like /users/123
@GetMapping("/{id}")
public String getUserById(@PathVariable("id") Long userId) {
// Here we can use userId to look up the user
return "User with ID: " + userId;
}
}
Key points:
- The
@PathVariableannotation binds a value from the URL to a method variable. - In the route we declare the dynamic part of the path:
{id}. - In the controller method we use the
userIdvariable to handle the request.
For GET /users/123 the server will return: User with ID: 123.
A slightly more complex example
You can use multiple variables in the path:
@RestController
@RequestMapping("/articles")
public class ArticleController {
@GetMapping("/{category}/{id}")
public String getArticleByCategoryAndId(@PathVariable String category, @PathVariable Long id) {
return "Article from category '" + category + "' with ID: " + id;
}
}
Now a request GET /articles/tech/42 will return: Article from category 'tech' with ID: 42.
How parameters get into the request: the @RequestParam annotation
If you need to extract data from the query string, use the @RequestParam annotation. Parameters are passed in the URL after the ? as key=value. For example, /products?category=books.
Usage example
Let's create a method to search for products:
@RestController
@RequestMapping("/products")
public class ProductController {
@GetMapping("/search")
public String searchProducts(@RequestParam String category, @RequestParam(defaultValue = "price-asc") String sort) {
return "Searching products in category: " + category + ", sort: " + sort;
}
}
Now a request GET /products/search?category=electronics&sort=price-desc will return: Searching products in category: electronics, sort: price-desc.
Key points:
- The
@RequestParamannotation extracts values from the query string. - The
categoryfield is required, whilesorthas a default valueprice-asc.
Handling optional parameters
You can make some parameters optional:
@RestController
@RequestMapping("/products")
public class OptionalParamController {
@GetMapping("/filter")
public String filterProducts(@RequestParam(required = false) String category) {
if (category == null) {
return "Please choose a category!";
}
return "Filtering products by category: " + category;
}
}
If the request comes without the category parameter, the app will handle it gracefully and return: Please choose a category!.
Comparing @PathVariable and @RequestParam
| Characteristic | @PathVariable | @RequestParam |
|---|---|---|
| Data source | URL path | Query string |
| Example | /users/123 |
/search?category=books |
| Annotation | @PathVariable("name") |
@RequestParam("name") |
| Required | Usually required | Can be optional |
| Use case | Unique resources (e.g. ID) | Filters, sorting, extra options |
Example: combining @PathVariable and @RequestParam
Let's look at an example that uses both annotations:
@RestController
@RequestMapping("/orders")
public class OrderController {
@GetMapping("/{orderId}")
public String getOrderDetails(@PathVariable Long orderId,
@RequestParam(required = false) String includeDetails) {
if ("true".equals(includeDetails)) {
return "Order details with ID: " + orderId + ". Info: [order details]";
}
return "Order with ID: " + orderId;
}
}
Request GET /orders/99?includeDetails=true will return: Order details with ID: 99. Info: [order details].
Request GET /orders/99 will return: Order with ID: 99.
Common mistakes
Errors when using @PathVariable and @RequestParam usually come from mismatched variable names, missing values, wrong required settings, or incorrect types.
For example:
- If you use a wrong variable name in the route (
/{id}) and in the annotation (@PathVariable("userId")), Spring will throw an exception. - If a request parameter is marked as required but isn't sent by the client, you'll get a
400 Bad Requesterror. - Wrong data type (for example, trying to pass a string where
Longis expected) will lead to anHttpMessageNotReadableException.
How to fix errors
- Use the same names for variables in the route and annotations.
- Remember that for
@RequestParamyou can set a default value viadefaultValue. - Be careful with data types: if a
Longis expected but a string is passed, you'll get an error.
Now you're armed with the knowledge of how to work with request parameters in Spring MVC. This opens up a lot of possibilities for creating flexible routes and handling complex web requests! In the next lectures you'll learn data validation when working with requests and see how Spring MVC helps avoid common mistakes.
GO TO FULL VERSION