「掘金者说」Spring中@RequestParam与@PathVariable区别

2,755 阅读2分钟

掘金者说,我无法预先把现在所发生的的点点滴滴串联起来,只有在未来回头今日时,我才会明白这些点点滴滴是如何串在一起的。所以,我必须相信:眼前现在发生的点点滴滴,将来都会连结在一起的。 也许当下我可能不知道,写这个东西是好还是浪费时间...但是将来回过头来看,就会知道一路走来都是值得。因为每个过程都成为了现在的你~

回头来看,平常都使用两个批注进行接收参数传递,要区分一下他们之间的关系和区别,还是需要找找材料,自己动手验证然后整理加固印象。那么@RequestParam@PathVariable之间的区别,他们都可以用于请求URI中提取值,但是他们有些不同。

查询参数与URL路基

  • 对于@RequestParam从查询字符串中提取值
@GetMapping("/pig")
public String getPigByIds(@RequestParam String ids) {
    return "IDs: " + ids;
}

通过浏览器查看http://localhost:8080/pig?ids=10085获取的IDs值为:10085]

  • 对于@PathVariable提取从URI路径值
@GetMapping("/pig/{id}")
public String getPigById(@PathVariable String id) {
    return "ID: " + id;
}

通过浏览器查看http://localhost:8080/pig/10085获取的ID值为:10085

编码与精确值

对于@PathVariable提取从URI路基值,是没有对其进行编码。

http://localhost:8080/pig/he+llo
----
ID: he+llo

但是,对于@RequestParam从查询字符串中提取值是需要进行编码。该参数是URL解码的:

http://localhost:8080/pig?id=he+llo
----
ID: he llo

可选值

无论@RequestParam@PathVariable可选配。

从Spring 4.3.3开始,我们可以使用必需的属性使@PathVariable成为可选属性:

@GetMapping({"/mypig/optional", "/mypig/optional/{ids}"})

public String getPigByIds(@PathVariable(required = false) String ids){
    return "IDs: " + ids;
}

执行,如下:

http://localhost:8080/mypig/optional/hello
----
ID: hello

或者

http://localhost:8080/mypig/optional
----
ID: null

对于@RequestParam,我们还可以使用required属性。

注意 在使@PathVariable为可选时,我们应格外小心,以避免路径冲突。
类头添加@RestController在方法中省略@ResponseBody

结论

基础不牢,地动山摇,记下笔记。

参考

gitee-pig

Spring MVC基础2

Spring @RequestParam批注

Spring @RequestParam与@PathVariable批注