The labs on this site need JavaScript to run. The same content is written out below.
Learn › Spring › Web MVC
Request mapping and parameter binding
How does a value sent in a request become a method parameter?
Why it exists — When you receive requests with servlets alone, you have to decide by hand which code to call for each address, and in every method you have to write the code that converts the text taken out with request.getParameter into a number and the handling for when the value is missing. Request mapping and parameter binding in Spring MVC replace this with a few annotations, so that from the method declaration alone you can tell which request it receives and which values it uses as which types.
Where it's used today — The controllers of an API built with Spring MVC receive values with these annotations. A common division is: a number that points to a target, such as /orders/{id}, with @PathVariable; optional conditions such as a search word or a page number, with @RequestParam; and a JSON body with several fields, with @RequestBody. On a page that submits an HTML form, @ModelAttribute receives several values into one object.
Request mapping decides which controller method receives a request, based on its URL and HTTP method, and parameter binding puts the values carried by the request into the parameters of that method. An HTTP request can carry a value in several places: the path of the URL, the query string after the ?, and the body. The annotation on a parameter of a controller method decides "which of these places the value is taken from". If the place that carries the value and the place the value is taken from do not match, the value does not come in.
Checked against real execution · Checked by sending requests for 48 combinations to a Spring Boot 4.1.1 server
Concepts in this lab
- @RequestParam and @PathVariable
- These are annotations that let a controller method receive a single value carried in the request as a method parameter. @RequestParam takes the value from the request parameters (the name=value pairs of the query string and of form data in the body), and @PathVariable takes it from a {name} placeholder declared in the path of the URL, as in /orders/{id}. The value taken is text, so Spring converts it to the type of the parameter (int, for example), and when text that cannot be converted arrives, Spring does not run the controller and responds with 400. By default, @RequestParam gives 400 when the value is missing; with required = false, null is passed in instead, and with defaultValue, that value is passed in instead. When you use required = false, declare the parameter with an object type such as Integer, not int, so that it can hold null.
- @ModelAttribute and @RequestBody
- Why it exists — When there are many values, receiving parameters one by one makes the method declaration long, and the declaration has to change whenever a value to receive is added. @ModelAttribute and @RequestBody let you receive several values as one object, so when values increase, you only add a field to that class.
- Where it's used today — It is common to receive a list query with several search conditions with @ModelAttribute, and a create or update request that a frontend or app sends as JSON with @RequestBody. You also attach @Valid to the receiving object to validate the values.
- These are two ways of receiving several values of a request as one object. @ModelAttribute creates the object first and then uses the setters to set the request parameters (query string and form data in the body) whose names match the fields (for a class that takes its values through a constructor, such as a record, the values are passed as constructor arguments when the object is created). @RequestBody passes the whole request body to the message converter that matches the Content-Type, which converts it into an object, and it is mostly used to receive a JSON body. The two look at different places, so a value sent in a JSON body does not come in through @ModelAttribute, and a value sent in the query string does not come in through @RequestBody. @ModelAttribute leaves a field with no value as it is and does not treat it as an error, so a value that is required has to be validated separately.
- Query string and form data
- Where it's used today — Values for which the same result must be viewable again from the address alone, such as a search term, sort order, and page number, go in the query string. Values that must not remain in the address and in access logs, such as a password, or long values, such as the content of a post, go in the body of a POST form.
- The query string is the part of a URL after the ? in which name=value pairs are joined with &, and form data is text of the same shape sent in the request body. When form data is sent, the Content-Type header is set to application/x-www-form-urlencoded. When an HTML form is submitted with GET, the values are carried in the query string, and when it is submitted with POST, they are carried as form data in the body. The servlet container combines the two and provides them as "request parameters", so server code takes the values in the same way without telling which of the two they came from. A JSON body is not included in the request parameters.
- HandlerMethodArgumentResolver
- Where it's used today — Spring Data's Pageable and the parameters of Spring Security's @AuthenticationPrincipal are also filled in by it. When you write one yourself, you implement HandlerMethodArgumentResolver and register it with addArgumentResolvers of WebMvcConfigurer.
- This component takes a value out of the request and builds it so that it can be passed to a parameter of a controller method. Parameters annotated with @RequestParam, @PathVariable, @RequestBody, and so on are filled in through it. If you implement your own, a controller can receive a recurring value, such as the logged-in user's information, directly as a parameter.
- HTTP status codes
- Why it exists — If results were reported only as text in the body, each server would write them differently, and browsers, proxies, and monitoring tools could not tell whether a request succeeded. A status code reports the result as a fixed number, so these tools can do caching, retries, and error counting without being adjusted for each server.
- Where it's used today — It is used to branch handling by the kind of error, such as a frontend that sends the user to the login screen on a 401 and to a "page not found" notice on a 404. In operations, you watch the ratio of 5xx responses and, if it suddenly rises, treat it as an outage and send an alert.
- A three-digit number that shows the result of the server's handling of a request. 2xx means success, 3xx means a move to another location (redirection), 4xx means a problem with the client's request, and 5xx means an error on the server side. Common ones are 200 (success), 201 (created), 400 (bad request), 401 (authentication required), 403 (no permission), 404 (not found), and 500 (server error).
Try these
- Default settings — The controller tries to receive a value sent in a JSON body with @RequestParam. The result is 400.
- The same request with @RequestBody — When you switch to a way that reads the body, the value comes in.
- When no value is sent — By default, @RequestParam requires the value to be present.
- Letters give 400 even with defaultValue — The default value is used only when the value is missing. It does not replace an invalid value.
- Taking the value from the path — The 3 in /orders/3 becomes the @PathVariable parameter.
- An object passes even without the value — @ModelAttribute does not treat a missing value as an error. qty stays 0.
- Form data also works with @RequestParam — Form data in the body is a "request parameter", the same as the query string.
Running with the default settings
- The request arrives: POST /orders. qty is carried in the body as JSON. The Content-Type header tells the format of the body. Wherever a value is carried, everything inside an HTTP request is text.
- @PostMapping("/orders"): Spring uses the HTTP method and the path of the request to find the controller method to run (request mapping). The HTTP method is POST and the path is /orders, so the order method is chosen. This step does not look at the query string or the body.
- @RequestParam int qty: Next, the values carried by the request are put into the parameters of the method (parameter binding). The annotation on the parameter decides where the value is taken from. @RequestParam looks in the "request parameters" for the value named qty. The request parameters are the query string and the form data in the body combined.
- Getting the value: A JSON body is not a request parameter. Even though qty is written inside the body, @RequestParam does not open the body. By default, @RequestParam requires the value to be present, so Spring responds with 400 (MissingServletRequestParameterException). The controller method does not run.
Result of this run
- A value sent in a JSON body cannot be received with @RequestParam, because the place that carries the value (the body) and the place the value is taken from (the request parameters) are different. Receive a JSON body with @RequestBody.
- Each annotation looks at a fixed place. @RequestParam looks at the request parameters (query string and form data), @ModelAttribute looks at those plus the path variables, @PathVariable looks at the path, and @RequestBody looks at the whole body.
Code
// Request sent
// POST /orders
// Content-Type: application/json
//
// {"qty": 3}
@RestController
class OrderController {
@PostMapping("/orders")
String order(@RequestParam int qty) {
return "Quantity " + qty;
}
}
Assumptions of this model
All 48 combinations of the 6 ways of receiving the value and the 8 requests were sent as HTTP requests to a real Spring Boot 4.1.1 server (Spring Framework 7.0.9, embedded Tomcat 11), and the status code, whether the controller ran, the value the controller received, and the name of the exception Spring threw were confirmed to match the screen. The names of the exceptions depend on the Spring version (NoResourceFoundException when no URL matches and MethodArgumentNotValidException for a failed @ModelAttribute conversion are as of this version). The body of an error response varies with the version and the configuration, so it was not treated as a result. The lab is simplified to a controller with one method and one parameter, and the mapping annotation shown is whichever of @GetMapping and @PostMapping matches the HTTP method of the request (the 405 for an HTTP method that does not match is in the "Servlets" lab). OrderForm is a class with a default constructor and a setter. For an object that receives its values through a constructor, such as a record, the behavior when the value is missing can be different, and that was not verified. Finding the value by the parameter name without writing the name separately, as in @RequestParam int qty, is the behavior when the code is compiled with the -parameters option, and the check was done that way too. Four cases that are not on the screen were also checked on the same server. When an empty value is sent, as in ?qty=, @RequestParam int gives 400, required = false gives null, and defaultValue gives the default value. When required = false is used with the type int and no value is sent, null cannot be stored and the result is 500. When a BindingResult parameter is placed immediately after the @ModelAttribute parameter, the controller runs even if the conversion fails. When the body is {}, the qty received with @RequestBody is 0. Validation that checks the range of a value (@Valid) is not covered in this lab and is covered separately in the next lab, "Validation".
Previous lab: Spring MVC request flow · Next lab: Validation