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方法
 

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