2016-03-21 44 views
0

我正在尋找一種方式來捕捉任何URL,如:在Spring(Boot)中使用@RequestMapping和@PathVariable捕獲變量路徑的任何方式?

mydomain.com/first/second/third 
mydomain.com/first/second/third/fourth 
mydomain.com/first/ 

,並能夠抓住它在我的控制器單一的方法,並建立一個字符串的路徑,如:

for (String pathVar : pathVariableArray){ 
    stringToBuild += pathVar + '.' 
} 

,並得到下面的結果:

stringToBuild = "first.second.third." 
stringToBuild = "first.second.third.fourth." 
stringToBuild = "first." 

有什麼辦法?我不想爲不同長度的路徑編寫不同的方法。

回答

1
@RequestMapping("/**") 
public void method(HttpServletRequest request) { 
    String stringToBuild = request.getServletPath().replace("/", ".") + "."; 

對於其他映射方法,請參閱Spring boot - Controller catching all URLs

如果路徑以/結尾,您可能需要更復雜一些,以避免雙重.

+0

您的回答確實有幫助,但我稍作修改。因爲你使用的是通配符,所以你必須使用getServletPath而不是getPathInfo,否則你會得到一個空值。 –

相關問題