Spring @PathVariable and @RequestParam (+ Examples)
Spring @PathVariable and @RequestParam (+ Examples)
Lokesh Gupta
Spring MVC
Spring Annotations, Spring WebMVC
This article explores the difference between @PathVariable and @RequestParam annotations
in Spring, as well as compares these to their equivalents in the Java/Jakarta EE provided
@PathParam and @QueryParam annotations. Additionally, we will look into the encoding of
parameter values and how to make the parameters optional to enhance flexibility.
Generally, a URL can contain two types of request parameters i.e. path parameters and
query parameters. Here’s an example of a URL that includes both:
http://localhost:8080/users/{id}/accounts?type=current&status=active
Spring supports accepting path variables and query parameters using easy-to-use
annotations.
g("/users/{id}/accounts")
t<Accounts> getAccounts(@PathVariable String id, @RequestParam String type, @RequestPar
Consider the following request, and see how the request parts are populated into method
arguments of the handler method.
The @PathVariable extracts the URI template variables from the request URL. For
example, in the URI template “/users/{id}/accounts”, the value of id is mapped to a
value 101. In runtime, the method parameter id is initialized with the value 101 for this
reason.
The @RequestParam extracts the query parameters, form parameters, and even files
from the request. In our example, we have two query parameters: type and status. Any
value passed in these parameters will be used to initialize the method arguments type
and status.
This way, we can pass both dynamic values in the URL path and additional parameters as
query parameters to provide more information to the server when making a request.
If the same query parameter is passed multiple times in a URL then the first value
(lexically) of the parameter is used.
In the previous example, we didn’t define the name of the path variable since the names of
the method parameter and the path variable were the same. However, if the path variable
name is different from the URI template variable, we must provide the name in the
@PathVariable annotation:
In the following handler method, we are mapping the id path variable to userId method
parameter.
@GetMapping("/user/{id}")
public String getUserById(@PathVariable(name = "id") String userId) {
//...
}
Similarly, @RequestParam name also can be configured using the name attribute. In the
following example, any query parameter sent with ‘?name=‘ will be populated into username
variable.
@GetMapping("/users")
public String getUsers(@RequestParam(name = "name") String username) {
//...
}
In such cases, when API has more than one path variable and request parameters, we can
use a Map to collect the parameters and values instead of naming each parameter
individually.
@GetMapping("/users/country/{countryCode}/state/{stateCode}")
public String getUsers(@PathVariable Map<String, String> locationMap, @RequestParam
//...
}
In the following example, passing both query parameters, type and status, is optional.
@GetMapping("/user/{id}")
public String getAccounts(@PathVariable String id,
@RequestParam(required = false) String type,
@RequestParam(required = false) String status) {
//...
}
@GetMapping("/user/{id}")
public String getAccounts(@PathVariable Optional<String> String id,
@RequestParam Optional<String> type,
@RequestParam Optional<String> status) {
Spring framework lacks a built-in capability to handle default values for method parameters
annotated with @PathVariable. Nevertheless, the use of java.util.Optional enables us to
ascertain whether the path variable holds a value or not. In case it turns out to be an empty
value, we have the option to handle the situation by providing a default value, as shown in the
previous section.
@GetMapping("/users")
public String getAllUsers(@RequestParam(value = "pageNo", defaultValue = "0") int pa
@RequestParam(value = "pageSize", defaultValue = "30") int pageSize) {
//...
}
@GetMapping("/user/{id}")
public String getUserById(@PathVariable String Id) {
return "User Id: " + id;
}
The value of @RequestParam parameters are automatically encoded in the URL when sent,
and the controller subsequently decodes it upon receiving.
For example, the controller method and response for URL: http://localhost:8080/users?
name=John%20Doe will be:
@GetMapping("/users")
public String getUsers(@RequestParam String name) {
return "Name: " + name;
}
Here the single space in the name “John Doe” is URL encoded to “%20” while sending the
request to the server.
6. FAQs
Both, @PathParam and @PathVariable, annotations extract values from the URI path of a
request URL. However, they are associated with different frameworks.
@GET
@Path("/user/{id}")
public Response getUserById(@PathParam("id") String id) {
// ...
}
Both, @QueryParam and @RequestParam, binds the value(s) of a HTTP query parameter to a
resource method parameter.
@GET
@Path("/users")
public Response getUsers(@QueryParam("name") String name) {
// Method implementation
}
7. Conclusion
Happy Learning !!
Weekly Newsletter
Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.
Email Address
SUBSCRIBE
Comments
Subscribe
{} [+]
0 COMMENTS
Getting Started
DispatcherServlet
WebMvcConfigurer
ProblemDetail and ErrorResponse
@RequestMapping
Custom Validator
JSR-303 Validation
MessageSourceAware
Interceptor
HandlerInterceptor
File Download
XmlViewResolver
InternalResourceViewResolver
ResourceBundleViewResolver
SimpleMappingExceptionResolver
Handling Dropdown
Interview Questions
Lokesh Gupta
A fun-loving family man, passionate about computers and problem-solving, with over 15
years of experience in Java and related technologies. An avid Sci-Fi movie enthusiast and a
fan of Christopher Nolan and Quentin Tarantino.
Follow on Twitter
Portfolio
PREVIOUS
NEXT
About Us
It also shares the best practices, algorithms & solutions and frequently
asked interview questions.
Tutorial Series
OOP
Regex
Maven
Logging
TypeScript
Python
Meta Links
About Us
Advertise
Contact Us
Privacy Policy
Our Blogs
Follow On:
Table Of Contents