Question
What is the difference between @RequestParam and @PathVariable in Spring, particularly regarding the handling of special characters?
@GetMapping("/example?name={name}") public ResponseEntity<String> handleRequest(@RequestParam String name) { return ResponseEntity.ok(name); }
Answer
In Spring, both @RequestParam and @PathVariable are used to extract values from the URL, but they serve different purposes and behave differently with special characters. Here’s a detailed breakdown of each annotation.
@GetMapping("/example/{input}") public ResponseEntity<String> handlePathVariable(@PathVariable String input) { return ResponseEntity.ok(input); }
Causes
- @RequestParam is used to extract query parameters from the URL, such as those following a '?' in the request string.
- @PathVariable is used to extract template variables from the URI path, which are defined within the URL mapping.
Solutions
- When handling special characters, @RequestParam typically decodes them (e.g., '+' becomes ' ' for spaces). This is because query parameters are URL encoded, and the framework handles this decoding automatically.
- @PathVariable does not perform such decoding; a '+' remains a '+' unless explicitly handled in the code.
Common Mistakes
Mistake: Assuming that @PathVariable will decode special characters similarly to @RequestParam.
Solution: Always verify how the URL template is defined and how special characters are passed in the URL.
Mistake: Using @RequestParam for URL path variables instead of @PathVariable.
Solution: Use @PathVariable when your intent is to extract values from the URI path.
Helpers
- Spring @RequestParam
- Spring @PathVariable
- handling special characters in Spring
- RequestParam vs PathVariable
- Spring Framework annotations