SpringBoot、SpringMVC编写RESTFull接口使用正则表达式匹配

  •  正则表达式的写法如下:
 @RequestMapping(value = "/{name:(?!fonts|oauth|webjars|swagger|images)[a-z][0-9a-z-]{3,31}}/**",method = {RequestMethod.POST, RequestMethod.GET})
    public void homePage(HttpServletRequest request, HttpServletResponse response ,@PathVariable String name)  {

}

 表示name满足4--32位以字母开头的字母与数字字符,并且不包括fonts、oauth、webjars、swagger、images这几个词。

 

  • 系统访问的url在后台有多个接口匹配时,定义最精确的会被匹配。

如:

@RequestMapping(value = "/{name:([a-z][0-9a-z-]{3,31}}/**",method = {RequestMethod.GET})

public void test1(@PathVariable String name){

}

@RequestMapping(value = "/{name:([a-z][0-9a-z-]{3,31}}/mytest",method = {RequestMethod.GET})

public void test2(@PathVariable String name){

}

@RequestMapping(value = "/test/mytest",method = {RequestMethod.GET})

public void test3(){

}

访问接口  /test/mytest 时,虽然三个接口都满足,但是请求会到test3方法

访问接口/myapi/mytest时,请求会到test2方法
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章