URL @PathVariable 变量匹配原理
url 中带有变量的匹配原理
在设置url的路径中我们可能使用变量来提高路径的灵活性,如
@RequestMapping(value="/{str}/qian",method=RequestMethod.GET) @ResponseBody public String qianStr(@PathVariable String str){ return "qianStr:"+str; }
然后在输入 http://localhost:8080/zhende/qian 路径的时候就可以匹配上 qianStr 方法,但是却一直没有细想过具体是怎么实现这个匹配的。
开始预测是通过正则表达式来匹配路径就行,但问题是我输入的是 /zhende/qian 怎么匹配到 /{str}/qian 呢,还是想不通,所以通过写个demo 调试来看怎么匹配的,过程如下:
Demo
使用springboot 来写个简单的web
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller() @RequestMapping("/get") public class TestController { @RequestMapping(value="/li", method = RequestMethod.GET) @ResponseBody public String test(){ return "test"; } @RequestMapping(value="/{str}",method=RequestMethod.GET) @ResponseBody public String li(@PathVariable String str){ return "li:"+str; } @RequestMapping(value="/qian/{str}",method=RequestMethod<em>本文来源gao.dai.ma.com搞@代*码(网$</em>.GET) @ResponseBody public String qianStr(@PathVariable String str){ return "qianStr:"+str; } @RequestMapping(value="/{str}/qian",method=RequestMethod.GET) @ResponseBody public String strQian(@PathVariable String str){ return "strQian:"+str; } }
上边写啦好几个路径以便我们更好的比对匹配过程。
调试如下
启动服务后输入如下路径:
可以看到 左边的调用栈中 有 DispatcherServlet 分派调用过来的,所以查看DispatcherServlet 关联代码 由mappedHandler处理的所以在DispatcherServlet 中加入断点再次调试。