“I can’t connect the dots looking forward,” says the gold digger. “I’ll only understand how they fit together looking back at today.” So I have to believe that what is happening now will be connected in the future. Maybe NOW I don’t know if it’s a good idea to write this or a waste of time… But looking back in the future, you’ll know it was all worth it. Because each process becomes you now ~
Looking back, two annotations are usually used for receiving parameter transmission. To distinguish the relationship and difference between them, we still need to find materials, verify by ourselves and consolidate the impression. So the difference between @requestParam and @pathVariable, they can both be used to extract values from request URIs, but they’re a little different.
Query parameters with URL subgrade
- for
@RequestParam
Extract the value from the query string
@GetMapping("/pig")
public String getPigByIds(@RequestParam String ids) {
return "IDs: " + ids;
}
Copy the code
Through the browser check http://localhost:8080/pig? Ids =10085 ids=10085
- for
@PathVariable
Extract the value from the URI path
@GetMapping("/pig/{id}")
public String getPigById(@PathVariable String id) {
return "ID: " + id;
}
Copy the code
Through the browser to check http://localhost:8080/pig/10085 for the ID of the value is: 10085
Encoding and exact values
For @pathvariable to extract the roadbed value from URI, it is not encoded.
http://localhost:8080/pig/he+llo
----
ID: he+llo
Copy the code
However, for @requestParam extracting values from the query string is coded. This parameter is URL decoded:
http://localhost:8080/pig?id=he+llo
----
ID: he llo
Copy the code
An optional value
Both @requestParam and @pathVariable are optional.
Starting with Spring 4.3.3, we can use the necessary attributes to make @pathVariable optional:
@GetMapping({"/mypig/optional", "/mypig/optional/{ids}"})
public String getPigByIds(@PathVariable(required = false) String ids){
return "IDs: " + ids;
}
Copy the code
Execute as follows:
http://localhost:8080/mypig/optional/hello
----
ID: hello
Copy the code
or
http://localhost:8080/mypig/optional
----
ID: null
Copy the code
For @RequestParam, we can also use the required attribute.
Note that care should be taken when making @pathvariable optional to avoid path conflicts. The class header adds @restController and omits @responseBody from the method
conclusion
The foundation is weak, the ground is shaking. Take notes.
reference
gitee-pig
Spring MVC Basics 2
Spring @ RequestParam notation
Spring @requestParam with @pathVariable annotation